Consider the runtime types of things in a C# program. With a virtual
call, an object's most derived type is used for a method invocation.
A virtual
method can be redefined. The virtual
keyword designates a method that is overridden in derived classes. We can add derived types without modifying the rest of the program.
Class
A has a public virtual
method called Test. Class
B, meanwhile, derives from class
A and it provides a public override
method called Test as well.
virtual
modifier tells the compiler that when any class
derived from class
A is used, an override
method should be called.virtual
methods, the runtime type is always used to determine the best method implementation.using System; class A { public virtual void Test() { Console.WriteLine("A.Test"); } } class B : A { public override void Test() { Console.WriteLine("B.Test"); } } class Program { static void Main() { // Compile-time type is A. // Runtime type is A as well. A ref1 = new A(); ref1.Test(); // Compile-time type is A. // Runtime type is B. A ref2 = new B(); ref2.Test(); } }A.Test B.Test
virtual
Private virtual
methods cannot be declared in the C# language. For private methods, you have already entered the data object.
virtual
method is not useful.virtual
method member, as well as the compile-time error.static
compilation phase. No program that declares a private virtual
method will ever be executed.class A { private virtual int Test() { return 1; } } class Program { static void Main() { } }Error 1 'A.Test()': virtual or abstract members cannot be private
Why would you need to use virtual
methods? Your program may be designed in such a way that you do not know all the types of objects that will occur when it is executed.
The term abstract
refers to a conceptual type. It has no implementation. An abstract
class
then is used as a template for derived classes.
Virtual methods are an implementation of type-based polymorphism. This gives you a dynamic entry point to the class
type.
Instance and static
methods are faster to invoke than interface
and virtual
methods. Speed is important in many programs.
Virtual specifies that the method can be overridden in derived types. It tells the compiler to generate code that selects an override
method.