C# Virtual Keyword trap

What does virtual keyword stand for?

Virtual exists in different programming languages though with different names and rules of how it should be used. E.g in C# its “virtual”.  With little experience of Java, I understand that all non-static methods are by default virtual functions, and therefore only methods modified with final keyword cannot be overridden as well as private methods which are not inherited.

So from the short and simple introduction, you can easily deduce that, by marking a method or a member virtual, you are giving authority to all child classes to  override and inject there own implementation. Override meaning that they can use their own implementation of the method/member instead of the base class implementation of the same method/member.

One thing to remember is that there is a hierarchy in derivation and execution of virtual members, since they can be overriden by many child classes. And so the rule  is that, only the most derived type will be executed depending on the object you are in.

So lets see what this might be bringing in our scenario.


class Shape
 {
 public Shape()
 {
 Draw();
 }
 public virtual void Draw()
 {
 Console.WriteLine(this.GetType().Name);
 }
 }

To note here is that the virtual method is called in the constructor, and remember the rules of the most derived takes precedence.

Another class that inherits from Shape as follows


class Circle : Shape
 {
private  int [] _coordinates;
 public Circle()
 {
_coordinates = new int[] { 1,2};
 }

public override void Draw()
 {
Console.WriteLine("{0} {1}", _coordinates[0], _coordinates[1]);
 }
 }

So in this class, we declared a array _coordinates and initialize it in the constructor. The is then used in the overridden method, just to see what happens. So in my calling class I set it up like so:


class Program
 {
 static void Main(string[] args)
 {

//Null exception
 Circle circle = new Circle();

//Null exception
 Shape shape = new Circle();
 Console.ReadLine();
 }
 }

When I run the above code so far, I get this screen

error2

I am creating a new instance of Circle class. The cause the constructor of Shape class to be called. In the Shape constructor we are calling Draw method. Our expectation here would be to see “Shape” printed on the console.

Which is not the case. The Draw method called in the base constructor, invokes the Draw method in the child (Circle) class since its the most derived, find an uninitialized int array, whence the null exception as we try to access first and second items in the array.

The consequences of this is that you can end using an object in unstable state. So you should be very careful when using virtual members in a constructor.

The Shape Draw method will only be called when you are creating a instance of Shape

Happy reading!

Advertisements

Tags: , , ,

About Piusn

Enthusiastic Software Developer

2 responses to “C# Virtual Keyword trap”

  1. Sven Aelterman says :

    This is a nice example of how inheritance should be a second choice for extending functionality. The better approach is composition in many cases.
    Another consideration is that you would generally mark a base class as abstract. That wouldn’t avoid the potential issue you’re seeing here, but I just wanted to remark on it. If the base class was marked abstract, no one would expect the Draw() method on Shape to be called from it’s constructor.

    • Piusn says :

      Hello sven, great you read through the post. I agree with your point here. And that would mean you can create a instance of the abstract class. Nice remarks.

What's your thought on the subject?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: