.Net Implicit Conversion Rules

What are general guidelines for when a custom implicit conversion can, should, or should not be defined?

I mean things like, for example, "an implicit conversion should never lose information," "an implicit conversion should never throw exceptions," or "an implicit conversion should never create new objects." I am sure that the first one is correct, the third one is not (or we could ever have an implicit conversion to structures), and I do not know about the second.

+3
source share
4 answers

The first is not as simple as you might expect. Here is an example:

using System;

class Test
{
    static void Main()
    {
        long firstLong = long.MaxValue - 2;
        long secondLong = firstLong - 1;

        double firstDouble = firstLong;
        double secondDouble = secondLong;

        // Prints False as expected
        Console.WriteLine(firstLong == secondLong);

        // Prints True!
        Console.WriteLine(firstDouble == secondDouble);        
    }
}

. , , , . ( , .)

EDIT: , , Microsoft.

+14

, - ( " " ), ; , . .

.

. , , , (, Nullable<T>, ).

+2

, , , (, , a==b, b==c a==c , , ), , . http://supercatnet.blogspot.com/2013/09/axioms-of-implicit-type-conversion.html ( ,.NET Framework , , , 't ).

, , , : - , , , , , "" , (, if (someLong == someFloat) , , long float , , a long a float (*), , , , - . , , , - , [Obsolete()]. , , .

(*) , , , , ; , float , long, float long , float long double.

+1

The cross-border incident that made me ask this question is a violation of the second. Namely, I have the Lazy <T> class (not all?) And began to wonder if I should not provide an implicit conversion to T. My instinct is to say yes, and the current version is that, but I'm not too sure.

0
source

All Articles