C# prevent base class method from being hidden by new modifier in the derived class
c#, inheritance
Solution
// How to prevent the following
There is no way to prevent this. It's allowed by the language.
Note that, in practice, this rarely matters. If you expect your base class to be used as your class, your method will still be called. Using `new` only hides the method when using the `DerivedClass` from a a variable declared as `DerivedClass`.
This means that your API, if built around `MyClass`, will always still call `MyMethod` when instances are passed into your methods.
Edit in response to comments:
If you are worried about people subclassing your class in general, the only real option you do have would be to seal your class:
public sealed class MyClass
{
This will prevent people from creating a subclass entirely. If you want to allow people to derive from your class, however, there is no way to prevent them from hiding your method in their class.
Problem
Here's my situation. In Java I can mark a method as final in the base/super class and there is no way a derived class can mask a method of the same signature. In C# however, the new keyword allows someone inheriting my class to create a method with the same signature. See my example below. I need to keep the `orignal.MyClass` public so please don't suggest that as an answer. This seems to be a lost feature moving from Java to C#: ``` public class orignal.MyClass{ public void MyMethod() { // Do something } } class fake.MyClass: orignal.MyClass { // How to prevent the following public new void MyMethod() { // Do something different } } ``` EDIT: Not a duplicate. All answers seem to suggest, it's not possible to prevent a method from being hidden/shadowed in a derived class. This became apparent while migrating some old Java code to C#. A final method in Java will not let anybody use the same method signature in any derived class. While it's great in most scenarios that C# allows a method of same signature in the derived class, it would have been great to prevent such a behavior if warranted.