✅ 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
Thinker2y 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.
Florian Voß
Florian VoßOP2y ago
or hide with new then, my bad still same question tho
Thinker
Thinker2y ago
hiding is not the same thing as overriding
Florian Voß
Florian VoßOP2y ago
whats the difference?
Jaiganésh
Jaiganésh2y 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.
Florian Voß
Florian VoßOP2y ago
oh wow I didn't know that I thought it would always use the most derived method
Jaiganésh
Jaiganésh2y ago
That's when it's virtual.
MODiX
MODiX2y 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.
Florian Voß
Florian VoßOP2y ago
understood, thank you both very much
Thinker
Thinker2y ago
np catsip
Want results from more Discord servers?
Add your server