MrLucky Posted March 5, 2006 Posted March 5, 2006 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? Quote
Administrators PlausiblyDamp Posted March 5, 2006 Administrators Posted March 5, 2006 (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 March 10, 2007 by PlausiblyDamp Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Leaders snarfblam Posted March 5, 2006 Leaders Posted March 5, 2006 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. Quote [sIGPIC]e[/sIGPIC]
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.