I just spent hours being confused by an NullReferenceException
where I thought there shouldn't be one. I was constructing a class like so:
public class MyClass : MyBase<Foo>
{
public MyClass()
{
base.Method(Foo.StaticField);
}
}
where
public class MyBase<T>
{
private SomeObject bar = new SomeObject();
public void Method(object o)
{
this.bar.AnotherMethod(o); // exception thrown here
}
}
Basically my IL was the following:
ctorIl.Emit(OpCodes.Ldarg_0);
ctorIl.Emit(OpCodes.Ldsfld, staticField);
ctorIl.Emit(OpCodes.Box, typeof(FieldType));
ctorIl.Emit(OpCodes.Call, parentMethod);
ctorIl.Emit(OpCodes.Ret);
and I finally figured that it must be that bar
was not being instantiated. I constructed my class in C# and compiled it and found the only difference was that the following should be above the IL above:
ctorIl.Emit(OpCodes.Ldarg_0);
ctorIl.Emit(OpCodes.Call, parentCtor);
// as above
With these lines, my code now works as expected.
So my questions are:
For calling the constructor of a parent class we can use the super keyword. The super() method from the constructor method is used for the invocation of the constructor method of the parent class to get access to the parent's properties and methods.
Note: In Java, constructor of the base class with no argument gets automatically called in the derived class constructor.
If parent class implements a constructor with arguments and has no a constructor with no arguments, then the child constructors must explicitly call a parents constructor.
In simple words, we can say that the parent constructor gets called first, then of the child class.
Note that you can actually emit a simple constructor (including base call) in a single method:
typeBuilder.DefineDefaultConstructor();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With