Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List interface: from Java to C#

I'm a Java programmer learning C# these days.

Usually in Java when using lists, it should be preferrable programming against its interface in order to switch between implementations:

List<Object> list = new ArrayList<Object>();
//or
list = new LinkedList<Object>(); 

What about C# ? Does exist a similar approach? Can someone show me an example? Since now I'm building a list this way, but I don't think List is an interface:

List<int> list = new List<int>();
list.Add(2);
like image 942
Heisenbug Avatar asked Oct 27 '11 07:10

Heisenbug


3 Answers

In .NET it is also preferable to work with the highest possible object in the hierarchy. You could use the IList<T> interface:

IList<int> list = new List<int>();
list.Add(2);

And if you don't need to access the list by index you could also use the ICollection<T> interface which is even higher in the hierarchy.

Or if you only want to enumerate through the list you could use the highest possible interface which is IEnumerable<T>:

IEnumerable<int> list = new List<int>(new[] { 1, 2, 3 });
foreach(int item in list)
{
    ...
}
like image 94
Darin Dimitrov Avatar answered Sep 28 '22 09:09

Darin Dimitrov


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

in C# it's easy - if it starts with an I its an interface.

like image 23
Jamiec Avatar answered Sep 28 '22 08:09

Jamiec


List<T> implements a number of interfaces, including IList<T> and ICollection<T>. You may need to examine your code to determine which interface is most appropriate.

like image 35
Damien_The_Unbeliever Avatar answered Sep 28 '22 07:09

Damien_The_Unbeliever