C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: The virtual modifier tells the compiler that when any class derived from class A is used, an override method should be called.
OverrideInfo: With virtual methods, the runtime type is always used to determine the best method implementation.
In Main: Ref1 has a compile-time and runtime type of A. On the other hand, ref2 has a compile-time type of A but a runtime type of B.
C# program that introduces virtual method
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();
}
}
Output
A.Test
B.Test
Thus: No virtualized entry point is ever required. And a private virtual method is not useful.
Here: We see both a program that attempts to use a private virtual method member, as well as the compile-time error.
Note: The error occurs during the static compilation phase. No program that declares a private virtual method will ever be executed.
C# program that uses private virtual method
class A
{
private virtual int Test()
{
return 1;
}
}
class Program
{
static void Main()
{
}
}
Output
Error 1
'A.Test()': virtual or abstract members cannot be private
And: You can provide a standard (base) type and design around that type. Then add methods for the more specific (derived) types.
So: When you call a method on the base type, you invoke the more derived (and useful) method.
Note: This enables you to clearly separate the usage of the type from the implementation of each subtype.
Info: If you are already inside the type, you can simply call a regular instance private method.