I find myself creating loads of the properties following the pattern:
private readonly MyType sth;
public MyClass(MyType sth) //class constructor
{
this.sth = sth;
}
public MyType Sth
{
get { return sth; }
}
Is there an easy way to automate creating of these properties? Usually I:
Is it possible to make it quicker?
With C# 6, your example can be rewritten as:
private MyType sth { get; }
public MyClass(MyType sth) //class constructor
{
this.sth = sth;
}
This is called a getter-only auto-property. The generated field behind the property is declared read-only when you remove the "private set;" like this.
From https://msdn.microsoft.com/en-us/magazine/dn879355.aspx
Getter-only auto-properties are available in both structs and class declarations, but they’re especially important to structs because of the best practice guideline that structs be immutable. Rather than the six or so lines needed to declare a read-only property and initialize it prior to C# 6.0, now a single-line declaration and the assignment from within the constructor are all that’s needed. Thus, declaration of immutable structs is now not only the correct programming pattern for structs, but also the simpler pattern—a much appreciated change from prior syntax where coding correctly required more effort.
Please consider this live template:
private readonly $MyType$ $FieldName$;
public $ClassName$($MyType$ $FieldName$) //class constructor
{
this.$FieldName$ = $FieldName$;
}
public $MyType$ $PropName$
{
get { return $FieldName$; }
}
where the order of parameters is:
It should look like this http://screencast.com/t/aRQi0xVezXMb
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With