tags:

views:

42

answers:

3

Hi,

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,

A: 

XName converts to and from string implicitly.

See MSDN:

XName does not contain any public constructors. Instead, this class provides an implicit conversion from String that allows you to create an XName.

Oded
None of the overloads takes a string as the first parameter though - so this doesn't explain what's going on.
Jon Skeet
@Jon Skeet -Yep, I was too fast on the gun. Answer corrected.
Oded
+2  A: 

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.

Jon Skeet
http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx
spender
@spender: Thanks, added that link to the answer.
Jon Skeet
I like the API for LINQ to XML, I think the use of implicit conversion works really well. Just looking for an excuse to use it somewhere. Thanks again for your responses.
Sir Psycho
+1  A: 

XName has an a special implicit operator defined. Implicit operators allow you to perform, well, implicit type conversions.

Anton Gogolev