Alma
Alma

Reputation: 4390

Return null in case of empty object in C#

I try this statement to check if SSN is not empty return the value in SSNstr otherwise return null. But this is returning me error Object reference not set to an instance of an object. when SSN is empty.

  Model.DocumentData dt = new Model.DocumentData();     
 dt.SSNstr = (dt.SSNstr == null ? null :(string)individual.XPathSelectElement("Individual/SSN")).Insert(5,"-").Insert(3,"-");

this is dt class:

      [DataMember]
      public string SSNstr = string.Empty;

Please attention here I know how to check null value but I like to do it in same line of code. As I have so many fields like this that I need to check I prefer to check in 1 line of the code or change something in dt class that take care of it.

Upvotes: 0

Views: 797

Answers (5)

Mr Lister
Mr Lister

Reputation: 46559

Check your parentheses.

If dt.SSNstr is null, the expression is not returning null, it is returning (null).Insert(5,"-").Insert(3,"-") which causes the error. You can't insert anything into null.

One solution would be to write

dt.SSNstr = dt.SSNstr == null ? null :(string)individual.XPathSelectElement("Individual/SSN").Insert(5,"-").Insert(3,"-");

but then if would be better to have

if (dt.SSNstr!=null)
  dt.SSNstr =(string)individual.XPathSelectElement("Individual/SSN").Insert(5,"-").Insert(3,"-");

otherwise you're assigning null to a variable that is already null.

Edit: As the other answers say, you should check for IsNullOrEmpty, not just equal to null. You start out with string.Empty, but later you assign null to it.

Upvotes: 2

Rahul
Rahul

Reputation: 77866

Per your edit, you can simply do like

    dt.SSNstr = ((individual.XPathSelectElement("Individual/SSN") as string) == null) ? null : (individual.XPathSelectElement("Individual/SSN") as string).Insert(5,"-").Insert(3,"-");

Upvotes: 1

MPelletier
MPelletier

Reputation: 16677

Null and "empty string" are two different things. Make your check with String.IsNullOrEmpty or String.IsNullOrWhiteSpace.

At the end of that, the result of your XPath query might be empty. Why don't you break that up into a few lines?

Addendum: It really looks like your XPath query result is empty. You're working on the assumption that it will not be empty. Do you have that assurance? When you're programming, don't trust anyone. Including yourself.

Upvotes: 7

var test = "";

var a = string.IsNullOrEmpty(test) ? null : test;

I hope it´s Helps.

Upvotes: 1

Batman
Batman

Reputation: 541

dt might be null in this case. I would check if that object actually has a value. You would need to instantiate dt, then you can set the value of dt.SSNstr.

Upvotes: 1

Related Questions