I'm guessing the reason why you want to initialize fields in the constructor is for immutability reasons, but since you haven't made the fields readonly
(and you've called your fields prop
), you can obviously also use the property initializer syntactic sugar, if you change your fields to properties, reducing your LOC as follows:
public class Stuff {
public int Prop1 {get; set;}
public int Prop2 {get; set;}
}
Caller would just use the default constructor:
var myStuff = new Stuff() {
Prop1 = 54,
Prop2 = 88
}
Edit
I guess to sum up the below banter:
- If 'prop1' et al are to be retained as
fields
, then there is no shorthand.
- If 'prop1' et al need to be kept private (albeit initialized externally) then there is also no shorthand.
- If the fields can be converted to publically setable properties, then you can use automatic properties, as per above.
However, and I’m speculating here, if your question is as a requirement of using ctor
initializers for the purpose of promoting the immutability of your fields, it would be nice to allow a hybrid syntactic sugar allowing for a combination of immutability similar to autoproperties which will reduce the LOC.
Several folk are already calling for readonly automatic properties to be implemented in C#, although it is speculative as to whether this extend to initializer syntax as part of the constructor.
This might allow the typical verbose pattern of:
class SomeClass
{
private readonly SomeDependency _dep1;
private readonly AnotherDependency _dep2;
. . .
public SomeClass(SomeDependency dep1, AnotherDependency dep2, …)
{
_dep1 = dep1;
_dep2 = dep2;
…
}
To be replaced with simpler, yet equivalent code. I have absolutely no idea what the syntax would look like ... but it would mean a property (or field) is "private readonly" except for the one exception of CTOR initializer syntax ...
"ReadOnly" SomeDependency Dep1 { private get; private set; }
"ReadOnly" SomeDependency Dep1 { private get; private set; }
. . . No need for ctor since can just use the default constructor
And which could then be used at construction time:
var x = new SomeClass
{
Dep1 = ...,
Dep2 = ...
}; // OK, this time only, because it is at construction time.
But not mutated
x.Dep1 = ...; // Compile time err ...
And obviously the requirement would be that ALL such properties must be initialized simultaneously (or just be baked with the type default for the object's lifespan )...