tags:

views:

586

answers:

8

Hi SO:

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!

+1  A: 

You need to do:

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

In your code you are trying to initialize an interface.

Kevin
+1  A: 

IList is an interface so you can't instantiate it. All sorts of classes implement IList. One such class that implements IList is List. You can instantiate it like so:

List<ListItem> allFaqs = new List<ListItem>();
Michael
+7  A: 

Your problem is that IList is an interface, not a class. You can't initialize an interface.

You can have an instance of an interface, but you need to initialize it with a class that implements that interface such as:

IList<string> strings = new List<string>();

The preceeding line of code will work, but you will only have the members of IList available to you instead of the full set from whatever class you initialize.

Justin Niessner
Well, you can if you cheat ;-p http://stackoverflow.com/questions/194484#1281522
Marc Gravell
+1 for the cheat! thanks Marc
Anders
+5  A: 

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

Change your code to:

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

and it should compile.

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

ChrisF
+1  A: 

You can't instantiate an interface (IList is an interface).

You would need to instantiate something that implements an IList,

like so:

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

There are other kinds of ILists, but List is a good one to start with.

Joseph
A: 

IList<T> is an interface. You need to instantiate a class that implements the interface:

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

List<T> implements IList<T>, and so can be assigned to the variable. There are also other types that also implement IList<T>.

adrianbanks
+1  A: 

IList is an Interface, not a class. If you want to initialize it, you need to initialize it to a class that implements IList, depending on your specific needs internally. Usually, IList is initialized with a List.

IList<ListItem> items = new List<ListItem>();
Michael Stum
A: 

IList is not a class; it's an interface that classes can implement. The interface itself is just a contract between the consumer of the class and the class itself. This line of code will work:

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

Does this help?

yodaj007