MonoTouch Linq for XML, how to make IF statement inline

Hello, I have the following question: is it possible to make an inline if statement?

var contact= new XElement("Contact", new XAttribute("id", id.ToString()), new XElement("ContactData", new XElement("Prefix", person.Prefix), new XElement("FirstName", person.FirstName) ); 

Because sometimes person.x can be null and bring me errors.

in advance for help.

+4
source share
3 answers

You can try something like this

 var contacts = new XElement("Contact", new XAttribute("id", id.ToString()), new XElement("ContactData", new XElement("Prefix", person.Prefix == null ? "" : person.Prefix), new XElement("FirstName", person.FirstName == null ? "" : person.FirstName)); 

Syntax (condition ? truevalue : falsevalue)

+5
source

What do you want if person.x null ?

If you want this to be the default value, you can wrap person.Prefix (for example) in a method that takes a string and returns a string or a valid default value.

Otherwise, it is:

 string x = null; string y = x ?? "f"; 

y becomes "f" if x is null , otherwise it gets the value x .

0
source

You should use the null-coalescing operator for the default values ​​if you do not want them to remain null :

 var contact = new XElement ("Contact", new XAttribute ("id", id.ToString ()), new XElement ("ContactData", new XElement("Prefix", person.Prefix ?? string.Empty), new XElement("FirstName", person.FirstName ?? string.Empty) ) ); 
0
source

Source: https://habr.com/ru/post/1338443/


All Articles