Search code examples
c#stringunassigned-variable

Use of unassigned variable (string)


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 ?


Solution

  • 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