Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I automate creating immutable properties with ReSharper?

Tags:

c#

.net

resharper

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:

  1. type the field, including the readonly keyword
  2. Select "initialize from constructor parameters
  3. Select "encapsulate"

Is it possible to make it quicker?

like image 928
Grzenio Avatar asked Apr 08 '14 14:04

Grzenio


2 Answers

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.

like image 58
kristianp Avatar answered Oct 10 '22 11:10

kristianp


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:

  1. PropName
  2. ClassName (in Choose Macro select "Containing type name")
  3. MyType
  4. FieldName (in Choose Macro select "Value of another variable with the first character in lower case" and then specify PropName there) - also select "Not editable" in right-top dropdown

It should look like this http://screencast.com/t/aRQi0xVezXMb

Hope it helps!

like image 2
Alexander Kurakin Avatar answered Oct 10 '22 12:10

Alexander Kurakin