override public class Base { public virtual void SomeMethod() { //print base } } public class Derived : Base { public override void SomeMethod() { //print child } } //... Base b = new Derived(); b.SomeMethod(); | new public class Base { public virtual void SomeOtherMethod() { //print base } } public class Derived : Base { public new void SomeOtherMethod() { //print child } } //... Base b = new Derived(); Derived d = new Derived(); b.SomeOtherMethod(); d.SomeOtherMethod(); |
Out put | Out put |
Child | base Child |
So what’s the matter:
Virtual keyword makes the method on the base type prone (عرضة) to any derived ones override it by writing override keyword before it
So when calling it from the parent object, parent object looks for if any overrides exists to implement it and eliminates the current virtual method code
But the new keyword make a new version from the method actually it’s a new one at all;
So when calling it on the parent object, although it was initialized by a child one, but now this method (public new void SomeOtherMethod()) is another one totally so the parent object implements its own method
End of the story;
C# fast-food by:
Eng.Waleed abou-zaid
Senior Software Developer
Harf Information Technology
MCSD.Net,MCAD.Net,MCP,A+,N+ certified
walid.abouzaid@gmail.com
Blog Archive
-
▼
2010
(55)
-
▼
May
(21)
- SharePoint in Plain English
- Practices for Testing Code
- Why we should move to visual studio 2010 ?
- [[ C# FastFood ]] What's AppDomain?
- [[ c# FastFood ]] Call Hierarchy of Methods (VS201...
- [[ c# FastFood ]] Difference between override and ...
- Why IT Projects Fail ?
- How to consume REST based-services?
- Intelligent Traffic Light System
- <<C# FastFood>> Generic types are not inherited
- <<C# FastFood>> CallBack better than PostBack
- <<C# FastFood>>[Did U use TimeStamp SqlDataType be...
- (C# FastFood) How to hide part of the partial clas...
- <<C# FastFood>>Static ClientID (ASP.Net 0.4)
- <<C# FastFood >> Singletone Design Pattern
- <<C# FastFood>>Parallel.For & Parallel.Foreach
- <<C# FastFood>>C# 4.0 new features
- <<C# FastFood>> Smartness of calling by REF
- 5 Top jQuery Plugins to improve Your HTML
- نظام فلير لحماية المنشأت والمبانى
- Day In A Life ( software as services )
-
▼
May
(21)

7 comments:
Thanks!
Nice post.
جزاك الله خيراً والى الأمام
Finally! You explain this better than Microsoft!
really nice ..thanks a lot
thx.. see also. http://msdn.microsoft.com/en-US/library/ms173153(v=vs.80).aspx
This is almost identical to the 2004 post:
http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-s-the-difference-between-code-override-code-and-code-new-code.aspx
Post a Comment