Monday, 3 July 2017

generics - Initialize IList C#



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




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


ReSharper suggests to initialize it like so:



IList 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?



Thanks!


Answer



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



Change your code to:




List allFaqs = new List();


or



IList allFaqs = new List();


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 test = new ListItem[5];

IList test = new ObservableCollection(allFaqs);


and so on, will all work.



No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...