and has 0 comments
Except the obvious one that override cannot be used on methods not declared as virtual, there is the little nag of how the original object will use the method internally. Mainly it will use its own not overriden code, but not the methods that hide its code.

Object A has a method M virtual. B inherits A and overrides method M.
With an instance of B, B.M() will run the code in object B, while M() inside the code of object A will also run the code in object B.

Object A has a method M not virtual. B inherits A and hides method M with a new M method.
With an instance of B, B.M() will run the code in object B, while M() inside the code of object A will run the code originally in object A.

Ex:

public class PrintStuff
{
public PrintStuff() {
PrintMe();
}

public void PrintMe() {
Console.Write('ME!');
}
}

public class PrintStuff2: PrintStuff
{

public new void PrintMe() {
Console.Write('new ME!');
}
}

a code like new PrintStuff2(); will output ME! while a code like new PrintStuff2().PrintMe() will output new ME!

Comments

Be the first to post a comment

Post a comment