use of 'new' keyword in functions

  • Thread starter Thread starter Micus
  • Start date Start date
M

Micus

I was wondering what the thought behind the 'new' keyword was in C# when
applied to a function? For Example :

public class A
{ ...
public virtual void Func() { // impl_A}
.... }

public class B : A
{ ...
public override void Func() { // impl_B}
.... }

public class C : B
{ ...
public override void Func() { // impl_C}
.... }

public class D : B
{ ...
public new void Func() { // impl_D}
.... }

// use classes - polymorphism
A[4] objArray = {new A(), new B(), new C(), new D() };
objArray[0].Func(); //impl_A called
objArray[1].Func(); //impl_B called
objArray[2].Func(); //impl_C called
objArray[3].Func(); //impl_B called *not impl_D

D objD = new D();
D.Func(); //impl_D called *

In what situation would you want this behavior? On the surface, it appears
the only time 'new' would make sense is when a class is inherited and you
want to 'override' a function, but the function is not overridden when
polymorphism is applied.???

I did find a previous post from Jan/04 covering this but it is no longer
available (sorry about the repeat).

Thanks for your time,
M
 
You use new when you want/must add a method to a class (e.g. when
implementing interfaces) and *do not* want to override the original one. But
you can also reach this behaviour with explicit interface implementation so
I really cannot say that I know an example where you actually want such a
behaviour.
 
cody said:
You use new when you want/must add a method to a class (e.g. when
implementing interfaces) and *do not* want to override the original one. But
you can also reach this behaviour with explicit interface implementation so
I really cannot say that I know an example where you actually want such a
behaviour.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Micus said:
I was wondering what the thought behind the 'new' keyword was in C# when
applied to a function? For Example :

public class A
{ ...
public virtual void Func() { // impl_A}
... }

public class B : A
{ ...
public override void Func() { // impl_B}
... }

public class C : B
{ ...
public override void Func() { // impl_C}
... }

public class D : B
{ ...
public new void Func() { // impl_D}
... }

// use classes - polymorphism
A[4] objArray = {new A(), new B(), new C(), new D() };
objArray[0].Func(); //impl_A called
objArray[1].Func(); //impl_B called
objArray[2].Func(); //impl_C called
objArray[3].Func(); //impl_B called *not impl_D

D objD = new D();
D.Func(); //impl_D called *

In what situation would you want this behavior? On the surface, it appears
the only time 'new' would make sense is when a class is inherited and you
want to 'override' a function, but the function is not overridden when
polymorphism is applied.???

I did find a previous post from Jan/04 covering this but it is no longer
available (sorry about the repeat).

Thanks for your time,
M
 
Back
Top