I have a couple of properties in my class which are of ICollection type. When I try to add any data in those properties without creating their new instance compiler shoots me an error saying I need to create instance of them. My question is, when I create a new instance of a class, then indirectly I create a new memory for the entire class and those properties (ICollection type) are inside class, so why do I need to create new instance for those properties.
public class User
{
public string UserId { get; set; }
public ICollection<Address> Addresses { get; set; }
public ICollection<Contact> Contacts { get; set; }
}
public class Address
{
public string AddressId { get; set; }
}
public class Contact
{
public string ContactId { get; set; }
}
class Program
{
static void Main(string[] args)
{
User user = new User();
user.Contacts = new Collection<Contact>() {new Contact() {}};
user.Addresses.Add(new Address()
{
});//Throws Error
Console.ReadKey();
}
}