Reputation: 17508
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,
Upvotes: 1
Views: 91
Reputation: 1502376
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.
Upvotes: 2
Reputation: 115839
XName
has an a special implicit operator defined. Implicit operators allow you to perform, well, implicit type conversions.
Upvotes: 1