views:

115

answers:

4

I noticed you can do this sort of thing in C#:

XNamespace c = "http://s.opencalais.com/1/pred/";

Notice the string value is implicitly converted to different type. Are there other places this can be done? What are some common patterns and practices around this sort of thing?

+5  A: 

This can happen whenever an implicit conversion operator is defined. All in all it is quite rare.

Matt Greer
+4  A: 

this should help http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx

edit: Matt ninja'd it :)

liho1eye
+2  A: 

Surprisingly, the first time I saw this was on the Wikipedia article about C# Conversion operators, I've never actually seen anyone use this before. Seems like it would hurt readability and confuse a lot of developers...

wsanville
In my experience, it only confuses people unaware of this possibility. Once you know the above is legit code, and that implicit conversion is possible, it is obvious there is an implicit conversion operator. This kind of conversions are to be used sparingly anyway.
Dykam
+1  A: 

Basically XNamespace provide an operator that performs implicit conversion.

I guess most common-sense guidelines apply, only use it where it makes sense and avoid confusion. The biggest problem is unintended implicit conversion which could potentially open up for programming errors. You can avoid this and still provide a conversion with an explicit conversion operator.

An example of a case where you would want to use an explicit conversion operator instead of an implicit one would be a integer class that allows conversion from a floating point type; an implicit conversion would hide the truncation/rounding that would have to take place and could thus make the user very confused (and probably be the source of bugs.)

In my code I've used it a couple of times, for example in a very simple validation result struct which provided implicit conversion to bool (but not from). This allowed me to do if (result) { ... } (the jury is still out about the usefulness of this though :)).

Guess most of its use is for "simple" datatypes, like big integers, decimals and likewise.

Skurmedel
@Skurmedel Interesting use of converting a struct to bool.
Paul Fryer