0

What is the use of virtual keyword in C#?

When to use virtual keyword? What is the purpose of virtual keyword in C#?

23rd Mar 2021, 2:18 PM
Mahesh Muttinti
Mahesh Muttinti - avatar
1 Answer
+ 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.
23rd Mar 2021, 2:57 PM
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ - avatar