What is the difference between casting and coercing?

后端 未结 7 1731
名媛妹妹
名媛妹妹 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 06:50

    Type Conversion:

    The word conversion refers to either implicitly or explicitly changing a value from one data type to another, e.g. a 16-bit integer to a 32-bit integer.

    The word coercion is used to denote an implicit conversion.

    The word cast typically refers to an explicit type conversion (as opposed to an implicit conversion), regardless of whether this is a re-interpretation of a bit-pattern or a real conversion.

    So, coercion is implicit, cast is explicit, and conversion is any of them.


    Few examples (from the same source) :

    Coercion (implicit):

    double  d;
    int     i;
    if (d > i)      d = i;
    

    Cast (explicit):

    double da = 3.3;
    double db = 3.3;
    double dc = 3.4;
    int result = (int)da + (int)db + (int)dc; //result == 9
    
    0 讨论(0)
  • 2020-12-02 06:58

    Casting is the process by which you treat an object type as another type, Coercing is converting one object to another.

    Note that in the former process there is no conversion involved, you have a type that you would like to treat as another, say for example, you have 3 different objects that inherit from a base type, and you have a method that will take that base type, at any point, if you know the specific child type, you can CAST it to what it is and use all the specific methods and properties of that object and that will not create a new instance of the object.

    On the other hand, coercing implies the creation of a new object in memory of the new type and then the original type would be copied over to the new one, leaving both objects in memory (until the Garbage Collectors takes either away, or both).

    As an example consider the following code:

    class baseClass {}
    class childClass : baseClass {}
    class otherClass {}
    
    public void doSomethingWithBase(baseClass item) {}
    
    public void mainMethod()
    {
        var obj1 = new baseClass();
        var obj2 = new childClass();
        var obj3 = new otherClass();
    
        doSomethingWithBase(obj1); //not a problem, obj1 is already of type baseClass
        doSomethingWithBase(obj2); //not a problem, obj2 is implicitly casted to baseClass
        doSomethingWithBase(obj3); //won't compile without additional code
    }
    
    • obj1 is passed without any casting or coercing (conversion) because it's already of the same type baseClass
    • obj2 is implicitly casted to base, meaning there's no creation of a new object because obj2 can already be baseClass
    • obj3 needs to be converted somehow to base, you'll need to provide your own method to convert from otherClass to baseClass, which will involve creating a new object of type baseClass and filling it by copying the data from obj3.

    A good example is the Convert C# class where it provides custom code to convert among different types.

    0 讨论(0)
  • 2020-12-02 07:00

    Below is a posting from the following article:

    The difference between coercion and casting is often neglected. I can see why; many languages have the same (or similar) syntax and terminology for both operations. Some languages may even refer to any conversion as “casting,” but the following explanation refers to concepts in the CTS.

    If you are trying to assign a value of some type to a location of a different type, you can generate a value of the new type that has a similar meaning to the original. This is coercion. Coercion lets you use the new type by creating a new value that in some way resembles the original. Some coercions may discard data (e.g. converting the int 0x12345678 to the short 0x5678), while others may not (e.g. converting the int 0x00000008 to the short 0x0008, or the long 0x0000000000000008).

    Recall that values can have multiple types. If your situation is slightly different, and you only want to select a different one of the value’s types, casting is the tool for the job. Casting simply indicates that you wish to operate on a particular type that a value includes.

    The difference at the code level varies from C# to IL. In C#, both casting and coercion look fairly similar:

    static void ChangeTypes(int number, System.IO.Stream stream)
    {
        long longNumber = number;
        short shortNumber = (short)number;
    
        IDisposable disposableStream = stream;
        System.IO.FileStream fileStream = (System.IO.FileStream)stream;
    }
    

    At the IL level they are quite different:

    ldarg.0
     conv.i8
     stloc.0
    
    ldarg.0
     conv.i2
     stloc.1
    
    
    ldarg.1
     stloc.2
    
    ldarg.1
     castclass [mscorlib]System.IO.FileStream
     stloc.3
    

    As for the logical level, there are some important differences. What’s most important to remember is that coercion creates a new value, while casting does not. The identity of the original value and the value after casting are the same, while the identity of a coerced value differs from the original value; coersion creates a new, distinct instance, while casting does not. A corollary is that the result of casting and the original will always be equivalent (both in identity and equality), but a coerced value may or may not be equal to the original, and never shares the original identity.

    It’s easy to see the implications of coercion in the examples above, as the numeric types are always copied by value. Things get a bit trickier when you’re working with reference types.

    class Name : Tuple<string, string>
    {
        public Name(string first, string last)
            : base(first, last)
        {
        }
    
        public static implicit operator string[](Name name)
        {
            return new string[] { name.Item1, name.Item2 };
        }
    }
    

    In the example below, one conversion is a cast, while the other is a coercion.

    Tuple<string, string> tuple = name;
    string[] strings = name;
    

    After these conversions, tuple and name are equal, but strings is not equal to either of them. You could make the situation slightly better (or slightly more confusing) by implementing Equals() and operator ==() on the Name class to compare a Name and a string[]. These operators would “fix” the comparison issue, but you would still have two separate instances; any modification to strings would not be reflected in name or tuple, while changes to either one of name or tuple would be reflected in name and tuple, but not in strings.

    Although the example above was meant to illustrate some differences between casting and coercion, it also serves as a great example of why you should be extremely cautious about using conversion operators with reference types in C#.

    0 讨论(0)
  • 2020-12-02 07:03

    According to Wikipedia,

    In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another.

    The difference between type casting and type coercion is as follows:

               TYPE CASTING           |                   TYPE COERCION
                                      |
    1. Explicit i.e., done by user    | 1. Implicit i.e., done by the compiler
                                      |
    2. Types:                         | 2. Type:
        Static (done at compile time) |     Widening (conversion to higher data 
                                      |     type)
        Dynamic (done at run time)    |     Narrowing (conversion to lower data 
                                      |     type)
                                      |
    3. Casting never changes the      | 3. Coercion can result in representation 
       the actual type of object      |    as well as type change.
       nor representation.            |
    

    Note: Casting is not conversion. It is just the process by which we treat an object type as another type. Therefore, the actual type of object, as well as the representation, is not changed during casting.

    I agree with @PedroC88's words:

    On the other hand, coercing implies the creation of a new object in memory of the new type and then the original type would be copied over to the new one, leaving both objects in memory (until the Garbage Collectors takes either away, or both).

    0 讨论(0)
  • 2020-12-02 07:05

    Usages vary, as you note.

    My personal usages are:

    • A "cast" is the usage of a cast operator. A cast operator instructs the compiler that either (1) this expression is not known to be of the given type, but I promise you that the value will be of that type at runtime; the compiler is to treat the expression as being of the given type, and the runtime will produce an error if it is not, or (2) the expression is of a different type entirely, but there is a well-known way to associate instances of the expression's type with instances of the cast-to type. The compiler is instructed to generate code that performs the conversion. The attentive reader will note that these are opposites, which I think is a neat trick.

    • A "conversion" is an operation by which a value of one type is treated as a value of another type -- usually a different type, though an "identity conversion" is still a conversion, technically speaking. The conversion may be "representation changing", like int to double, or it might be "representation preserving" like string to object. Conversions may be "implicit", which do not require a cast, or "explicit", which do require a cast.

    • A "coercion" is a representation-changing implicit conversion.

    0 讨论(0)
  • 2020-12-02 07:07

    From the CLI standard:

    I.8.3.2 Coercion

    Sometimes it is desirable to take a value of a type that is not assignable-to a location, and convert the value to a type that is assignable-to the type of the location. This is accomplished through coercion of the value. Coercion takes a value of a particular type and a desired type and attempts to create a value of the desired type that has equivalent meaning to the original value. Coercion can result in representation change as well as type change; hence coercion does not necessarily preserve object identity.

    There are two kinds of coercion: widening, which never loses information, and narrowing, in which information might be lost. An example of a widening coercion would be coercing a value that is a 32-bit signed integer to a value that is a 64-bit signed integer. An example of a narrowing coercion is the reverse: coercing a 64-bit signed integer to a 32-bit signed integer. Programming languages often implement widening coercions as implicit conversions, whereas narrowing coercions usually require an explicit conversion.

    Some coercion is built directly into the VES operations on the built-in types (see §I.12.1). All other coercion shall be explicitly requested. For the built-in types, the CTS provides operations to perform widening coercions with no runtime checks and narrowing coercions with runtime checks or truncation, according to the operation semantics.

    I.8.3.3 Casting

    Since a value can be of more than one type, a use of the value needs to clearly identify which of its types is being used. Since values are read from locations that are typed, the type of the value which is used is the type of the location from which the value was read. If a different type is to be used, the value is cast to one of its other types. Casting is usually a compile time operation, but if the compiler cannot statically know that the value is of the target type, a runtime cast check is done. Unlike coercion, a cast never changes the actual type of an object nor does it change the representation. Casting preserves the identity of objects.

    For example, a runtime check might be needed when casting a value read from a location that is typed as holding a value of a particular interface. Since an interface is an incomplete description of the value, casting that value to be of a different interface type will usually result in a runtime cast check.

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