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.
Here we specify a subroutine called Display that receives an IList
of type Integer. We call Display()
twice in the Main
sub.
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 ModuleCount: 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 Module500 600 700
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.