0

I am just a learner.I am getting null reference exception for the following snippet.Please correct the mistake and tell me what's wrong with this code.

  class Program
    {
        static void Main(string[] args)
        {
            Company objcompany = new Company();

            Employee obj1 = new Employee(101, "Test1");
            Employee obj2=  new Employee(102, "Test2");
            Employee obj3 = new Employee(103, "Test3");

            objcompany.EmpList.Add(obj1);
            objcompany.EmpList.Add(obj2);
            objcompany.EmpList.Add(obj3);

            foreach (var emp in objcompany.EmpList)
            {
                Console.WriteLine(emp.EmpId + " " + emp.EmpName);
            }

            Console.ReadKey();
        }
    }

    class Company
    {
        public List<Employee> EmpList { get; set; }
    }

    class Employee
    {
        public int EmpId { get; set; }
        public string EmpName { get; set; }

        public Employee(int empid, String empname)
        {
            this.EmpId = empid;
            this.EmpName = empname;
        }
    }

i have created 3 classes.[Employee,Company,Program].I want to add employees into the collection.I am processing the code in the program class.

Rahman
  • 320
  • 1
  • 7
  • 22
Wiki
  • 96
  • 1
  • 8

1 Answers1

1

You have not initialized EmpList. I would suggest you to initialize it in Company class constructor

class Company
{
    public Company()
    {
         EmpList = new List<Employee>();
    }
    public List<Employee> EmpList { get; set; }
}
Satpal
  • 126,885
  • 12
  • 146
  • 163