Pratap Singh
Pratap Singh

Reputation: 63

why do we need to create new instence of Icollection type property

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();
    }
}

Upvotes: 2

Views: 2056

Answers (2)

krillgar
krillgar

Reputation: 12805

Agreed with everything that nvoigt said in their answer. All reference type properties (anything other than int, DateTime, string, etc.) defaults to a null when they are a property on a new object.

What you'll want to do in order to get around that NullReferenceException is to instantiate all of those properties when you create a new object.

public User() {
    this.Addresses = new List<Address>();
    this.Contacts = new List<Contact>();
}

With that in your constructor, you'll be able to add items to those collections without having to instantiate them outside your objects.

Upvotes: 1

nvoigt
nvoigt

Reputation: 77294

Because ICollection is an interface and interfaces are reference types. That means by creating a variable, you did not create an instance. That only happens when you call new. You only created a reference to an instance.

By default, a reference is null which means it's not set to any particular instance. That's why when you call a method on a reference that was not set to an instance, you get a NullReferenceException.

Upvotes: 4

Related Questions