Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAttribute default value if not existing on XElement

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?

like image 454
Mike Avatar asked Dec 06 '12 16:12

Mike


1 Answers

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.

like image 58
Jon Skeet Avatar answered Sep 17 '22 16:09

Jon Skeet