Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi,

 

I have this piece of code:

 

					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:


					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?

  • Administrators
Posted (edited)

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.

Edited by PlausiblyDamp

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

  • Leaders
Posted

Also, unless I'm missing something, the arrays are declared, but never created, yet you are accessing elements of the array.

 

In other words:

 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.
 

[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...