Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

edit: Matt ninja'd it :)

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...

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top