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

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"



Solution 1:[1]

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

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2