C # error: using an unassigned local variable

Error in for loop:

for (i = 0; i < hand.Length; i++) { Console.WriteLine(hand[i]); } 

I am trying to save values ​​so that they can be displayed later. There is a letter to help me make sure that the code really works as I intend it.

The rest of the code for reference: * edit: added a line of code

 enum house //variable type for the card type { Spades, Hearts, Clubs, Diamonds } enum cards //variable type for the cards { Joker, Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } class Program { static void Main(string[] args) { Random rnd; Random rnd2; int i; int random; int random2; String[] hand; house randomhouse; cards randomcard; //all declared variables Console.WriteLine("Your hand is made up of :"); for (i = 0; i <= 6; i++)//does everything in the {} until i is equal to 6 { rnd2 = new Random(); random2 = rnd2.Next(0, 14); randomcard = (cards)random2; //selecting a random card from joker to king if (randomcard > (int)cards.Joker) //if the random card isn't a joker { rnd = new Random(); random = rnd.Next(0, 4); randomhouse = (house)random;//selects a random card type Console.WriteLine(randomcard + " of " + randomhouse); //outputs the name of the card System.Threading.Thread.Sleep(1000);//wait 1 second before getting the new card } else { Console.WriteLine(randomcard);//outputs "Joker" System.Threading.Thread.Sleep(1000);//wait 1 second before getting the new card } hand = new String[i];//making a new array value for every loop hand[i] = randomcard.ToString();//adding randomcard to the array* } Console.Clear(); for (i = 0; i < hand.Length; i++) { Console.WriteLine(hand[i]); } Console.ReadKey(); } } 
+6
source share
2 answers

The compiler can never be sure that hand actually initialized. You must either initialize it earlier or set it to null , so you will bypass this compiler check.

So you could do it, but it's really bad practice! When changing the code, you can get a NullReferenceException !

 String[] hand = null; 

You know that your code doesn’t actually work, as you end up with one array. I think you mean this:

 hand = new String[6]; ... hand[i] = theValue; 
+8
source

Arrays in C # are not dynamic. You need to manually resize them to add anything to them. Initialize your hand outside the for loop. Since the starting hand has 6 cards, you can assign it.

 string[] hand = new string[6]; 

If new maps are added, you can use:

 Array.Resize(ref hand, (i + 1)); 
0
source

All Articles