Skip to content

Instantly share code, notes, and snippets.

@EvanCarroll
Created July 18, 2009 22:02
Show Gist options
  • Save EvanCarroll/149703 to your computer and use it in GitHub Desktop.
Save EvanCarroll/149703 to your computer and use it in GitHub Desktop.
C# - sohws the effect of virtual/overide vs new
using System;
namespace ConsoleView
{
public class Base {
public virtual void View() {
Console.WriteLine("Viewing Base, Original virtual View");
}
public void ViewNew() {
Console.WriteLine("Viewing Base, Original OLD ViewNew ;)");
}
}
public class Child : Base {
public override void View() {
Console.WriteLine("Viewing Child, override View");
}
public virtual new void ViewNew() {
Console.WriteLine("Viewing Child, new ViewNew");
}
}
class Implementor {
[STAThread]
static void Main(string[] args) {
{
Console.WriteLine("\n\n*****\nNow running the against the Child");
Child myChild=new Child();
Console.WriteLine("The reference now is a Child that refers to a child. Typical, ha?!");
myChild.View();
myChild.ViewNew();
}
{
Console.WriteLine("\n\n*****\nNow running the against the Child cast as basen");
Base myBase=(Base)new Child();
Console.WriteLine("The reference now is a Base, yet it still refers to a child");
myBase.View();
myBase.ViewNew();
}
Console.Read();
}
}
}
/**
To make this clearer, if you cast the child as Base and call the virtual method, you'll still get the overridden version not the virtual (original) one. This happens because override totally replaces the Base virtual method. It doesn't just hide it.
Now, if you leave the original Base method with or without the virtual modifier (it doesn't matter here), and use the new modifier with the Child version of this method, you'll be hiding the original method only when Child is treated as a Child (Not casted as Base). If you cast it as Base, and call the same method, you'll get the original version of the method, not the new one.
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment