0
What is the use of virtual keyword in C#?
When to use virtual keyword? What is the purpose of virtual keyword in C#?
1 Respuesta
+ 3
virtual is a keyword related to polymorphism. It's usually paired with the override keyword.
public class A
{
public virtual int f() {return 1;}
}
public class B : A
{
public override int f() {return 2;}
}
Polymorphism basically means having many form, and virtual is one of the ways to do it.
Saying you have this:
A obj;
At some point you do this:
obj.f();
There will be 2 possible output.
1 if obj is initialized with A(),
2 if obj is initialized with B(),
There is third but it's an error which obj is not initialized.