Adding to a list inside a class

18,483

Solution 1

You need to initialize your list in the constructor:

   public User (string username) : this()
   {
       _name = username;
   }
   public User()
   {
      this.ControlNumber = new List<int>();
   }

Otherwise, ControlNumber will have its default value of null.

Solution 2

Make sure you initialize your lists before you use them!

Corrected User-Class:

public class User
{
   private string _name;
   public string UserName { get; set; }       
   public List<int> ControlNumber { get; set; }
   public User (string username) : this()
   {
       _name = username;
   }
   public User()
   {
       ControlNumber = new List<int>();
   }

}

And also, before converting row["ControlNumber"] to an integer, you should make sure it is not null.

if (row["ControlNumber"] != null)
{
user.ControlNumber.Add(Convert.ToInt32(row["ControlNumber"]));
}

Solution 3

You have not initialised the ControlNumber, you can do this in the constructor like

public User (string username)
{
    _name = username;
    ControlNumber = new List<int>();
}

or just before you attempt to Add

_user.ControlNumber = new List<int>();
_user.ControlNumber.Add(Convert.ToInt32(row["ControlNumber"]));

I hope this helps.

Solution 4

I hate setting properties in constructor, so what I do is:

private List<int> _controlNumber;
public List<int> ControlNumber { 
    get { 
        if (_controlNumber == null)
            _controlNumber=new List<int>(); 

        return _controlNumber; 
    }

    set { _controlNumber = value } 
}

or simply

private List<int> _controlNumber = new List<int>();
public List<int> ControlNumber { 
    get { return _controlNumber; } 
    set { _controlNumber = value } 
}

Solution 5

By default, your ControlNumber property is set to null.

In your constructor, do the following to initialize it to an empty list:

this.ControlNumber = new List<int>();
Share:
18,483
MaylorTaylor
Author by

MaylorTaylor

I am a highly skilled Full Stack Developer with 6+ years of experience in a real world work environment. I work well in a team environment, and am seasoned enough to accomplish projects with minimal direction and oversight. I am looking for a position with opportunity for growth, including leading a team of my own and learning new skills and languages. 5+ years with SQL and MySQL databases, C# language, Razor templates, and MVC framework 5+ years using .NET 4.6 and 4.7 4+ years of AngularJS development, HTML, CSS/LESS 2+ years using latest .NET Core and .NET Standard technologies and builds 2+ years experience with Node, Express, MEAN stack, and Angular 2+ Well versed on proper RESTful standards, HTML5 standards, ADA compliance standards, and C# coding patterns such as the “Visitor Pattern”

Updated on June 28, 2022

Comments

  • MaylorTaylor
    MaylorTaylor almost 2 years

    I have this class

    public class User
    {
       private string _name;
       public string UserName { get; set; }       
       public List<int> ControlNumber { get; set; }
       public User (string username)
       {
           _name = username;
       }
       public User()
       {
       }
    
    }
    

    And this function that fills the class.

    User UserClass = new User(e.Key); //e.Key = user's name
    
    public static void FillUserListClass(DataTable dt, ref UserClass)
    
    {
        try
        {
    
            for (int ctr = 0; ctr < dt.Rows.Count; ctr++)
            {
                var row = dt.Rows[ctr];
                var userName = row["User"].ToString();
    
                if (UserList.ContainsKey(userName))
                {
                    UserList[userName].Add(Convert.ToInt32(row["ControlNumber"]));
                }
                else
                {
                    _user.UserName = row["User"].ToString();
                    _user.ControlNumber.Add(Convert.ToInt32(row["ControlNumber"]));
    
                }
                  //print out
                Console.WriteLine("UserList Class: ");
                Console.WriteLine(_user.UserName);
                Console.WriteLine(_user.ControlNumber);
    
    
            }
        }
        finally
        {
            //conn.Close();
        }
    
    }
    

    However, at the _user.ControlNumber.Add(Convert.ToInt32(row["ControlNumber"])); line I get the "Object reference not set to an instance of an object." error. Any help?

    What i'm trying to do is create a class for each user that contains the user's control numbers. I then want all of these classes to be placed into a dictionary for reference.