patel.milanb
patel.milanb

Reputation: 5992

How can i add object to a ICollection<> Objects

i am having a simple demo class like this...

Employee

public class Employee
        {
            public string Name { get; set; }
            public string Email { get; set; }

        }

one more class AddressDetails

public class AddressDetails
        {
            public string Address1 { get; set; }
            public string City { get; set; }
            public string State { get; set; }
        }

one more EmpAdd

public class EmpAdd 
        {
            public ICollection<Employee> Employees { get; set; }
            public ICollection<AddressDetails> AddressDetails { get; set; }
        }

ok, when i am passing some values in class like this..

Employee newEmp = new Employee();
            newEmp.Email = "[email protected]";
            newEmp.Name = "Judy";

            AddressDetails newAddress = new AddressDetails();
            newAddress.Address1 = "UK";
            newAddress.City = "London";
            newAddress.State = "England";

all works fine...

but when i am trying to add this two in EmpAdd it gives me error "Object reference not set to an instance" please help ...this is just a dummy .. i have 7 entities in which i am facing the same problem....

EmpAdd emp = new EmpAdd();
            emp.Employee.Add(newEmp);
            emp.AddressDetails.Add(newAddress);

Upvotes: 1

Views: 697

Answers (3)

Adrian Iftode
Adrian Iftode

Reputation: 15663

emp.Employee and emp.AddressDetails are not instantiated. You need to create a constructor which instantiates them

public class EmpAdd 
{
    public ICollection<Employee> Employees { get; set; }
    public ICollection<AddressDetails> AddressDetails { get; set; }
    public EmpAdd()
    {
        Employees = new List<Employee>();
        AddressDetails = new List<AddressDetails>();
    }
}

Upvotes: 2

Catalyst
Catalyst

Reputation: 1018

What @Adrian Iftode means is this:

EmpAdd emp = new EmpAdd();
        emp.Employee = newEmp;
        emp.AddressDetails = newAddress;
        emp.Employee.Add(newEmp);
        emp.AddressDetails.Add(newAddress);

This should fix this.
Anyway, stick to @Menno van den Heuvel's suggestion.

Upvotes: 0

Menno van den Heuvel
Menno van den Heuvel

Reputation: 1861

Your ICollection property is never initialized. The auto properties implement a field behind your property, but it still needs to be assigned to. I suggest making your property read-only (get rid of the set), implement the field behind it yourself, and initialize it on declaration:

private List<Employee> _employees = new List<Employee>();

public ICollection<Employee> Employees { 
    get
    {
        return _employees;
    }
}

Upvotes: 1

Related Questions