With the XElement class, its constructor clearly takes the daya type XName as its first parameter, however, if I pass in a string, it works and I don’t get a compile time error.
What’s going on here exactly and how can I implment this in my own code?
Thank you,
There’s an implicit conversion from string to
XName, basically. That’s why this works too: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:
Another useful oddity is the explicit conversions from XAttribute and XElement to various types; for example you can do:
The beauty of the nullability here is that if
attributeis null, then the result will be too. This allows you to handle optional attributes (and elements) very cleanly.