views:

119

answers:

2

I am new to C#.I wish to know the differences of using Collections. I suspect ,the following question may be asked before(If so kindly show me the link).

What is the Difference between

IList<int> intCollection = new List<int>();

and

List<int> intCollection = new List<int>();
  1. Why should i expose my collection through interface.
  2. Is it just syntatic sugar for choosing the first approach?
  3. What would be the disadvantages will i face if i suppose to use the later approach?
  4. If the corresponsing interface exits,should initialize all collection class indirectly using their corresponding interface?
  5. Please show me the benefits in example of exposing collection through interface.
+5  A: 

Using an interface allows you to change the backing implementation without breaking any callers.

The two lines in your example amount to the same thing, but if you expose IList<T> as a property, you can change exactly what gets returned without calling code needing to change.

Suppose you have a class which exposes an List<int> as a property. All is fine, until later when you realise you need to handle an event raised when an item is added to this list. You can't; you're going to have to change the property type and therefore all the code that calls this. If you initially declare an IList<int> you can go ahead and change the concrete implementation to be something different (as long as it still supports the interface).

This is something picked up by StyleCop and dealt with in this question.

Graham Clark
An example that could be thought of here is the ability to swap in another collections library that implements `IList`, such as C5.
Marcus Griep
+2  A: 

The benefits of using an interface is that it gives you flexibility for future changes. In your example, using an IList would allow you in the future to use a different implementation of IList and you would only have to change the object initializer.

Another scenario is where you have code that may need to interact with many different types of the same interface or the implementation is completely unknown. For example, a strategy pattern where you need to use different sorting algorithms and you want to use different implementations of IList depending on your sorting needs. Or you may be using a plugin model and have no idea what kind of a list another component will pass into your api but all you care is that it is a ILIST that abides by the IList contract.

Matt Wrock