inherited static readonly fields

R

Ranier Dunno

Hi,

I have a class hierarchy, and would like all classes in
the tree to have a common, static readonly variable -
with a class-specific value. I'd like it to be readonly
(it should never change), but this prevents me from
setting its value in the static constructor of the
subclasses - I'm allowed to set its value in the
superclass constructor only.

Any suggestions as to what would be a good solution?

An example is provided below:

public class A
{
public static readonly string MyString;

static A
{
MyString = "Hello, World!"; // This is OK.
}
}

public class B : A
{
static B
{
MyString = "Bonjour, Le Monde!"; // This is NOT.
}
}
 
J

Jon Skeet [C# MVP]

Ranier Dunno said:
I have a class hierarchy, and would like all classes in
the tree to have a common, static readonly variable -
with a class-specific value.

That's not going to happen, basically.
I'd like it to be readonly
(it should never change), but this prevents me from
setting its value in the static constructor of the
subclasses - I'm allowed to set its value in the
superclass constructor only.

It wouldn't help you even if you could set it in your derived type's
static constructor - if you declare a static variable in the base type,
there's only one variable however many derived types you have.
Any suggestions as to what would be a good solution?

Have a map from type (or typename) to value instead, and make each
class set the value for itself in its static constructor. If you make
the map itself private and give a public readonly property to fetch the
value, and a protected method to write the value, you should be okay.
 
R

Ranier Dunno

-----Original Message-----


That's not going to happen, basically.


It wouldn't help you even if you could set it in your derived type's
static constructor - if you declare a static variable in the base type,
there's only one variable however many derived types you
have.

D'oh! Hadn't even thought about that problem :/
Have a map from type (or typename) to value instead, and make each
class set the value for itself in its static constructor. If you make
the map itself private and give a public readonly property to fetch the
value, and a protected method to write the value, you
should be okay.


Brilliant workaround! You the man! :-D
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top