It is asked very frequently, that how can we call the parent version of a method in inheritance. In C# we can use
new keyword to define a new method in child class and get this effect. I have mentioned a little example that will illustrate you the difference between override and new keyword :
//Calls Base class function 1 as new keyword is used.
BaseClass bd = new DeriveClass();
bd. function ();
//Calls Derived class function 2 as override keyword is used.
BaseClass bd2 = new DeriveClass();
bd2. function ();
Thank You. Happy coding....
public class Parent {
ReplyDeletepublic virtual void func() {
//nothing...
}
}
public class Child : Parent {
public override void func() {
// Something...
}
}
public class Child2 : Parent {
public new void func() {
// Something...
}
}
public static void main (string[] args) {
Parent p = new Child();
p.func(); // call child class method
p = new Child2();
p.func(); // call parent class method
}
The new modifier is supposed to hide the implementation of the base class. You need to clear your own concepts, before teaching anybody else...
ReplyDeleteSee here for a reference...
http://msdn.microsoft.com/en-us/library/435f1dw2.aspx
@Faheem it is already explained with the code sample I posted above. Let me explain it for you once again.The new operator hides the method implementation of child class i.e. If you create a method with new keyword in child class, then you will not be able to access that method with parent class instance. When you call a method which is overridden, in child class, then that method will be called from parent class reference. I hope this will clear your confusion about new and override keywords. Thank You.
ReplyDelete