C# Type Casting

C# Type Casting: Converting Data Types

Type casting is the process of converting a value from one data type to another data type. In C#, there are two types of casting: Implicit Casting (done automatically) and Explicit Casting (done manually).


1. Implicit Casting (Automatically)

Implicit casting happens automatically when you are converting a smaller type to a larger type size. Because the destination type is larger, there is no risk of losing data.

Order of Implicit Casting: char -> int -> long -> float -> double

Implicit Casting Example

using System;

class Program { static void Main() { int myInt = 9; // Automatic casting: int to double double myDouble = myInt;
Console.WriteLine(myInt); // Outputs 9 Console.WriteLine(myDouble); // Outputs 9 } }


2. Explicit Casting (Manually)

Explicit casting is required when you are converting a larger type to a smaller type. You must do this manually by placing the type in parentheses in front of the value, acknowledging that you might lose precision (data loss).

Order of Explicit Casting: double -> float -> long -> int -> char

Explicit Casting Example

using System;

class Program { static void Main() { double myDouble = 9.78; // Manual casting: double to int (the .78 is lost!) int myInt = (int) myDouble;
Console.WriteLine(myDouble); // Outputs 9.78 Console.WriteLine(myInt); // Outputs 9 } }

Notice how converting 9.78 to an int simply chops off the decimal portion. It does not round the number up to 10.


Exercise

?

When converting an int to a double, which type of casting occurs?