Which hidden static field will a derived class object return using the base class getter

76 views Asked by At

I realize this is maybe a bit confusing to explain.

In my BaseClass:

public static string SaveDataType => "TRACKED"; 
public string GetSaveDataType => SaveDataType;

In my DerivedClass:

public new static string SaveDataType => "COUNTER";

What will the follow return?

BaseClass x = new DerivedClass();
x.GetSaveDataType();

I'd like it to return correctly "COUNTER"

2

There are 2 answers

6
user2147873 On

BaseClass does not know the new static... so new is not an override.. if you want it to have the "correct" COUNTER. downcast to the derived...

(x as DerivedClass)?.GetSaveDataType();
0
StepUp On

As msdn artcile says about "What's the difference between override and new":

if you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it

So your code would like this:

class BaseClass
{
    public virtual  string SaveDataType => "TRACKED";
    public string GetSaveDataType => SaveDataType;
}

class DerivedClass : BaseClass
{
    public override string SaveDataType => "COUNTER";
}

and it can be called like this:

BaseClass x = new DerivedClass();
string saveDataTypeest =  x.GetSaveDataType;

Just in case if you are curious why it does not make sense to create static overridable methods.