We help IT Professionals succeed at work.
Get Started

Local variable not assigned in while loop

Jim Riddles
Jim Riddles asked
on
71 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
CERTIFIED EXPERT
Distinguished Expert 2020
Commented:
This problem has been solved!
Unlock 2 Answers and 5 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE