Monday, May 24, 2010

How to hide parent class method from child class in c#.net?

Make it private, or if it needs to be accessed by other classes but not inheritable, make it public sealed.

How to hide parent class method from child class in c#.net?
Sometimes you may want to create your own implementation of a method that exists in a base class. The Child class does this by declaring its own xyz() method. The Child xyz() method hides the Parent xyz() method. The effect is the Parent xyz() method will not be called, unless we do something special to make sure it is called.





Inside the Child xyz() method, we explicitly call the Parent xyz() method. This is done by prefixing the method name with "base.". Using the base keyword, you can access any of a base class public or protected class members.


Another way to access base class members is through an explicit cast. This is done in the last statement of the Child class Main() method. Remember that a derived class is a specialization of its base class. This fact allows us to perform a cast on the derived class, making it an instance of its base class.


Notice the new modifier on the Child class xyz() method. This enables this method to hide the Parent class xyz() method, thus explicitly preventing polymorphism. Without the new modifier, the compiler will produce a warning to draw your attention to this. I'm sugesting on reading more about polymorphism.


No comments:

Post a Comment