There's an implicit conversion from string to XName
, basically. That's why this works too:
XName name = "element-name";
You can do this with your own types if you provide an appropriate implicit conversion - but generally I wouldn't do this. (Note that you can provide the conversion either at the source type or the target type; in this case it's the target type (XName
) which provides the conversion, not the source type (string
).)
LINQ to XML does all kinds of interesting things with operator and conversion overloads which would normally be a bad idea, but happen to work really well in the context of XML. I particularly like the namespace handling:
XNamespace ns = "some namespace uri";
XName fullName = ns + "element-name";
Another useful oddity is the explicit conversions from XAttribute and XElement to various types; for example you can do:
XAttribute attribute = ...;
int? value = (int?) attribute;
The beauty of the nullability here is that if attribute
is null, then the result will be too. This allows you to handle optional attributes (and elements) very cleanly.