Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null check on XElement

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.)

like image 333
lazymf Avatar asked May 23 '11 10:05

lazymf


2 Answers

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.

like image 80
aL3891 Avatar answered Oct 14 '22 03:10

aL3891


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.

like image 7
Øyvind Bråthen Avatar answered Oct 14 '22 04:10

Øyvind Bråthen