C # Object Constructor - short property syntax

A few months ago I read about the technique, so if the parameters you pass correspond to local variables, you can use some shorthand syntax to set them. To avoid this:

public string Method(p1, p2, p3)
{
    this.p1 = p1;
    this.p2 = p2;
    this.p3 = p3;
}

Any ideas?

+5
source share
3 answers

Perhaps you are thinking about the syntax of a new object initializer in C # 3.0. It looks like this:

var foo = new Foo { Bar = 1, Fizz = "hello" };

So, giving us a new instance of Foo, the โ€œBarโ€ property, initialized to 1, and the โ€œFizzโ€ property for โ€œhelloโ€.

, "=" , , . , , Foo, :

var foo2 = new Foo { foo1.Bar, foo1.Fizz };

, . p1, p2 p3, , :

var foo = new Foo { p1, p2, p3 };

, - , , - , , .

+25

, " " #, , , .

, , , "this" .

+2

There is an even simpler way to do this in C # 7 - body expression constructors.

Using your example above - your constructor can be simplified to one line of code. I have included class fields for completeness, I assume that they will still be in your class anyway.

private string _p1;
private int _p2;
private bool _p3;  

public Method(string p1, int p2, bool p3) => (_p1, _p2, _p3) = (p1, p2, p3);

See the following link for more information: -

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members

0
source

All Articles