Add items to Generic List Collection in C#

Last Reply 9 months ago By dharmendr

Posted 9 months ago

How to Add items to Generic List Error

i am getting error "Object reference not set to an instance of an object."

    public  class Employee {
        public string Name { get; set; }
        public List<EmployeeDepartments> EmployeeDetails { get; set; }
    }


    public class EmployeeDepartments {
        public string Department { get; set; }
        public int Mark { get; set; }
    }


    private void Form1_Load(object sender, EventArgs e) {
            List<Employee> employees = new List<Employee>();
            try 
            {
                Employee emp = new Employee();
                emp.Name = "a";
                EmployeeDepartments dept = new EmployeeDepartments();
                dept.Department = "IT";
                dept.Mark = 100;
                emp.EmployeeDetails.Add(dept);
                employees.Add(emp);
            } 
            catch(Exception ex) {                
            }
        }
Posted 9 months ago

Hi yogesjoshi,

Refer the below modified code.

C#

public class Employee
{
    public string Name { get; set; }
    public List<EmployeeDepartments> EmployeeDetails { get; set; }
}

public class EmployeeDepartments
{
    public string Department { get; set; }
    public int Mark { get; set; }
}

protected void Form1_Load(object sender, EventArgs e)
{
    List<Employee> employees = new List<Employee>();
    List<EmployeeDepartments> depts = new List<EmployeeDepartments>();
    try
    {
        Employee emp = new Employee();
        emp.Name = "a";

        EmployeeDepartments dept = new EmployeeDepartments();
        dept.Department = "IT";
        dept.Mark = 100;

        depts.Add(dept);

        emp.EmployeeDetails = depts;
        employees.Add(emp);
    }
    catch (Exception ex)
    {

    }
}