Use of unassigned variable (string)

Patryk picture Patryk · Dec 4, 2011 · Viewed 10.6k times · Source

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 ?

Answer

Oded picture Oded · Dec 4, 2011

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