Reputation: 5105
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.
Upvotes: 0
Views: 3968
Reputation: 1
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".
Upvotes: 0
Reputation: 2317
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);
}
Upvotes: 5
Reputation: 2284
try to
List<User> Locums = new List<User>();
before _shiftDateService.GetAvailableLocums...
Upvotes: 0
Reputation: 1221
get out this line :
AvailableLocums = null;
and it will be Ok ... You declaring new object and on next row set it to null?
Upvotes: 1
Reputation: 191058
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;
Upvotes: 3