Note that there are some explanatory texts on larger screens.

plurals
  1. POC# constructor chaining - changing the order of execution
    primarykey
    data
    text
    <p>I want to know how to change the order of execution when chaining constructors in C#. The only methods I have seen require the chained constructor to be called first, outside of the current constructor.</p> <p>Specifically, take the following example:</p> <pre><code>public class Foo { private static Dictionary&lt;string, Thing&gt; ThingCache = new Dictionary&lt;string, Thing&gt;(); private Thing myThing; public Foo(string name) { doSomeStuff(); if (ThingCache.ContainsKey(name)) { myThing = ThingCache[name]; } else { myThing = ExternalStaticFactory.GetThing(name); ThingCache.Add(name, myThing); } doSomeOtherStuff(); } public Foo(Thing tmpThing) { doSomeStuff(); myThing = tmpThing; doSomeOtherStuff(); } } </code></pre> <p>Ideally, I'd like to reduce code repetition by doing this (note, I admit that in this contrived example, not much code is saved, but I am working with code that would benefit much more. I use this example for clarity):</p> <pre><code>public class Foo { private static Dictionary&lt;string, Thing&gt; ThingCache = new Dictionary&lt;string, Thing&gt;(); private Thing myThing; public Foo(string name) { if (ThingCache.ContainsKey(name)) { this(ThingCache[name]); } else { this(ExternalStaticFactory.GetThing(name)); ThingCache.Add(name, myThing); } } public Foo(Thing tmpThing) { doSomeStuff(); myThing = tmpThing; doSomeOtherStuff(); } } </code></pre> <p>This is possible in VB .Net, but C# doesn't let me call a constructor in the middle of another constructor - only at the beginning using the Foo() : this() syntax.</p> <p>So my question is, how does one control the order of constructor calling when chaining constructors, rather than using the colon syntax, which can only call the other constructor first?</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. 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