Note that there are some explanatory texts on larger screens.

plurals
  1. POExecute a derived constructor before the base constructor in C#
    primarykey
    data
    text
    <p>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 <code>Start()</code> method that uses the object.</p> <p>Here's an excerpt from the base class, (renamed from <a href="http://msdn.microsoft.com/en-us/library/aa446489.aspx#barcode_scanners_netcf_topic6" rel="noreferrer">BarcodeScanner</a> for convenience).</p> <pre><code>public abstract class MyBase { public MyBase() { if (Initialize()) this.Start(); } public abstract bool Initialize(); public abstract void Start(); } </code></pre> <p>Here's the derived class that I'm creating.</p> <pre><code>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()); } } </code></pre> <p>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.</p> <p>I've gotten around this by putting the Initialize/Start if block inside the <code>MyDerived</code> 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. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload