Wednesday, May 26, 2010
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



7 comments:

Anonymous said...

Thanks!

Anonymous said...

Nice post.

أبوعصر said...

جزاك الله خيراً والى الأمام

Anonymous said...

Finally! You explain this better than Microsoft!

suresh said...

really nice ..thanks a lot

Anonymous said...

thx.. see also. http://msdn.microsoft.com/en-US/library/ms173153(v=vs.80).aspx

Anonymous said...

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

Search

Loading...