Step 2 - Climbing the ladder...
# Wednesday, January 23, 2013

I had to figure out a design recently which required setting immutable state from chained constructors having trivial logic performed prior to initialisation.

When performing common logic inside chained constructors it's oft-recommended to isolate the functionality out into a variant of an Initialise() private method which is invoked from the last (master) constructor in the chain.

Something like:

public MyClass(int data) : this(data, null)
{
    
}

public MyClass(int someNumber, string someText)
{
    Initialise(someNumber, someText);
}

private void Initialise(int someNumber, int someText)
{
    //some logic prior to initialising the object's state
}

Simple stuff. It get's slightly more complicated when the objects fields are declared as readonly. This means the C# compiler will not allow you to initialise the fields outside a constructor or class level.

If some centralised (due to chaining) logic is required prior to their initialisation, the described Initialisation() method above will throw the afore mentioned compile error.

One solution, which certainly isn't the most aesthetic, is to call the Initialise method passing each readonly field in as out params. This allows you to perform your logic and initialise the readonly fields outside the constructors.

Example:

private readonly int _someNumber;
private readonly string _someText;

public MyClass(int someNumber) : this(data, null)
{
    
}

public MyClass(int someNumber, string someText)
{
    Initialise(out _someNumber, someNumber, out _someText, someText);
}

private void Initialise(out int _someNumber, int someNumber, out string _someText, string someText)
{
    //some logic prior to initialising the object's state
}

Further reading:
SO question which helped me solve the issue.

Recent posts

Wednesday, January 23, 2013 10:54:52 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]

Posted under: Programming by

My latest artwork
View my entire gallery.
Archive
<January 2013>
SunMonTueWedThuFriSat
303112345
6789101112
13141516171819
20212223242526
272829303112
3456789
About the author/Disclaimer

Disclaimer
The opinions expressed herein are the personal opinions of Adam Naylor and do not represent my current or previous employer's view in any way.

© Copyright 2014
Adam Naylor
Statistics
Total Posts: 55
This Year: 0
This Month: 0
This Week: 0
Comments: 8
Creative Commons Licence
© 2014, Adam Naylor