List VS IList IN C#

Taha Temuri
2 min readSep 24, 2020

Hello,

Today we will learn the difference between List and IList in C#

I assume that everyone understand what is an interface.

The basic difference between these two is, In order to create a List we have to tell the type

Example:

List<string> or List<YourClass> etc

whereas IList is an interface WE DONT HAVE TO… Now what does it means? what is the difference …?

Consider somewhere in your code the method receive Lists but unfortunately in a case the type changes

Example:

GetProperties(new List<MYclass>());GetProperties(new List<string>());So if you decorate your method to receive likeGetProperties(List<MYclass>list){//this will get fail if type not matches}

Real World Example:

this code use to log all user activities on a web application so in case of post or get this method gets all parameters with prop name and its value.

See in case of ‘System.Collection.Generic’ means the parameter that was posted is a list type WE NEED TO GET ITS ALL PROPERTIES, now here is the issue if we use List instead of IList we have to define type which does not cater generic criteria.

foreact(var listItem in (List<someclassnamehardcoded>())value){
//here failure if list not matches the type
}

Since post parameters may be List<Checkboxes> or List<class> or List<string> etc.

We use IList because ALL TYPE OF LIST IMPLEMENTS ILIST , hence digestable by IList and we can read all its properties using.

In this case posted parameter is of type CheckBoxListItems so by using IList we Win!

Thanks for reading , Please dont forget to give and clap and subscribe.

--

--