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);
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)
{
...
}
IList<int> = new List<int>();
in C# it's easy - if it starts with an I
its an interface.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With