C# IList

Lists and arrays implement IList. This interface is an abstraction that allows list types to be used with through a single reference type. With it, we can create a single method to receive an int[] or a List<int>.

Example

First, with the IList generic interface, you must specify a type parameter. If you want your method to act upon ints, you can use IList<int>.

In this program, we introduce the Display method, which receives an IList<int> parameter. It accesses the Count property and then uses the enumerator in a foreach-loop.

Int TypeForeach Loop Examples

Program that uses IList<T> generic interface [C#]

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);
	}
    }
}

Output

Count: 3
1
2
3
Count: 3
5
7
9

Main method

Passing collections to Display method.You can see in the Main method that you can pass an int[] or a List<int> to the Display method. These are implicitly cast to their base interface IList<int>. Arrays always implement IList<T>. The List type also implements IList<T>.

Array TypesList Examples

Implement IList<T>

Programming tip

You can also implement IList<T> for a custom class in your C# program. The methods required by this contract are an indexer; the IndexOf method; the Insert method; and the RemoveAt method.

Indexer Examples

Summary

The C# programming language

In this article, 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.

Note:With this layer of abstraction, you can formulate more concise ways of acting upon your data.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值