Examples of implicit variable assignment in C #

I noticed that you can do such things in C #:

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

Note that the string value is implicitly converted to another type. Could there be other places? What are some common patterns and practices around these kinds of things?

+6
c # implicit-conversion
source share
4 answers

This can happen whenever an implicit conversion operator is defined. In general, this is quite rare.

+5
source share

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

edit: Matt ninja'd it :)

+4
source share

Surprisingly, the first time I saw this, on a Wikipedia article about C # conversion operators, I never saw anyone use this before. It seems like this will degrade readability and confuse many developers ...

+2
source share

Basically, XNamespace provides an operator that performs an implicit conversion.

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

An example of a case where you want to use the explicit conversion operator instead of the implicit will be an entire class that allows conversion from a floating-point type; an implicit conversion will hide the truncation / rounding that would have happened, and thus make the user very confused (and probably be a source of errors.)

In my code, I used it several times, for example, in a very simple structure of check results, which provided implicit conversion to bool (but not from). This allowed me to do if (result) { ... } (the jury still does not know the benefits of this :)).

Guess that most of its use is used for "simple" data types, such as large integers, decimal numbers, etc.

+1
source share

All Articles