views:

31

answers:

4

I have created a dummy projet for testing collection and ICollection.I have a user class and wanted to create a collection.Example -

ICollection<User> users = new Collection<User>();
Collection<User> users = new Collection<User>();

Both code are working fine whether I use Collection or I collection.Now can anyone tell me what is difference between above two line?

Thanks in advance.

+1  A: 

ICollection is an Interface. Collection implements ICollection, so it works. ICollection is not a class, so this wont work:

ICollection<User> users = new ICollection<User>();

..because you can't instantiate an interface. An interface just describes what a class must implement.

Mr Q.C.
A: 

because users is reference. in both samples it points to same object. behavior is defined by class of object and it is same.

Andrey
+1  A: 

Collection<T> is just an implementation of ICollection<T>. If someone creates another class that implements from ICollection<T>, you can easily use that one by replacing your first line with:

ICollection<User> users = new MyCustomCollectionCollection<User>();

Later on in the code, you don't have to fix anything since the same interface is still used.

Peter van Kekem
A: 

The first line ICollection<User> users = new Collection<User>(); creates a reference to an object (Collection) that implements the ICollection interface whereas the second line Collection<User> users = new Collection<User>(); creates a reference to an object that is a concrete implementation of the class Collection where T = User.

In usage terms you would look to use the ICollection reference where your subsequent code needed to be agnostic about the type of collection it was dealing with, i.e. you could provide any object that implements ICollection and your code would still work. Great if your code is not tightly coupled (which we all want of course).

Using Collection as the reference tightly couples your processing code to Collection class, a specific implementation of ICollection and while you might still only use the methods defined in the interface, you might also use some specific features of the class and then you won't be able to easily replace the collection object with something different. There are good reasons for this but it's bit beyond the scope of an answer here, search for Dependency Injection and Inversion of Control here and I'm sure you'll find loads of background info.

Lazarus