tags:

views:

75

answers:

5
void Foo()
{

string ID = "test";
var testctrl = new Control() {ID = (ID**!=null?ID**:ID)};

}

Is it possible to get the value of ID** in the code above? The problem is they both have the same property names.

Please ignore the fact the specific ID assignment is pointless, im just using it as an example.

A: 

The question is not that clear to me, but do you want this:

void Foo()
{

bool ID = "test";
var testctrl = new Control(){ID = (this.ID==null?ID:this.ID)};

}

note, untested.

Sam Holder
You cannot use `this` keyword in variable initializer.
Darin Dimitrov
Yeah, he wants to do something like that (not quite what you wrote), and it's not possible (i.e. your code does not work).
Noon Silk
thanks, wasn't sure it would do (apart for the obvious errors in the OPs question)
Sam Holder
@Darin Dimitrov, does this not conflict with what Marc Gravell has posted in his answer?
Sam Holder
@Darin Dimitrov: The code above compiles just fine (if you make `ID` of type `string` and add an `ID` field to class `Foo`) and works as expected. Did I miss your point?
0xA3
+1  A: 

First remark about this line, it looks strange (assigning string to bool):

bool ID = "test";

Second remark, this works fine:

string ID = "test";
var testctrl = new Control(){ ID = (ID==null?ID:ID) };

Third remark: it is a convention in C# to name your local variables start with lowercase letter.

Darin Dimitrov
My bad, i rewrote the code one too many times.
maxp
+1  A: 

Putting aside that the code can't possibly compile... The first ID (ID=) in this syntax refers to the assignment, specifically the member being assigned. On the right-hand-side, it comes down to standard resolution. Which never means the ID of the new object. It will first look at the local ID variable, then after that members (fields etc) on the current instance. To prefer members on the current instance, use this.ID.

You might also want to consider the null-coalescing operator, so if you mean "the local-variable, or the instance-member if it is null, that would be ID ?? this.ID - but an even better idea would be to make unambiguous variable names ;-p

Marc Gravell
+1  A: 

If you want to check if the new controls id is null then you should do this.

void Foo()
{
    string ID = "test";
    var testctrl = new Control();
    if(testctrl.ID==null)
        testctrl.ID = ID;
}
juharr
A: 

Seeing your example, I suspect that you don't have the requirement that the ID should be unique? In general, to avoid nasty problems like this, avoid try using duplicate property names, but maybe your bound to an existing interface.

How about adding an constructor overload which takes the 'outer' ID as a parameter?

void Foo()
{

string ID = "test";
var testctrl = new Control(ID);

}

I think in general, if the property does more than just assignment (argument checking in this case), you should do it in the 'set' of the property itself and not during 'object initialization'.

Rob van Groenewoud