Tutorial :C# inheritance


Let's say I have the following code:

interface ISomeInterface  {      void DoSomething();      void A();      void B();      }    public abstract class ASomeAbstractImpl : ISomeInterface  {      public abstract void A();      public abstract void B();      public void DoSomething()      {          // code here      }  }    public class SomeImpl : ASomeAbstractImpl   {      public override void A()      {          // code      }        public override void B()      {          // code      }  }  

The problem is that i wish to have the ASomeAbstractImpl.DoSomething() method sealed (final) so no other class could implement it. As the code is now SomeImpl could have a method called DoSomething() and that could be called (it would not override the method with the same name from the abstract class, because that's not marked as virtual), yet I would like to cut off the possibility of implementing such a method in SomeImpl class.

Is this possible?


Methods in C# are sealed by default. There is, however, nothing you can do to prevent method hiding (exposing a method with the same name in the derived class, commonly with new).

Or, for that matter, interface-reimplementation:

static void Main()  {      ISomeInterface si = new EvilClass();      si.DoSomething(); // mwahahah  }    public class EvilClass : ASomeAbstractImpl, ISomeInterface  {      public override void A() {}      public override void B() { }      void ISomeInterface.DoSomething()      {          Console.WriteLine("mwahahah");                  }  }  


All methods are sealed by default, but there's no way of preventing Member Hiding.

The C# compiler will issue a compiler warning whenever you hide a member, but apart from that, you can't prevent it.


A method which is not marked as virtual is sealed by default. In a derived class you have to mark a "overriding" method with the keyword new, else you'll get a compiler warning. If the method of the super class is marked as virtual, you can seal it per sealed override.



if SomeImpl class contains DoSemthing method, this means it hides the original one not override.


When dealing with interfaces and abstract classes its more about what you MUST do and not what you cannot do. So you can let the interface user know that these are the methods they must implement and with your abstract classes you can use the virtual keyword to let them know its OK to override a method. However you can't stop them from doing too much. Even if you purposefully don't use the virtual keyword they can still hide it with the new keyword.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »