简体   繁体   中英

How to get a reference to a string property in C#

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?

Just do it like this:

string someString = "I can't do that, Dave.";
if (condition1) foo.Bar1 = someString;
else if (condition2) foo.Bar2 = someString;
else if (condition3) foo.Bar3 = someString;

C# tries to make strings as easy as possible to work with. They are primitive types, so you don't really need to worry about mutability or memory or addresses or anything like that.

Personally I would probably just go ahead and assign the property:

string value = "I can't do that, Dave.";
if (condition1) foo.Bar1 = value;
else if (condition2) foo.Bar2 = value;
else if (condition3) foo.Bar3 = value;

If you really want to use the approach you suggest, you can wrap it in a delegate I guess:

Action<string> assignString;
if (condition1) assignString = s => foo.Bar1 = s;
else if (condition2) assignString = s => foo.Bar2 = s;
else if (condition3) assignString = s => foo.Bar3 = s;
assignString("I can't do that, Dave.");

...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.

You can always do it like this:

EDITED **

var someString = (condition1) ? foo.Bar1 : (condition2) ? foo.Bar2 : (condition3) ? foo.Bar3 : "I can't do that Dave";

Let me know how you go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM