Search code examples
c#stringilist

error: Object reference not initialised


I have the following code in C#:

IList<string> myList = null;
myList.Add(temp);

temp is a string that is decalred elsewhere and is not null (I checked it). I keep getting the following error at the line myList.Add(temp); "Object reference not initialised to an instance of an object"

What am I doing wrong here???

Updating the quesiton: I have already tried new
IList<string> myList = new List<string>();
as most of you suggested andget the following from Intellisense:

Cannot create an instance of the abstract class or interface Systems.Collections.Generic.Ilist.

Thanks for your previous answers. Now I am running into a peculiar problem. My datareader has an empty string in it. (1 field in the sql server table is blank. that is string.Empty). Is there a way to get rid of this inside the reader (I mean rdr here)??


Solution

  • The line:

    IList<string> myList = null;
    

    does not give you a list, but an empty reference to where a list could be.

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

    would properly instantiate myList, so you can use it (Add, Remove, etc.).