Dan Abramov
Dan Abramov

Reputation: 268235

Is there a difference between el.Attribute ("...") and el.Attribute (XName.Get ("..."))?

In our production code, I've seen XML attributes being read using explicit XName.Get call:

var name = element.Attribute (XName.Get ("name"));

I used to always pass a string to Attribute:

var name = element.Attribute ("name");

This is more readable but I wonder if there is any difference in logic or performance.

Upvotes: 0

Views: 1463

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500225

Well, there are two parts to this:

Are they calling the same Attribute method?

Yes. There's only one XElement.Attribute method, with an XName parameter, which means that in the latter case you are using the implicit string to XName conversion.

Does the implicit string to XName conversion do the same as XName.Get?

This isn't guaranteed - the documentation doesn't mention it. But I have no reason to doubt SLaks' analysis that the current implementation is the same.


Personally I always either use the conversion from string to XName or the addition operator between XNamespace and string to get an XName. I can't remember the last time I referred to it explicitly.

The conversions available are one of the beautiful things about LINQ to XML - it seems pointless to ignore them, IMO.

Upvotes: 1

SLaks
SLaks

Reputation: 887365

There is no difference whatsoever.
XName has an implicit cast from string which calls XName.Get.

You can see this in the source:

/// <summary>
/// Converts a string formatted as an expanded XML name ({namespace}localname) to an XName object. 
/// </summary>
/// <param name="expandedName">A string containing an expanded XML name in the format: {namespace}localname.</param> 
/// <returns>An XName object constructed from the expanded name.</returns> 
[CLSCompliant(false)]
public static implicit operator XName(string expandedName) { 
    return expandedName != null ? Get(expandedName) : null;
}

Upvotes: 6

Related Questions