Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This practice is somewhat questionable, so you might want to rethink your approach here.</p> <p>If you still want to go ahead with this, the correct way is to have a <code>virtual</code> method that provides this value to the base constructor:</p> <pre><code>class Base { public Base() { obj = new ObjNeedParam(GetParamVal()); } protected virtual int GetParamVal() { return 1; } } class Derived : Base { protected override int GetParamVal() { return 2; } } </code></pre> <p><strong>You will have to ensure that the <code>override</code> does not use any class members of <code>Derived</code> that get initialized in <code>Derived</code>'s constructor</strong> because that constructor will not have run yet at the point where the override is called! See <a href="https://stackoverflow.com/questions/119506/virtual-member-call-in-a-constructor">Virtual member call in a constructor</a>.</p> <p><strong>Update:</strong> It is somewhat questionable because when constructing an object of some derived type the compiler has a problem to solve: in what order should the fields be initialized and the constructors run so that any method call from inside any constructor is guaranteed to find the object in a "usable" state?</p> <p>This problem cannot be solved in the general case because by definition the object is not in a usable state until all constructors have returned, and we are talking about calling methods from <em>inside</em> these constructors. So the compiler has to guarantee as much as it can and either prevent or allow you to do things that are not provably safe.</p> <p>In this scenario C++ (amusingly) prevents the doing of things that are not provably safe, while C# allows it. Therefore it's somewhat questionable because if you don't pay attention it is possible to introduce bugs. A safer approach would be to write the class such that this member is initialized after the constructors have run.</p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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