interviews.dotnetthread.com

↑ Grab this Headline Animator

Friday, April 9, 2010

What is Method Hiding?

Method hiding is to hide/mask method in base class by creating a similar function in derived class and by using new keyword in the derived class.
Unlike Method overriding, When we refer base class object created by casting derived class object a method in base class will be called.
Also we can change the return type while masking the base class method.
Using new keyword is not compulsory, however a warning will be displayed if we wont specify new keyword while masking.


Example:

Base Class:
--------------
public class BaseClass
{
public virtual void Method1()
{
Print("Base Class Method");
}
}

Derived class
---------------
public class DerivedClass: BaseClass
{
public override void Method1()
{
Print("Derived Class Method");
}
}

Usage
-------------------
public class Sample
{
public void TestMethod()
{
DerivedClass objDC = new DerivedClass();
objDC.Method1();
BaseClass objBC = (BaseClass)objDC;
objDC.Method1();
}
}
Result
-----------------------------------
Derived Class Method
Base Class Method

Submit this story to DotNetKicks

No comments:

Post a Comment

Post your comments/questions/feedback for this Article.

 

Latest Articles