Alex Rivera | Logout

What is the difference between casting and coercing?

Asked 2012-01-13T21:55:31.123
102

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.

Is there perhaps a clear and simple way of explaining the difference that you guys know of?

Type conversion (also sometimes known as type cast)

To use a value of one type in a context that expects another.

Nonconverting type cast (sometimes known as type pun)

A change that does not alter the underlying bits.

Coercion

Process by which a compiler automatically converts a value of one type into a value of another type when that second type is required by the surrounding context.

Edit
Report

1 Answer

13

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 answered 2012-01-13T21:57:25.353

Your Answer