Method Hiding in C# with Example

Method Hiding in C# with Example
Rating: 5 - 1 Votes

Method Hiding in C# with Example

Method Hiding in C# with Example

Method Hiding in C# with Example

As per inheritance in C#, derived class have access to all the code available in base class, which means all the public methods available in the base class are accessible through derived class object.  But in some cases, derived class contains a method which is similar by name and signature to the method available in base class.  Now, when you create a derived class subject and try to call that method, the derived class method will be called because C# compiler automatically hides the base class method.  But it is a good practice to use new keyword if your hiding is intentional.  This process known as method hiding where we use new keyword to intentionally hide the method available in base class.

Output:

Method from Derived Class
Press any key to continue . . .

Now, in this case, a question arises what if you want to call the base class method instead of derived class method using derived class object?  There are 3 ways which you can use to call the base class method.

First way, you can use base keyword to call base class method from derived class method (base.methodname).

 Output:

Method from Base Class
Press any key to continue . . .

Second way, you can type cast derived class object using base class name (((base name)derived object).methodname).

 Output:

Method from Base Class
Press any key to continue . . .

Third way, you can create a base class reference variable which will point to the derived class object because a derived class has access to all the code available in base class.  But a derived class reference variable cannot point to the base class object because a base class does not have access to all the code available in derived class.

 Output:

Method from Base Class
Press any key to continue . . .