ahmd0
ahmd0

Reputation: 17293

How can I declare string reference variable in C#?

The best way to illustrate my question is this C# example:

//It seems that the comment is required:
//I need to change the values of someString0, someString1, or someStringN 
//depending on the `type` variable

ref string strKey;

switch(type)
{
    case 0:
        strKey = ref someString0;
        break;
    case 1:
        strKey = ref someString1;
        break;
    //And so on

    default:
        strKey = ref someStringN;
        break;
}

//Set string
strKey = "New Value";

Can I do this in C#?

PS. I know that I can do this in a function. I'm asking about an "in-line" approach.

Upvotes: 3

Views: 927

Answers (3)

If you really want to do the assignment similar to the way you're asking for, here is one way that doesn't use ref

Action<string> action;
switch (type) {
    case 0:
        action = newVal => someString0 = newVal;
        break;
    case 1:
        action = newVal => someString1 = newVal;
        break;
    case 2:
        action = newVal => someString2 = newVal;
        break;
    default:
        action = null;
        break;
}
if (action != null) action.Invoke("some new value");

Performance-wise, the above takes about 8 nanoseconds longer to execute than the direct alternative below

switch (i) {
    case 0:
        someString0 = "some new value";
        break;
     case 1:
        someString1 = "some new value";
        break;
      case 2:
        someString2 = "some new value";
        break;
      default:
        break;
}

But you're talking a little longer than next to nothing. On my not particularly fast laptop, the Action version takes around 13 nanoseconds to execute vs. the direct assignment method that takes around 5.5 nanoseconds. Neither is likely to be a bottleneck that matters.

Upvotes: 2

acfrancis
acfrancis

Reputation: 3661

Why don't you just set the correct string variable like this:

switch(type)
{
    case 0:
        someString0 = "New Value";
        break;
    case 1:
        someString1 = "New Value";
        break;
    //And so on

    default:
        someStringN = "New Value";
        break;
}

An even better approach is to replace your n string variables with an array of strings so that the assignment becomes a single line of code:

string[] someString;
someString[type] = "New Value";

Upvotes: 0

John Gardner
John Gardner

Reputation: 25116

why are you splitting this up into a switch and then an assignment later? why not just set the value in the switch and avoid the ref behavior at all?

string newValue = "new value";

switch(type)
{
    case 0:
        someString0 = newValue;
        break;
    case 1:
        someString1 = newValue;
        break;
    //And so on

    default:
        someStringN = newValue;
        break;
}

Upvotes: 1

Related Questions