The Difference Between New and Override
This is a fundamental topic in C# and if you plan to do any development at all with the language you need to know this. Override is used for changing the behavior of the original type’s method or property. The new keyword, in this case, is used for scratching the existing behavior but only in the current type. To better explain this, consider the following code.
1 2 3 4 5 6 7 8 9 10 11 | public class Foo{ public virtual void Print(){ Console.WriteLine("I am a Foo!"); } } public class Bar{ public override void Print(){ Console.WriteLine("I am a Bar!"); } } |
If we declare a Bar and cast it to a Foo in the above code, we will still get “I am a Bar!” when we invoke the Print method. However, if we change the code to the following things will get messed up a bit.
1 2 3 4 5 6 7 8 9 10 11 | public class Foo{ public void Print(){ Console.WriteLine("I am a Foo!"); } } public class Bar{ public new void Print(){ Console.WriteLine("I am a Bar!"); } } |
If we instantiate a Bar, we will get the new functionality. However, if we cast that Bar object into a Foo, we will get the implementation provided by the Foo. So be sure of what you are using and why!
No Comments
No comments yet.
RSS feed for comments on this post.
Leave a comment
You must be logged in to post a comment.
