Lesson Sunday

Type casting is the process of transferring a piece of data between types. Let's look at an example using standard data types. Let's try to multiply a decimal-holding number, which is called a double, and store it in an integer.

    double myNumber = 12.5;
    int multipliedNumber = myNumber * 2;
    Console.WriteLine(multipliedNumber);

When we multiply 12.5 * 2 we get 25, which should be a valid integer, but when we compile this code we get an error:

Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)

Even though the result of the operation is a whole number, C# throws an error because double is not an int. This is our strongly-typed paradigm at work.

Casting


The error hints at a solution: An explicit conversion exists...(are you missing a cast?) What is an explicit conversion? Let's look at how we can use one to compile this code.

    double myNumber = 12.5;
    int multipliedNumber = (int)myNumber * 2;
    Console.WriteLine(multipliedNumber);

The syntax (int)myNumber is an example of a cast. Casting, just like in the movies, is the act of turning one thing into another. Just as Audrey Hepburn was cast as Holly Golightly, we can cast double as an int.

Explicit casting

This type of cast is called an explicit cast. We're openly telling the compiler to convert myNumber into an integer before proceeding. Since myNumber and 2 are both valid integers, their evaluation can be stored in the multipliedNumber variable.

If we evaluate this expression, we get:

24

Unfortunately, that's the wrong answer. So why doesn't C# return 25?

Casting can be an imperfect process. When data types are different, casting can sometimes result in a loss in accuracy. In this case, the expression (int)myNumber converts 12.5 into an integer before performing the multiplication operation. To convert a double into an int, our cast drops the decimal.

This is called lossy conversion, as there is a loss of data or accuracy that occurs during the conversion.

We can mitigate this loss by waiting until the operation completes before performing the conversion:

    double myNumber = 12.5;
    int multipliedNumber = (int)(myNumber * 2); //CHANGE IS HERE
    Console.WriteLine(multipliedNumber);

We perform our mathematical operation before making the explicit conversion, which leads to the correct result:

25

Implicit casting

There is another cast going on here that we might not spot right away. In our expression myNumber * 2, the 2 is declared without a type. It's just a numeric value.

So what type is 2 exactly if we haven't declared it?

Let's change our example slightly:

    int myNumber = 12;
    double multipliedNumber = myNumber * 2;
    Console.WriteLine(multipliedNumber);

When we run this code, we get the correct value 24. How does a multiplied int become a double when a multiplied double cannot become an int?

When we convert 12.5 to an int, we lose information. It would make sense to think of a double as a data type that contains more information. This makes a double a larger data type than an int. When we convert from an int to a double, we don't lose any information because we're moving from a smaller data type to a larger one. This is called implicit casting. No special syntax is required and C# will do this automatically.

So what is 2 in the code above then?

It starts as an int. However, because it's a smaller data type than a double, C# implicitly casts it to a double so it can be evaluated.

Casting Between Classes

Classes from the same class hierarchy (sometimes referred to as type hierarchy) can be converted into one another. A hierarchy is just a group of classes that inherit from each other. Consider this non-technical example:

Animal > Mammal > Canine > Terrier > ScottishTerrier

Here we have a hierarchy of dogs. It begins with the general Animal class. A specific type of animal is a warm-blooded Mammal. Canine is an even more specific type of Mammal. It inherits all Mammal traits but also has properties and capabilities specific to canines.

Finally, ScottishTerrier inherits from Terrier which inherits from Canine. In this fictional example, we could cast an Animal to a ScottishTerrier:

Animal newPuppy = new Animal("Wilbur");
ScottishTerrier newPuppy = (ScottishTerrier) newPuppy;

But we couldn't cast a Book to a Canine since they do not belong in the same hierarchy of interrelated classes that inherit from one another.

All objects in C# inherit from System.Object. That means that we can cast to a System.Object and vice versa. We won't worry about this now but it will come up later in this course.

Guidelines


Here are some guidelines for explicit and implicit casting. In general, we should use type casting as little as possible. Regular use of type casting is a sign that the code is inefficient.

C# will perform implicit casting when:

  • Data types are compatible, such as when we are working with two ints;
  • When data of a smaller type is assigned to a bigger data type, such as when an int is cast as a double.

We should use explicit casting when:

  • We are working with incompatible data types where automatic conversion cannot be done. We explicitly state the data type to which the value should be converted. However, be careful: explicit casting can potentially result in loss of accuracy.

Terminology


Cast: Turning one data type into another.

Explicit cast: Explicitly telling the application to turn something from one data type into another.

Implicit casting: When we move from a smaller to a larger data type implicitly. Our application will handle this for us so we don't need to do it explicitly.

Lossy conversion: When there is a loss of data or accuracy during a conversion. This should be avoided.

Type casting is the process of transferring a piece of data between types.

Guidelines


Here are some guidelines for explicit and implicit casting.

C# will perform implicit casting when: * Data types are compatible, such as when we are working with two ints; * When data of a smaller type is assigned to a bigger data type, such as when an int is cast as a double.

We should use explicit casting when: * We are working with incompatible data types where automatic conversion cannot be done. We explicitly state the data type to which the value should be converted. However, be careful: explicit casting can potentially result in loss of accuracy.

Lesson 2 of 7
Last updated more than 3 months ago.