C
C#3y ago
Thalnos

✅ Understanding virtual keyword

Hi, I am familiar with inheritance and polymorphism but I struggle to understand the benefit of the virtual keyword. The idea behind the virtual keyword is to be able to provide a default implementation but also being able to possibly override that implementation in inheriting types. But we can do the exact same thing with just regular methods, so does virtual only exist to express clearer intend that methods shall be reimplemented in inheriting types by other developers or what is the purpose of that keyword?
10 Replies
Thinker
Thinker3y ago
But we can do the exact same thing with just regular methods
Well, no you can't You can't override non-virtual/abstract methods.
Thalnos
ThalnosOP3y ago
or hide with new then, my bad still same question tho
Thinker
Thinker3y ago
hiding is not the same thing as overriding
Thalnos
ThalnosOP3y ago
whats the difference?
Jaiganésh
Jaiganésh3y ago
If you have a reference to the base class, it will call the base class method with hiding in derived class. While with virtual, it will always call the most derived method.
Thalnos
ThalnosOP3y ago
oh wow I didn't know that I thought it would always use the most derived method
Jaiganésh
Jaiganésh3y ago
That's when it's virtual.
MODiX
MODiX3y ago
thinker227#5176
REPL Result: Success
class A
{
public void F() => Console.WriteLine("a");
}

class B : A
{
// hide
public new void F() => Console.WriteLine("b");
}

class C
{
public virtual void F() => Console.WriteLine("c");
}

class D : C
{
// override
public override void F() => Console.WriteLine("d");
}

A a = new B();
a.F();

C c = new D();
c.F();
class A
{
public void F() => Console.WriteLine("a");
}

class B : A
{
// hide
public new void F() => Console.WriteLine("b");
}

class C
{
public virtual void F() => Console.WriteLine("c");
}

class D : C
{
// override
public override void F() => Console.WriteLine("d");
}

A a = new B();
a.F();

C c = new D();
c.F();
Console Output
a
d
a
d
Compile: 705.157ms | Execution: 53.724ms | React with ❌ to remove this embed.
Thalnos
ThalnosOP3y ago
understood, thank you both very much
Thinker
Thinker3y ago
np catsip

Did you find this page helpful?