Here is the program and results, we will see how the virtual and new goes.
public class MyBase
{
public virtual string MyVirtualMethod()
{
return "Base";
}
public string MyNonVirtualMethod()
{
return "Base";
}
} //end of sub class
public class MyDerived : MyBase
{
public override string MyVirtualMethod()
{
return "Derived";
}
public new string MyNonVirtualMethod()
{
return "Derived";
}
} //end of sub class
--------------------------------------------------------------------------------
MyBase m1 = new MyDerived();
Console.WriteLine("MyVirtualMethod='" + m1.MyVirtualMethod() + "', MyNonVirtualMethod='" + m1.MyNonVirtualMethod() + "'");
// Returns: MyVirtualMethod='Derived', MyNonVirtualMethod='Base'
MyDerived md = new MyDerived();
Console.WriteLine("MyVirtualMethod='" + md.MyVirtualMethod() + "', MyNonVirtualMethod='" + md.MyNonVirtualMethod() + "'");
// Returns: MyVirtualMethod='Derived', MyNonVirtualMethod='Derived'
----------------------------------------------------------------------------------
the difference bewteen abstract and virtual:
1. abstract method must use in the abstract class, and is required no implement.
2. in the derived class, both of them can be override.
however, virtual method has other two choice, new and do nothing.
Virtual | Abstract | |
Has implementation | Yes | No |
Scope | members only | members and classes |
Can create an instance of | Not Applicable (you can only create instances of classes, not members) | No - but you can create an instance of a class that derives from an abstract class. And you can declare a type Abstract class and instantiate that as a derived class. |
PS:
reference by http://timstall.dotnetdevelopersjournal.com/tips_with_oop__new_virtual_and_abstract.htm