0

This is my code..I cant add a null value to the list.Getting null reference exception.how to avoid it

List<string> lst = new List<string>();
 var empPersonal = context.tblEmployeePersonalDetails.Where(x => x.isDelete == false && x.empId == id).First();
lst.Add(empPersonal.gender.ToString() != null ? empPersonal.gender.ToString() :string.Empty);
Safeena
  • 395
  • 2
  • 7
  • 20
  • which line are you getting the error on? – imlokesh May 21 '15 at 07:22
  • In almost all cases NullReferenceException is same. Refer [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Sriram Sakthivel May 21 '15 at 07:23
  • `NullReferenceException` doesn't mean that the *item* you're adding is `null`. You can add a null string to the list without problems. What the runtime is telling you is that you are trying to access a property on a reference which points to `null`.E.g.: 1) `context` is null, but you are accessing `context.tblEmployeePersonalDetails`, or 2) `empPersonal` is null, but you are accessing `empPersonal.gender`, or 3) `empPersonal.gender` is null, but you are accessing `empPersonal.gender.ToString()`. You might also want to use `FirstOrDefault` instead of `First`. – Groo May 21 '15 at 07:27

3 Answers3

1
List<string> lst = new List<string>();
var empPersonal = context.tblEmployeePersonalDetails
    .FirstOrDefault(x => x.isDelete == false && x.empId == id);
lst.Add(empPersonal != null ? empPersonal.gender.ToString() :string.Empty);
Szer
  • 3,071
  • 14
  • 34
1

If empPersonal.gender is null, calling empPersonal.gender.ToString() will yield an error.

What you probably meant to write was:

lst.Add(empPersonal.gender != null ? empPersonal.gender.ToString() : string.Empty);
Heinzi
  • 151,145
  • 51
  • 326
  • 481
0

Perhaps

Change

lst.Add(empPersonal.gender.ToString() != null ? empPersonal.gender.ToString() :string.Empty);

To

lst.Add(empPersonal != null && empPersonal.gender != null ? empPersonal.gender.ToString() :string.Empty);

This catches empPersonal is null and the empPersonal.gender is null because both could be null.

Schuere
  • 1,519
  • 17
  • 31