Hiding a base class member produces CS0109 but shouldn't #8940
Replies: 6 comments
-
This seems by-design. The signatures of the two methods are different (one has no parameter and the other does). The https://github.com/dotnet/csharplang/blob/master/spec/classes.md#the-new-modifier |
Beta Was this translation helpful? Give feedback.
-
I hope it's not by design because there is a bug one way or another. Let's see. public class Program
{
public static void Main() => new Derived().DoSomething();
}
public class Base
{
public Task DoSomething() => Task.CompletedTask;
}
public class Derived : Base
{
public Task DoSomething(CancellationToken token = default) => Task.CompletedTask;
} This code is translated into (on SharpLab):
So if Speaking about the second code snippet, the compiler still prefers the method from the derived class, but no warnings are shown (on SharpLab): public class Program
{
public static void Main() => new Derived().DoSomething(42);
}
public class Base
{
public Task DoSomething(int x) => Task.CompletedTask;
}
public class Derived : Base
{
public Task DoSomething(int x, CancellationToken token = default) => Task.CompletedTask;
}
|
Beta Was this translation helpful? Give feedback.
-
It does seem like a scenario the original spec for the 'new' modifier didn't account for. This scenario doesn't meet the definition of 'hiding' used in the spec, but it can make it impossible to call the base member without casting to the base type. |
Beta Was this translation helpful? Give feedback.
-
The compiler is indeed behaving according to spec. Moving to csharplang for the LDM's consideration. |
Beta Was this translation helpful? Give feedback.
-
This is a question for the LDM: should we do anything about this? |
Beta Was this translation helpful? Give feedback.
-
We would like to do this as follows:
Because the latter requires a warning wave, this depends on that compiler feature. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
In the example below the
Derived
type hides a base class member, and there is used keywordnew
to suppress potential CS0108, but as the result CS0109 is produced by the compiler:It might seem that expression
new Derived().DoSomething()
callsBase.DoSomethig()
, but actually the compiler recognizes that the new method should be invoked and generates the correct output.Another example is:
Derived.DoSomething
will be used instead of base class members, but no warning.Language version: 8.0
Compiler version: 3.3.1-beta3-19423-01 (8cf35ae6)
Beta Was this translation helpful? Give feedback.
All reactions