I am trying to figure out a way I can make use of private
static
fields in a generic class
. This is the obvious way to do it (fiddle). It won't compile because Field
is not accessible in BaseChild
, and ideally I wouldn't want it to be accessible there:
public class Base<T>
{
private static readonly string Field = "field";
public Base()
{
Console.WriteLine(Field);
}
}
public class BaseChild : Base<string>
{
public BaseChild()
{
Console.WriteLine(Field);
}
}
The problem with this solution is that there is a different Field
for each generic type, instead of being shared across them.
I have seen this answer where it says that JetBrains recommends a solution for static
fields across generic types:
If you need to have a static field shared between instances with different generic arguments, define a non-generic base class to store your static members, then set your generic type to inherit from this type.
This makes sense for the case where you have public
or protected
static
fields in the base
class that you want to share across any child class
like this example (fiddle):
public abstract class Base
{
protected static readonly string Field = "field";
}
public class Base<T> : Base
{
public Base()
{
Console.WriteLine(Field);
}
}
public class BaseChild : Base<string>
{
public BaseChild()
{
Console.WriteLine(Field);
}
}
However, what about the case where you want to use a private
static
field? I would guess that this is not possible since private
means only accessible to the class
it's declared in and I think that since the generic class
is really just a template to create a class
, that any private
field could only ever be shared by each class
, not across all the classes created by the template.
Do I have to just put the private
field in the generic class (example 1) and accept it as at least a workable solution for what I want, or is there another way I can accomplish this?