A derived class that uses the "new" keyword for a method instead of "overriding" will behave differently depending on how it is executed.
Example:
class Class1 { public virtual void DoSomething { Console.WriteLine("Class1.DoSomething"); } } class Class2 : Class1 { public new void DoSomething { Console.WriteLine("Class2.DoSomething"); } } class Class3 : Class1 { public override void DoSomething { Console.WriteLine("Class3.DoSomething"); } }
Classes 2 and 3 come out of class 1, but class 2 uses the keyword "new" to "hide" the virtual member of class 1, while class 3 uses the keyword "override" to "override" the virtual member of class 1. Here's what happens when you use these classes as your own types:
Class1 one = new Class1(); one.DoSomething(); // outputs "Class1.DoSomething" Class2 two = new Class2(); two.DoSomething(); // outputs "Class2.DoSomething" Class3 three = new Class3(); three.DoSomething(); // outputs "Class3.DoSomething"
They all return the correct class name, as expected. But this is what happens when you use these classes as class 1:
Class1 one = new Class1(); one.DoSomething(); // outputs "Class1.DoSomething" Class1 two = new Class2(); two.DoSomething(); // outputs "Class1.DoSomething" Class1 three = new Class3(); three.DoSomething(); // outputs "Class3.DoSomething"
Since class 2 "hides" the method, it will output "Class2.DoSomething" when used as its own type, but it will output "Class1.DoSomething" when used as the base type. But since class 3 "overrides" the method, it outputs "Class3.DoSomething" whether it is used as its own type or as the base type, because it "redefines" the functionality of the base type.
(Another effect of this is that if Class2
or Class3
have an additional method, say DoSomethingElse
, you cannot call Class1 two = new Class2(); two.DoSomethingElse()
because Class1
does not have this method.)
I don't know about any real use cases for this, but it is, and this is the only way I can think that using Class1 class2 = new Class2()
will offer any real use. If Class2
does not βhideβ any members of Class1
, then there is no real benefit.
See: http://msdn.microsoft.com/en-us/library/ms173153.aspx