Consider the example:
IList<string> _lstColl = new[] { "Alex", "Sam", "Gates", "Riaz" };
I can initialize it as:
string[] _stringBag = new[] { "Alex", "Sam", "Gates", "Riaz" };
What are the advantages of having Interface here?
Consider the example:
IList<string> _lstColl = new[] { "Alex", "Sam", "Gates", "Riaz" };
I can initialize it as:
string[] _stringBag = new[] { "Alex", "Sam", "Gates", "Riaz" };
What are the advantages of having Interface here?
The advantage is that it shows to readers that you're not using the fact that it happens to be an array. I tend to declare local variables as the most general type which contains all the functionality I need. For instance, I'll do:
using (TextReader reader = File.OpenText(...))
instead of specifying StreamReader
.
It's rarely hugely important, but it does make it easier to change the details of the implementation. For example, suppose for whatever reason we wanted to change your example to use a List<T>
instead of an array.
You can change this:
IList<string> _lstColl = new[] { "Alex", "Sam", "Gates", "Riaz" };
to this:
IList<string> _lstColl = new List<string> { "Alex", "Sam", "Gates", "Riaz" };
and know it'll still compile. Some of the semantics may not be the same, so you still need to be careful - but at least you know it won't be using any array-specific methods.
This is an example of generics and you are creating an IList with string datatype.
Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations.
Read more here
There are no advantages or disadvantages. If your code requires an IList, then give it one. If your code requires an array, then give it one.
I don't really understand why an array implements IList. When you call Add, it throws an exception. An array does not have IList semantics, because it is not resizable. That's why I avoid having an array as IList. If I need a list, i would write it like this:
IList<string> _lstColl = new List<string>() { "Alex", "Sam", "Gates", "Riaz" };
(PS: There are quite a few problems with using of the collection interfaces of the standard framework, like missing methods and even missing interfaces. When you are working with collection interfaces, as usual for instance when using NHibernate, you recognize that they are sometimes badly designed. The developers of this interfaces didn't seem to use them a lot I think. Just my opinion.)