Reputation: 24130
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 ?
Upvotes: 0
Views: 12569
Reputation: 52798
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;
}
Upvotes: 2
Reputation: 4908
Set groupName in each case and use default key in switch statement or assign groupName to null before switch.
Upvotes: 1
Reputation: 11313
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.
Upvotes: 1
Reputation: 2709
string groupName = string.Empty;
Just assign an empty string and your should be okej.
Upvotes: 1
Reputation: 499242
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
Upvotes: 7