Link to home
Start Free TrialLog in
Avatar of Jim Riddles
Jim RiddlesFlag for United States of America

asked on

Local variable not assigned in while loop

I am creating a program that will generate X number of codes that must not already exist in a MySQL table.I am trying to read all of the codes in the current table, and store it within an array.  However, I can't seem to get that to work, either.  Below is the code that I have, but I get an error within the while block indicating that ExistingCodes has not been initialized, which puzzles me.  Use of unassigned local variable 'ExistingCodes' is the precise error.  What am I doing wrong here?  Is there a better way of doing this?  Keep in mind that I am going to use this array to check against when generating the new codes, and adding the new codes as they are generated.

    public static string[] GetExistingCodes
    {
      get
      {
        int index = 0;
        string[] ExistingCodes;
        string sql = "SELECT code from `gift_codes`";
        MySqlCommand cmd = new MySqlCommand(sql, Conn);
        MySqlDataReader rdr = cmd.ExecuteReader();
        while (rdr.HasRows)
        {
          ExistingCodes[index] = rdr.GetString(0);
          index++;
        }
        return ExistingCodes;
      }
    }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:)

cross-posted !
Avatar of Jim Riddles

ASKER

Thank you so much.  I am very new to C#, and I am actually trying to consolidate a slew of tools that I built in PHP CLI into a single C# WPF application.  This solution works perfectly.
Avatar of Arana (G.P.)
Arana (G.P.)

if you wanted to do that without the list you would have to know the total number of codes beforehand (lets say 8 codes)

string[] ExistingCodes=string[8]
or
string[] ExistingCodes={1,2,3,4,5,6,7,8}   /*you can imagine if you have thousands :P not good idea*/

then :

        while (rdr.HasRows)
        {
          ExistingCodes[index] = rdr.GetString(0);
          index++;
        }