1

I have a piece of code that iterates over XML attributes:

string groupName;
do
{
    switch (/* ... */)
    {
        case "NAME":
            groupName = thisNavigator.Value;
            break;
        case "HINT":
            // use groupName

But this way I get the error of using an unassigned variable. If I assign something to groupName then I cannot change it because that's how the strings work in C#. Any workarounds ?

Mat
  • 202,337
  • 40
  • 393
  • 406
Patryk
  • 22,602
  • 44
  • 128
  • 244

5 Answers5

8

You are right that strings are immutable in .NET, but your assumption that a string variable can't be changed is wrong.

This is valid and fine:

string groupName = null;
groupName = "aName";
groupName = "a different Name";

Your code will not have an error if you do the following:

string groupName = string.Empty; // or null, if empty is meaningful
do
{
    switch (/* ... */)
    {
        case "NAME":
            groupName = thisNavigator.Value;
            break;
        case "HINT":
            // use groupName
Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

Does the default of your switch assign a value to groupName? If not, then that will be causing the error.

switch
{
  case "NAME":
    groupName = thisNavigator.Value;
    break;
  //...
  default:
    groupName = "something";
    break;
}
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
1
string groupName = string.Empty;

Just assign an empty string and your should be okej.

Erik Larsson
  • 2,639
  • 4
  • 16
  • 14
1

The compiler is unaware of the context of your switch statement (e.g. there's no guarantee that the switch will always match a case).

So it's possible for groupName to remain unassigned even after the switch.

You can instantiate groupName with String.Empty or use default: in your switch statement.

lukiffer
  • 11,025
  • 8
  • 46
  • 70
1

Set groupName in each case and use default key in switch statement or assign groupName to null before switch.

Reza ArabQaeni
  • 4,848
  • 27
  • 46