Home
C#
IList Example
Updated Feb 9, 2024
Dot Net Perls
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.
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.
interface
List
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.
Detail The Display method accesses the Count property and then uses the enumerator in a foreach-loop.
Property
foreach
Info You can pass an int[] or a List int to the Display method. These are implicitly cast to their base interface IList int.
Note Arrays always implement IList T. The List type also implements IList T.
using System; using System.Collections.Generic; class Program { static void Main() { int[] array = new int[3]; array[0] = 1; array[1] = 2; array[2] = 3; Display(array); List<int> list = new List<int>(); list.Add(5); list.Add(7); list.Add(9); Display(list); } static void Display(IList<int> list) { Console.WriteLine("Count: {0}", list.Count); foreach (int value in list) { Console.WriteLine(value); } } }
Count: 3 1 2 3 Count: 3 5 7 9
IEnumerable use. Consider this alternative program—it uses IEnumerable instead of IList. With IEnumerable we do not have a Count property.
IEnumerable
But We can use the Count() extension method from LINQ on an IEnumerable. This will return the same value.
Count
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.
Indexer
List Insert
List Remove
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 9, 2024 (edit).
Home
Changes
© 2007-2025 Sam Allen