A few months ago I read about a technique so that if there parameters you passed in matched the local variables then you could use some short hand syntax to set them. To avoid this:
public string Method(p1, p2, p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; }
Any ideas?
You may be thinking about the new object initializer syntax in C# 3.0. It looks like this:
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:
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:
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.