Say I have a class with three string properties:
public class Foo
{
public string Bar1 { get; set; }
public string Bar2 { get; set; }
public string Bar3 { get; set; }
}
Now say I want to assign to one of the string properties, but that which of the three properties I assign to depends upon some condition. Knowing that strings are supposedly reference types, I might be tempted to write some code like this:
string someString;
if (condition1) someString = foo.Bar1;
else if (condition2) someString = foo.Bar2;
else if (condition3) someString = foo.Bar3;
someString = "I can't do that, Dave.";
This doesn’t work. I know it’s got something to do with string immutability (at least I think it does) but I haven’t any idea how to do it.
Strings basically confuse the bejesus out of me.
Um, yeah, so my question is what’s the most concise way to do this?
Personally I would probably just go ahead and assign the property:
If you really want to use the approach you suggest, you can wrap it in a delegate I guess:
…but in this case that would only make things unnecessarily complex. For the kind of scenario that is described in the question, I can’t think of any reason you would want to do this.