Null check on XElement

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.


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.


There is a great article on the CodeProject for such actions: http://www.codeproject.com/KB/cs/maybemonads.aspx

public static TResult With<TInput, TResult>(this TInput o, 
       Func<TInput, TResult> evaluator)
       where TResult : class where TInput : class
{
  if (o == null) return null;
  return evaluator(o);
}

string valueEl = this.With(x => elem.Element("TagName")
                  .With(x => x.Value);

Other examples are available on the CodeProject.


A crazy ?? approach:

// make this a member-variable somewhere
var emptyElement = XElement.Parse("<x></x>");

(elem.Element("TagName") ?? emptyElement).Value;

Would have preferred an extension method though.