-2

So i try to get around this issue. I know for a fact that this will be initialized before am calling it but c# can not know this i guess. I cannot do xUser user = new xUser; One work around i was thinking about was using an List and store the values in list and then create the xuser after the while loop but it seems very messy. And i really wanna learn how to avoid this kind of errors.

        noUSer iuser = new noUSer();
        xUser user;
        string sql = "select * from accounts where id='" +id +"'";
        SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
        SQLiteDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {

            iuser.user_name = reader["login"].ToString();
            iuser.password = reader["password"].ToString();
            iuser.cookie_file = @"c:\cookies";

            user = iusers.create(iguser);


        }



        m_dbConnection.Close();
        if (tab_mode.SelectedTab.Text == "User")
        {
           dothiscall(user); //Error on "user" local variable might be not initialized before accessing

        }

3 Answers3

4

You should initialize the variable to null, however, be aware that if the code inside while loop doesn't execute, it will remain null.

Mehrzad Chehraz
  • 5,092
  • 2
  • 17
  • 28
0

Yes better way is create a list iusers and add new iuser inside while loop. and your whileloop to user you are adding iguser which can not find. It should be iuser

   xUser user = new xUser();
   string sql = "select * from accounts where id='" +id +"'";
   SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
   SQLiteDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        noUSer iuser = new noUSer();
        iuser.user_name = reader["login"].ToString();
        iuser.password = reader["password"].ToString();
        iuser.cookie_file = @"c:\cookies";

        user = iusers.Add(iuser);

    }
SilentCoder
  • 1,970
  • 1
  • 16
  • 21
0

When you do:

xUser user;

You are merely creating a pointer.meaning if u had an object of type xUser later on and wanted a pointer to it you could do for example something like :

user =(xUser)DataGridView1.Rows[0].cells[myxUserObjectInCell.index].Value;

That way making changes to user will make changes to the object in your grid. However if you're planning on creating an object of type xUser,then you need to do:

xUser user = new xUser();

The new keyword makes it initialize.

Niklas
  • 955
  • 15
  • 29