What is the difference between casting and coercing?

后端 未结 7 1732
名媛妹妹
名媛妹妹 2020-12-02 06:45

I\'ve seen both terms be used almost interchangeably in various online explanations, and most text books I\'ve consulted are also not entirely clear about the distinction.

相关标签:
7条回答
  • 2020-12-02 07:10

    Casting preserves the type of objects. Coercion does not.

    Coercion is taking the value of a type that is NOT assignment compatible and converting to a type that is assignment compatible. Here I perform a coercion because Int32 does NOT inherit from Int64...so it's NOT assignment compatible. This is a widening coercion (no data lost). A widening coercion is a.k.a. an implicit conversion. A Coercion performs a conversion.

    void Main()
    {
        System.Int32 a = 100;
        System.Int64 b = a;
        b.GetType();//The type is System.Int64.  
    }
    

    Casting allows you to treat a type as if it were of a different type while also preserving the type.

        void Main()
        {
            Derived d = new Derived();
            Base bb = d;
            //b.N();//INVALID.  Calls to the type Derived are not possible because bb is of type Base
            bb.GetType();//The type is Derived.  bb is still of type Derived despite not being able to call members of Test
        }
    
        class Base 
        {
            public void M() {}
        }
    
        class Derived: Base
        {
            public void N() {}
        }
    

    Source: The Common Language Infrastructure Annotated Standard by James S. Miller

    Now what's odd is that Microsoft's documentation on Casting does not align with the ecma-335 specification definition of Casting.

    Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.

    ...This sounds like Coercions not Casting.

    For example,

      object o = 1;
      int i = (int)o;//Explicit conversions require a cast operator
      i.GetType();//The type has been explicitly converted to System.Int32.  Object type is not preserved.  This meets the definition of Coercion not casting.
    

    Who knows? Maybe Microsoft is checking if anybody reads this stuff.

    0 讨论(0)
提交回复
热议问题