C# Object Constructor - shorthand property syntax

You may be thinking about the new object initializer syntax in C# 3.0. It looks like this:

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

So that's giving us a new instance of Foo, with the "Bar" property initialized to 1 and the "Fizz" property to "hello".

The trick with this syntax is that if you leave out the "=" and supply an identifier, it will assume that you're assigning to a property of the same name. So, for example, if I already had a Foo instance, I could do this:

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

This, then, is getting pretty close to your example. If your class has p1, p2 and p3 properties, and you have variables with the same name, you could write:

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

Note that this is for constructing instances only - not for passing parameters into methods as your example shows - so it may not be what you're thinking of.


There's an even easier method of doing this in C# 7 - Expression bodied constructors.

Using your example above - your constructor can be simplified to one line of code. I've included the class fields for completeness, I presume they would be on 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 info :-

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


You might be thinking of the "object initializer" in C#, where you can construct an object by setting the properties of the class, rather than using a parameterized constructor.

I'm not sure it can be used in the example you have since your "this" has already been constructed.

Tags:

C#

Object

Class