0

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"

Prodigle
  • 1,757
  • 12
  • 23

2 Answers2

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();
user2147873
  • 107
  • 5
  • That will also return `TRACKED`. The `new` is on the property, not the method. – Charles Mager Apr 06 '22 at 14:23
  • `new` is never an override. – ProgrammingLlama Apr 06 '22 at 14:25
  • Yeah, I assumed there wouldn't be a nice way around it, Handling these objects as the BaseClass with no easy way to know the derived, will just have to look for another method to do what I'm doing – Prodigle Apr 06 '22 at 14:40
  • @CharlesMager, o yes ... indeed it still returns TRACKED. it was a surprised for me . thx! – user2147873 Apr 06 '22 at 14:40
  • @Prodigle maybe what you need is affordable with overwriting, not new.. class Base { virtual GetX() => "XXXX"}, Derived:Base { override GetX() => "YYY" } – user2147873 Apr 06 '22 at 14:42
  • @user2147873 Appreciate the help but this was just a micro problem in a much bigger one haha, of needing both a virtual & (somehow virtual) static function to return the same string (different for each subclass). Have now found a way around it (and it is an absolute mess and uses Reflection) – Prodigle Apr 06 '22 at 15:08
-1

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.

StepUp
  • 36,391
  • 15
  • 88
  • 148