XAttribute default value if not existing on XElement

Mike picture Mike · Dec 6, 2012 · Viewed 7.7k times · Source

Is there an easier/better way to return a default value if a XAttribute on a XElement is not existing?:

I'm trying to write this in a shorter way (cause it's a two-liner):

var a = root.Attribute("testAttribute");
var v = (a == null ? "" : a.Value);

My approach: via an extension method:

public static XAttribute Attribute(this XElement obj, string name, string defaultValue)
{
    if (obj.Attribute(name) == null)
        return new XAttribute(name, defaultValue);
    return obj.Attribute(name);
}

var v = root.Attribute("testAttribute", "").Value;

Will this have any side-effects like a massive negative speed impact ? Is there any better way to do that?

Answer

Jon Skeet picture Jon Skeet · Dec 6, 2012

There's a much easier way to do that:

var v = (string) root.Attribute("testAttribute") ?? "";

The explicit conversion from XAttribute to string returns null if the input XAttribute is null. The null-coalescing operator then effectively supplies the default value of an empty string.

Of course, you can still write your extension method, but I'd do it in terms of the above. I'd also change the name parameter to be of type XName instead of string, for more flexibility.