Use of unassigned local variable?

MrLucky

Freshman
Joined
Mar 5, 2006
Messages
47
Hi,

I have this piece of code:

C#:
						int[] values;
						string[] legends;
						
						int i = 0;
						while(reader.Read())
						{
							values[i] = Convert.ToInt32(reader.GetValue(reader.GetOrdinal("total_played")));
							legends[i] = reader.GetValue(reader.GetOrdinal("history_artist")) + " - " + reader.GetValue(reader.GetOrdinal("history_title"));
						}

						chart.SetValues(values);
						chart.SetLegends(legends);
						chart.Render("Most played songs", "", 200, 200);

						System.Drawing.Image final = chart.Final;

						graphMostPlayed.Image = final;

But when I try to build it, I get these 2 errors:
Error 1 Use of unassigned local variable 'values' C:\Documents and Settings\Lucas\My Documents\Visual Studio 2005\Projects\RM\RM\Form1.cs 730 23 RM
Error 2 Use of unassigned local variable 'legends' C:\Documents and Settings\Lucas\My Documents\Visual Studio 2005\Projects\RM\RM\Form1.cs 731 24 RM

on these 2 lines:
C#:
						chart.SetValues(values);
						chart.SetLegends(legends);

But above the while loop, I declared the vars, so I thought the vars should exists.

Why am I getting this error?
 
Although the variables are declared outside the while loop they are only ever assigned to inside the while loop. More importantly the compiler cannot guarantee the code in the loop will ever execute (the adapter might return no records for example) so it cannot be sure the variables will ever be assigned to.
Easiest fix is to assign something to them when you declare them (even assigning null will work) so the compiler knows they have been initialised to something.
 
Last edited:
Also, unless I'm missing something, the arrays are declared, but never created, yet you are accessing elements of the array.

In other words:
C#:
  int[] MyArray = new int[10]; // The new statement creates an array
  MyArray[1] = SomeValue;
   
  // Versus
   
  int[] MyArray; //or int[] MyArray = null;
  MyArray[1] = SomeValue; 
  // Raises a null reference exception because we
  // havent created an array.
 
Back
Top