Domanda

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?

È stato utile?

Soluzione 2

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!

Altri suggerimenti

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.

You can take advantage of automatic getters and setters to make the code a little cleaner

public readonly MyType Sth {get; private set;}

public MyClass(MyType sth)
{
    Sth = sth;
}

I use this R# template (named prop):

public $TYPE$ $NAME$ { get; private set; }

It will not take you all the way and if you need readonly and readonly is nice.

An alt + enter option 'To readonly' would be sweet.

A way is alt + enter > 'To property with backing field' then delete the setter + add readonly. Not very automatic.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top