We help IT Professionals succeed at work.

Local variable not assigned in while loop

Jim Riddles
Jim Riddles asked
on
Medium Priority
46 Views
Last Modified: 2020-03-10
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

Comment
Watch Question

Software Tead Lead / Business Analyst / System Analyst / Data Engineer
CERTIFIED EXPERT
Commented:
try define as a List<string> instead.

like:

List<string> ExistingCodes = new List<string>();

Open in new window


then:
ExistingCodes.Add(rdr.GetString(0));

Open in new window


also change the method to:

public static List<string>GetExistingCodes()

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
I'd go with a List<string> instead of an array. It will give you more flexibility:

var ExistingCodes = new List<string>();

while (rdr.HasRows)
{
    ExistingCodes.add(rdr.GetString(0));
}

Open in new window

If you then explicitly need an array, you can cast it:

return ExistingCodes .ToArray();
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:
:)

cross-posted !
Jim RiddlesPrepress/OMS Specialist
CERTIFIED EXPERT

Author

Commented:
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.
CERTIFIED EXPERT

Commented:
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++;
        }