Home > Software design >  Which hidden static field will a derived class object return using the base class getter
Which hidden static field will a derived class object return using the base class getter

Time:04-07

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"

CodePudding user response:

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();

CodePudding user response:

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.

  • Related