views:

5423

answers:

9

What is the difference between declaring a method in a base type "virtual" and then overriding it in a child type using the "override" keyword as opposed to simply using the "new" keyword when declaring the matching method in the child type?

+20  A: 

the "new" keyword doesn't override, it indicates that it's a new method that has nothing to do with the base class method.

public class Foo
{
     public bool DoSomething() { return false; }
}

public class Bar : Foo
{
     public new bool DoSomething() { return true; }
}

public cass Test
{
    public static void Main ()
    {
     Foo test = new Bar ();
     Console.WriteLine (test.DoSomething ());
    }
}

This prints false, if you used override it would have printed true.

(Base code taken from Joseph Daigle)

So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE. The only place where you need to use "new" is when the method is not related in any way to the base class version.

AlbertEin
You should revise your code, I had made the methods static (which is valid for using the "new" keyword). But I decided it was clearer to use instance methods.
Joseph Daigle
Thank you, i missed the "static" part. Should take more attention on the future
AlbertEin
+5  A: 

The new keyword actually creates a completely new member that only exists on that specific type.

For instance

public class Foo
{
     public bool DoSomething() { return false; }
}

public class Bar : Foo
{
     public new bool DoSomething() { return true; }
}

The method exists on both types. When you use reflection and get the members of type Bar, you will actually find 2 methods called DoSomething() that look exactly the same. By using new you effectively hide the implementation in the base class, so that when classes derive from Bar (in my example) the method call to base.DoSomething() goes to Bar and not Foo.

Joseph Daigle
+1  A: 

The difference between the override keyword and new keyword is that the former does method overriding and the later does method hiding.

Check out the folllowing links for more information...

MSDN and Other

Nescio
Thanks for the clarification and the valuable links.
i3ensays
+4  A: 

Here's some code to understand the difference in the behavior of virtual and non-virtual methods:

class A
{
    public void foo()
    {
        Console.WriteLine("A::foo()");
    }
    public virtual void bar()
    {
        Console.WriteLine("A::bar()");
    }
}

class B : A
{
    public new void foo()
    {
        Console.WriteLine("B::foo()");
    }
    public override void bar()
    {
        Console.WriteLine("B::bar()");
    }
}

class Program
{
    static int Main(string[] args)
    {
        B b = new B();
        A a = b;
        a.foo(); // Prints A::foo
        b.foo(); // Prints B::foo
        a.bar(); // Prints B::bar
        b.bar(); // Prints B::bar
        return 0;
    }
}
Franci Penov
+1  A: 

Beyond just the technical details, I think using virtual/override communicates a lot of semantic information on the design. When you declare a method virtual, you indicate that you expect that implementing classes may want to provide their own, non-default implementations. Omitting this in a base class, likewise, declares the expectation that the default method ought to suffice for all implementing classes. Similarly, one can use abstract declarations to force implementing classes to provide their own implementation. Again, I think this communicates a lot about how the programmer expects the code to be used. If I were writing both the base and implementing classes and found myself using new I'd seriously rethink the decision not to make the method virtual in the parent and declare my intent specifically.

tvanfosson
+1  A: 

virtual / override tells the compiler that the two methods are related and that in some circumstances when you would think you are calling the first (virtual) method it's actually correct to call the second (overridden) method instead. This is the foundation of polymorphism.

(new SubClass() as BaseClass).VirtualFoo()

Will call the SubClass's overriden VirtualFoo() method.

new tells the compiler that you are adding a method to a derived class with the same name as a method in the base class, but they have no relationship to each other.

(new SubClass() as BaseClass).NewBar()

Will call the BaseClass's NewBar() method, whereas:

(new SubClass()).NewBar()

Will call the SubClass's NewBar() method.

Wedge
+26  A: 

I always find things like this more easily understood with pictures:

Again, taking joseph daigle's code,

public class Foo
{
     public /*virtual*/ bool DoSomething() { return false; }
}

public class Bar : Foo
{
     public /*override or new*/ bool DoSomething() { return true; }
}

If you then call the code like this:

Foo a = new Bar();
a.DoSomething();

NOTE: The important thing is that our object is actually a Bar, but we are storing it in a variable of type Foo (this is similar to casting it)

Then the result will be as follows, depending on whether you used virtual/override or new when declaring your classes.

Virtual/Override Explanation

Orion Edwards
Code comments and pictures! Excellent!
i3ensays
Thanks....but could you please explain a little about picture above with regard to the casting you said?
odiseh
Oops If forgot to add these few line to my prev. comment:do you mean virtual/overriding and non-vitual/new are used just for polymorphysm concept and when you simply declare a variable (not using casting) they don't mean? Thanks again.
odiseh
this answer is exactly what I was looking for. The only problem I had is that flickr images are blocked at my workplace so I had to access it via my phone...
mezoid
A: 

sweet
thanks for that

A: 

very good post about this subject :

http://blog.flair-systems.com/2010/05/c-fastfood-difference-between-override.html

Waleed Mohamed