Say I have the following code:
class Parent
{
static string MyField = \"ParentField\";
public virtual string DoSomething()
{
return MyField
You have to handle this in Child, too:
class Child
{
static new string MyField = "ChildField";
public override string DoSomething()
{
return MyField;
}
}
That being said, using a single virtual property would probably be a cleaner design, since you wouldn't need the "new" keyword to hide the Parent's member field.
I don't get why you think you need both "static" and "non-static" environments to call different properties/functions that return the same thing. If you just do this:
class Parent
{
public virtual string DoSomething()
{
return "ParentField";
}
}
class Child
{
public override string DoSomething()
{
return "ChildField";
}
}
Then this will work like you want:
Child c = new Child();
Console.WriteLine(c.DoSomething());
And instead of writing this:
Console.WriteLine(Parent.MyField);
Console.WriteLine(Child.MyField);
you just write this:
Console.WriteLine(new Parent().DoSomething());
Console.WriteLine(new Child().DoSomething());
Is there some other constraint on the problem that makes this unacceptable? Is creating new objects of these classes extremely expensive for some reason, for example?
First, let me say that you really should just make MyField virtual and accept that you need to spawn an instance to get it. However, another way of "solving" the problem would be:
class Parent
{
public static string MyField = "ParentField";
protected virtual MyLocalField = MyField;
public virtual string DoSomething()
{
return MyLocalField;
}
}
class Child : Parent
{
public static new string MyField = "ChildField";
protected override MyLocalField = MyField;
}
If you find yourself requiring a construct not supported by the language, in this case static virtual
members, that is a smell, indicating you might have a faulty design.
Instead of showing us a solution, show us the problem you are trying to solve with that solution. My guess is that there is a totally different design that eliminates the need for this oddity.
Put another way: the answers you've received aren't the ones you want because the question you asked is not really the question you should be asking. I can think of no situation where the proposed design offers benefits that another, more conventional design does not.
In one response you seem to indicate that the static field is constant. If that is the case, then this should work for you.
class Parent
{
protected virtual string MyField() { return "ParentField"; }
public virtual string DoSomething()
{
return MyField();
}
}
class Child : Parent
{
protected override string MyField() { return "ChildField"; }
}
There's no inheritance magic on anything static but you could dó this
protected virtual string { get { return "your value"; } }
and use the property inside your method