C# - Type Casting


Type casting is a way to convert a value from one data type to another in C#. There are two types of type casting in C#.

  1. Implicit Casting
  2. Explicit Casting

1. Implicit Casting

Implicit type casting is done automatically by the compiler when there is no possibility of losing data in the conversion. It works as converting a smaller type to a larger type size.

C# Type Casting

Example

int myInt = 12;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt); // Outputs 12
Console.WriteLine(myDouble); // Outputs 12

2. Explicit Casting

Explicit type casting is done by the programmer when there is a possibility of losing data in the conversion. It works as converting a larger type to a smaller type size.

C# Type Casting

Example

double myDouble = 12.68;
int myInt = (int) myDouble; // Programmer casting: double to int

Console.WriteLine(myDouble); // Outputs 12.68
Console.WriteLine(myInt); // Outputs 12

Explicit Type Casting with Lossing Data

when we explicitly cast a value to a smaller data type, there is a possibility of losing data or precision. In this case, the compiler truncates the value to fit into the smaller data type, which can result in a loss of information.

Example

float num1 = 10.5f;
int num2 = (int)num1; // num1 is explicitly cast to intOutput- 10

Prev Next