My current project (C# 3.5) has a lot of code like this (elem is an instance of XElement):
textbox1.Text = elem.Element("TagName") == null ? "" : elem.Element("TagName").Value;
Is there any way to write the same thing without repeating a call elem.Element() and without use of extension methods? Maybe using lambdas? (But I cannot figure out how.)
XElement has a explicit conversion to String (and a bunch of other types) that will actually call .Value. In otherwords you can write this:
var value = (String)elem.Element("TagName");
i think this will return null if the actual element is null as well
-edit-
verified, here is an example:
var x = new XElement("EmptyElement");
var n = (String)x.Element("NonExsistingElement");
n
will be null after this.
Yes. you can write it like this:
(string)elem.Element("TagName") ?? "";
This is the null coalescing operator.
It means that if the left hand side is not null, then use the left hand side. If it is null, then use the right hand side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With