user2167089
user2167089

Reputation: 151

object not set to instance of an object error while creating a list

I have alist that needs to get populated on page load the following is the code in dal

      public List<KeyValuePair<Guid, string>> GetProjectName()
    {
        List<KeyValuePair<Guid, string>> List = null;
        try
        {
            using (LiveLeaseEntities db = LiveLeaseHelper.GetDbLiveLeaseEntities())
            {
                var projects = (from p in db.t_Project
                                where p.IsActive == true
                                select p).ToList();
                if (projects != null)
                {
                    foreach (t_Project p in projects)
                    {
                        List.Add(new KeyValuePair<Guid, string>(p.ProjectId, p.ProjectName));
                    }
                }

                return List;

i get object not set to instance of object error. steping through projects show a count of 7 but i get error.

Upvotes: 0

Views: 902

Answers (3)

Sachin
Sachin

Reputation: 40970

You have set your List as null by this line

List<KeyValuePair<Guid, string>> List = null;

and then trying to add item into this. so you need to make the instance of that List type, so do something like this

List<KeyValuePair<Guid, string>> list =  new List<KeyValuePair<Guid, string>>();

and now trying to add item into this list

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

You need to set List variable to something other than null, like this:

List<KeyValuePair<Guid, string>> List = new List<KeyValuePair<Guid, string>>();

Otherwise, this line will trigger the exception:

 List.Add(new KeyValuePair<Guid, string>(p.ProjectId, p.ProjectName));
 // ^
 // |
 // +------ List variable is null

Note that the if (projects != null) condition is unnecessary: ToList() could return an empty list, but it never returns null. In addition, you do not need to use == true with Boolean variables, unless they are nullable.

Finally, the foreach loop can be folded with LINQ's Select, like this:

try {
    using (LiveLeaseEntities db = LiveLeaseHelper.GetDbLiveLeaseEntities()) {
        return db.t_Project
            .Where(p => p.IsActive)
            .Select(p => new KeyValuePair<Guid, string>(p.ProjectId, p.ProjectName))
            .ToList();
     }
} catch {
   ...
}

Upvotes: 3

Steve
Steve

Reputation: 216323

You have declared the variable List (by the way, use absolutely another name)

List<KeyValuePair<Guid, string>> List = null;

but never initialized

List<KeyValuePair<Guid, string>> List = new List<KeyValuePair<Guid, string>>();

Of course when you try to use this variable you get the NullReferenceException

List.Add(.....) <- NullReferenceException without the initialization

Upvotes: 1

Related Questions