tags:

views:

479

answers:

2

A few months ago i read about a technique so that if there paramaters 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?

+1  A: 

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.

Andy White
Is there something similar in Java?
verhogen
Not as far as I know.
Andy White
+8  A: 

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.

Matt Hamilton
You could be right Matt although i'm not certain. haha. really need to save these things when i find them next time. cheers.
Schotime