Prodigle
Prodigle

Reputation: 1797

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"

Upvotes: 0

Views: 67

Answers (2)

StepUp
StepUp

Reputation: 38199

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.

Upvotes: -1

user2147873
user2147873

Reputation: 107

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

Upvotes: 1

Related Questions