简体   繁体   中英

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.

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.

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.

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 .

根据您的修改,您可以像

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

var test = "";

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

I hope it´s Helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM