IList ExampleUse the IList interface to refer to Lists and arrays in the argument of a function.
This page was last reviewed on Feb 9, 2024.
IList. The IList interface is similar to IEnumerable, but it allows for both looping and a Count property. Types such as arrays and Lists implement IList.
By specifying a parameter of type IList, we can pass either an array or a List to a method. IList is generic, so we must specify a type parameter on it.
Example. Here we specify a subroutine called Display that receives an IList of type Integer. We call Display() twice in the Main sub.
Version 1 We create an Integer array of 3 elements (we specify the max element index). We can pass this, without casting, to Display.
Version 2 We create a generic List with Integer elements, and add 3 elements. We can also pass this List as an IList interface reference.
Module Module1 Sub Main() ' Version 1: create Integer array and use as IList. Dim array(2) As Integer array(0) = 1 array(1) = 2 array(2) = 3 Display(array) ' Version 2: create Integer List and use as IList. Dim list As List(Of Integer) = New List(Of Integer)() list.Add(5) list.Add(7) list.Add(9) Display(list) End Sub Sub Display(list as IList(Of Integer)) ' Receive an IList, and print its Count and elements. Console.WriteLine("Count: {0}", list.Count) For Each value In list Console.WriteLine(value) Next End Sub End Module
Count: 3 1 2 3 Count: 3 5 7 9
IEnumerable. How is IList different from IEnumerable? With IList, we have a Count property, whereas on IEnumerable, we can only enumerate the collection with For Each.
Module Module1 Sub Main() ' Use Integer array as IEnumerable. Dim array() As Integer = { 500, 600, 700 } X(array) End Sub Sub X(list as IEnumerable(Of Integer)) ' Receive an IEnumerable, which does not have a Count property. For Each value In list Console.WriteLine(value) Next End Sub End Module
500 600 700
Summary. With IList, we can build a function in VB.NET that receives either a List or an array—or any other type that implements IList. This can lead to more reusable code, and simpler programs.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 9, 2024 (new).
© 2007-2024 Sam Allen.