Explain About Method Shadowing

These guys were pretty clear about the topic Smile | :) Thumbs up, codeproject is getting better by the day Big Grin | :-D 
 
In addition to those, just a small point of view on why and when you should use new keyword
 
Ok, back to the basics. When you inherit from a class, the methods marked with either public or protected will be available to the child class. right? So while designing, you decide that I might need more expanded behavior or different behavior from these methods. Let's take an example.
public class Bird {
     public void Eat() {
          Console.WriteLine("Eating....");
     }
 
     public virtual void Fly() {
          Console.WriteLine("Flying....");          
     }
}
Few things to notice, since every bird is eating, you know that's not going to change, so you don't intend to change it's behavior in child classes. But some birds can't fly, so you know it's going to change, so you are marking that method with virtual keyword. You can achieve the same thing, by abstract classes but it's a different lesson Smile | :) 
 
So let's implement 2 birds classes
public class Robin : Bird {
     public override void Fly() {
          Console.WriteLine("Flying Fast....");
     }
}
public class Ostrich : Bird {
     public override void Fly() {
          Console.WriteLine("Cannot fly");
     }
}
Now, I am going do something crazy Big Grin | :-D Laugh all you want, but I could not come up with a better example this quickly. But I know it'll help you understand the concept.
 
So let's imagine, you are want to include disabled birds who can't eat. Now this was not expected in the original design. I.e. it was not intended in the design. So you can go back to the original design and decorate the Eat() method with override.
 
But this is not possible when you are using someone else's code. I.e. you don't have the source code to edit and update but only the compiled DLL. So now what? That's where new keyword helps you out.
public class DisabledBird : Bird {
     public override void Fly() {
          Console.WriteLine("Cannot fly :(");
     }
 
     public new void Eat() {
          Console.WriteLine("Cannot eat :(");
     }
}
The new keyword serves 2 purposes.
1. Allows you to hide methods of parent classes and implement a different method for the same signature. 
2. Allows you to keep track of methods that you did like that. So that it would not confuse you when you look in to the code later on.
 
NOTE: This is NOT mean that you should not design your code or overriding can be just ignored. If you do that, you'll quickly lose the ability to maintain your code. This should be only used for exceptional cases like when you are using a toolkit or a library.
 
Damn, this turned out to be an article :P Apologies

0 comments:

Post a Comment