Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual keyword in c#

I have knowledge of Java and have been learning C# for the last couple of days. Now I have come across the "virtual" keyword which, as suggested at this link, is used to allow the corresponding methods, properties etc. to be overriden in the subclasses. Now I think we can override methods even without using the "virtual" keyword. Then why it is necessary?

like image 974
Victor Mukherjee Avatar asked Dec 13 '12 09:12

Victor Mukherjee


2 Answers

You need the virtual keyword if you really want to override methods in sub classes. Otherwise the base implementation will be hidden by the new implementation, just as if you had declared it with the new keyword.

Hiding the methods by "overriding" them without the base method being declared virtual leaves you without polymorphism, that means: if you "cast" a specialized version to the "base" version and call a method, always the base classes implementation will be used instead of the overridden version - which is not what you'd expect.

Example:

class A
{
    public void Show() { Console.WriteLine("A"); }
}

class B : A
{
    public void Show() { Console.WriteLine("B"); }
}

A a = new A();
B b = new B();

a.Show(); // "A"
b.Show(); // "B"

A a1 = b;
a1.Show(); // "A"!!!
like image 158
Thorsten Dittmar Avatar answered Sep 22 '22 00:09

Thorsten Dittmar


virtual is a way of defining that a method has a default implementation, but that that implementation may be overriden in a child class. Other than by using virtual, you cannot override a method directly without using the new keyword (which is generally bad practice).

A good example of the implementation of virtual is the ToString() method. Every object in C# is guaranteed to be able to call ToString() because every object inherits from the base System.Object class, which contains a virtual method ToString(). Derived classes can override this however, and provide their own implementation which may be more useful to the users of the object.

Update: I recently wrote a blog post which goes into this topic in a bit of depth. Check it out here.

like image 40
Levi Botelho Avatar answered Sep 22 '22 00:09

Levi Botelho