Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize IList<T> C#

Tags:

Is there a particular way to initialize an IList<T>? This does not seem to work:

IList<ListItem> allFaqs = new IList<ListItem>(); // Error I get here: Cannot create an instance of the interface 'IList<ListItem>' 

ReSharper suggests to initialize it like so:

IList<ListItem> allFaqs = null; 

But won't that cause a Null Reference Exception when I go to add items to this list?

Or should I just use List<ListItem>?

Thanks!

like image 410
Anders Avatar asked Aug 28 '09 19:08

Anders


People also ask

How do I initialize an IList?

IList<ListItem> allFaqs = new List<ListItem>(); and it should compile. You'll obviously have to change the rest of your code to suit too. IList<ListItem> test = new ListItem[5]; IList<ListItem> test = new ObservableCollection<ListItem>(allFaqs);

How do you define IList?

List and IList are used to denote a set of objects. They can store objects of integers, strings, etc. There are methods to insert, remove elements, search and sort elements of a List or IList. The major difference between List and IList is that List is a concrete class and IList is an interface.

What is IList in C sharp?

In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.

Which interface represents a collection of objects that can be individually accessed by index?

IList Interface (System.


1 Answers

The error is because you're trying to create an instance of the interface.

Change your code to:

List<ListItem> allFaqs = new List<ListItem>(); 

or

IList<ListItem> allFaqs = new List<ListItem>(); 

and it should compile.

You'll obviously have to change the rest of your code to suit too.

You can create any concrete type that implements IList like this, so

IList<ListItem> test = new ListItem[5];  IList<ListItem> test = new ObservableCollection<ListItem>(allFaqs); 

and so on, will all work.

like image 51
ChrisF Avatar answered Sep 26 '22 03:09

ChrisF