Avatar of Jim Riddles
Jim Riddles
Flag 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

C#MySQL Server

Avatar of undefined
Last Comment
Arana (G.P.)

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Ryan Chong

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
Chris Stanyon

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Chris Stanyon

:)

cross-posted !
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.
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++;
        }
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes