My problem here is that I would like to pass an object to a derived class, but it must be done before the base class constructor, since the base class will immediately call the derived class's Start()
method that uses the object.
Here's an excerpt from the base class, (renamed from BarcodeScanner for convenience).
public abstract class MyBase
{
public MyBase()
{
if (Initialize())
this.Start();
}
public abstract bool Initialize();
public abstract void Start();
}
Here's the derived class that I'm creating.
class MyDerived : MyBase
{
private string sampleObject;
public MyDerived (string initObject)
{
sampleObject = initObject;
}
public override bool Initialize()
{
return GetDevice();
}
public override void Start()
{
Console.WriteLine("Processing " + sampleObject.ToString());
}
}
I doubt you can make C# execute a derived constructor before the base constructor; so I'm really just looking for a solution to pass an object to the derived class before the object is used.
I've gotten around this by putting the Initialize/Start if block inside the MyDerived
constructor. However, there are other classes deriving from the base class; so I ended up having to repeat this block of Initialize/Start code in every derived class. I'd like to see an alternative to modifying the base class.
Base Constructor is called first. But the initializer of fields in derived class is called first.
Because const variables must be initialized with a value at the time of creation, the base class constructor must set its value when the variable is created. However, when the base class constructor finishes, the derived class constructor's member initializer lists are then executed.
How to call the parameterized constructor of base class in derived class constructor? To call the parameterized constructor of base class when derived class's parameterized constructor is called, you have to explicitly specify the base class's parameterized constructor in derived class as shown in below program: C++
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.
What you are trying to do is impossible in C#. A constructor in a base class must be run before the constructor of any derived class otherwise there would be potential for corrupt object state. A child object must be able to assume that its base is fully constructed and available.
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