It can be argued that the most important difference about virtual is that it calls the compiler when the method member is called polymorphically , which compiles the code to bind. When you call a class member from client code, where the actual type of the object is, for example, the derived class is foo , but the variable it calls is actually typed (declared) as some base class, say bar , Members declared as virtual will be bound to the implementation in the actual type of the object (or to the most derived base class of an object type that has an implementation). Members not declared as virtual will be bound to the implementation in the type declared by the variable.
a. Virtual then, if the member is declared as virtual, the implementation in the derived class will be executed, even if the variable is declared as the base type.
public class Animal { public virtual Move() { debug.Print("Animal.Move()"); } public class Bird: Animal { public virtual override Move() { debug.Print("Bird.Move()"); } Animal x = new Bird(); x.Move();
B. Not virtual . If a member that is not declared as virtual , then the implementation will be selected based on the declared type of the variable in which the method is executed. Therefore, if you have a Bird object in the x variable declared as "Animal" and you call the method implemented in both classes, the compiler is bound to the implementation in the Animal class, not in Bird, although the object is really a Bird.
public class Animal { public Move() { debug.Print("Animal.Move()"); } public class Bird: Animal { public Move() { debug.Print("Bird.Move()"); } Animal x = new Bird(); x.Move();
source share