C# IList ExampleUse the IList generic interface, which is implemented by the List and array types.
IList. In C# lists and arrays implement IList. This interface is an abstraction that allows list types to be used with through a single reference.
Type notes. With IList, we can create a single method to receive an int array, or a List of ints. This is powerful—it allows us to combine and reuse code.
An example. With IList, you must specify a type parameter. If you want your method to act upon ints, you can use IList<int>. Any type (string, object) can be specified.
Next In this program, we introduce the Display method, which receives an IList<int> parameter.
Display This method accesses the Count property and then uses the enumerator in a foreach-loop.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Display(new int[] {1, 2});
Display(new List<int>() {1, 2});
}
static void Display(IEnumerable<int> list)
{
foreach (int value in list)
{
Console.WriteLine(value);
}
}
}1
2
1
2
Discussion. You can also implement IList<T> for a custom class. The methods required are an indexer, the IndexOf method, the Insert method, and the RemoveAt method.
A summary. We looked at the IList generic interface, which can be used as an abstraction for arrays and Lists. The IList generic interface is separate from the regular IList interface.