I’m trying to call an overriden property from a base constructor but I’m receiving a System.Reflection.TargetInvovationException(“Object reference not set to an instance of an object.”). Why is this error being thrown and can anything be done to avoid it?
I would have expected the constructor to have just called the overriden property.
Here is a stripped down example:
// Call that generates exception
var foo = new Foo();
public class Foo : Bah {
public Foo() : base("Foo!") {}
public override string Name {
get { return _name + "123"; }
set { _name = value; }
}
}
public class Bah {
protected string _name;
public Bah(string name) {
Name = name; // << -- Exception here
}
public virtual string Name {
get { return _name; }
set { _name = value; }
}
}
You have some other issue going on. The code, as typed, works. Try this fully functional program to see, which prints (as expected) “Foo!123”:
That being said, calling virtual methods (including Property accessor methods) in a constructor is a very bad idea. It can lead to very odd behavior, which is likely the culprit in your real code.