Getting Started with Adobe After Effects - Part 6: Motion Blur
A collection of quick technology learning tips from what people around you learn every day

C#: Virtual methods calls in constructor might cause problems

Mar 15 2012 12:00AM by Olga Medvedeva   

It is simple rule, but maybe some people will find this post useful.

From MSDN: "When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, it is possible that the constructor for the instance that invokes the method has not executed."

So the reason of possible problems is that constructor of derived class will be called later then constructor of base class. And if you call virtual method in base class constructor, overridden method of derived class will be actually executed. And as fields of derived class were not initialized properly in constructor, you can get unexpected values (results) or even errors and exceptions.

For instance, this code example will generate NullReferenceException because field _b was not initialized yet :

internal class BaseClass
{
    protected int _a;

    public BaseClass(int a)
    {
        _a = a;
        PrintFields();
    }

    public virtual void PrintFields()
    {
        Console.WriteLine( _a);
    }
  }

  internal class DerivedClass : BaseClass
  {
    private string _b;

    public DerivedClass(int a, string b): base(a)
    {
        _b = b;
    }

    public override void PrintFields()
    {
        Console.WriteLine(string.Format("Field a = {0}, field b = {1}, length of string b is {2}", _a, _b, _b.Length));
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
        BaseClass a = new DerivedClass(5, "some string");
    }
  }
Read More..   [32134 clicks]

Published under: Microsoft .NET Tips ·  ·  ·  · 


Olga Medvedeva
66 · 3% · 843
6
 
1
 
 
0
Incorrect
 
0
Interesting
 
0
Forgotten



Submit

1  Comments  

  • Indeed, methods that could be needed during initialization should never be virtual. You should have a pattern like this instead.

    public MyObject() {
     this._method();
    }
    
    private void _method()  {
     base.method();
     [some code]
    }
    
    virtual protected void method()  {
     this._method();
    }
    

    _ = _

    commented on Mar 15 2012 5:33AM
    Sergejack
    41 · 4% · 1393

Your Comment


Sign Up or Login to post a comment.

"C#: Virtual methods calls in constructor might cause problems" rated 5 out of 5 by 6 readers
C#: Virtual methods calls in constructor might cause problems , 5.0 out of 5 based on 6 ratings
    Copyright © Rivera Informatic Private Ltd Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising      [ZULU1097]