C
C#16mo ago
Florian Voß

✅ 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
Thinker16mo 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ß16mo ago
or hide with new then, my bad still same question tho
Thinker
Thinker16mo ago
hiding is not the same thing as overriding
Florian Voß
Florian Voß16mo ago
whats the difference?
Jaiganésh
Jaiganésh16mo 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ß16mo ago
oh wow I didn't know that I thought it would always use the most derived method
Jaiganésh
Jaiganésh16mo ago
That's when it's virtual.
MODiX
MODiX16mo 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ß16mo ago
understood, thank you both very much
Thinker
Thinker16mo ago
np catsip