0

I have created a new empty List of type User (User is an Entity in my EDM)

List<User> AvailableLocums = new List<User>();
AvailableLocums = null;

I also have another List of type User which is populated with the results of a query

List<User> Locums = _shiftDateService.GetAvailableLocums(id, shiftDate.shiftDateID).ToList();

I then wish to loop around the Locums List, do some logic, and then add the User to my AvailableLocums List

foreach (var locum in Locums)
{
   //Do some logic

   AvailableLocums.Add(locum);

}

However, when I try to do this I get the following error

Object reference not set to an instance of an object.

I then tried to amend my code and do the following

foreach (var locum in Locums)
{
       //Do some logic

       User locumUser = new User();
       locumUser = locum;

       AvailableLocums.Add(locumUser);     
}

But again I get the same error

Object reference not set to an instance of an object.

Could someone please help me with this?

Thanks.

5 Answers 5

5

You are telling your variable "AvailableLocums" to no longer point to anything in memory.

Remove: AvailableLocums = null;

how about:

List<User> AvailableLocums;
List<User> Locums;

// get id for shift date service
// int id = ...

// get locums from shift date service 
Locums = _shiftDateService.GetAvailableLocums(id, shiftDate.shiftDateID).ToList();

// time to add to AvailableLocums
if(AvailableLocums == null)
    AvailableLocums = new List<User>();

foreach (var locum in Locums)
{
   //Do some logic

   AvailableLocums.Add(locum);
}
Sign up to request clarification or add additional context in comments.

Comments

3

You are nulling out that list

List<User> AvailableLocums = new List<User>();
AvailableLocums = null; // HERE

hence, the exception. You don't need this line to make an empty list:

AvailableLocums = null;

Comments

1

get out this line :

AvailableLocums = null;

and it will be Ok ... You declaring new object and on next row set it to null?

Comments

0

try to

List<User> Locums = new List<User>();

before _shiftDateService.GetAvailableLocums...

Comments

0

Try this code.

List<User> AvailableLocums = null; 
List<User> Locums = _shiftDateService.GetAvailableLocums(id, shiftDate.shiftDateID).ToList();  
AvailableLocums = Locums.Where(newUserRecord => newUserRecord != null).ToList();

* you can take any name instead of "newUserRecord".

1 Comment

you can use Lambda expression instead of using foreach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.