Type Casting In C#

Type Casting In C#

In this article, you will learn type casting in c#. There are two types of casting:

 

1. Implicit Casting (automatically) - converting a smaller type to a larger type size.

 

int a = 10;
double b = a;       // Automatic casting: int to double

Console.WriteLine(a);      // Output 10
Console.WriteLine(b);   // Output 10

 

2. Explicit Casting (manually) - converting a larger type to a smaller size type.

 

double a= 10.50;
int b= (int) a;    // Manual casting: double to int

Console.WriteLine(a);   // Outputs 10.50
Console.WriteLine(b);      // Outputs 10

 

Some Ex. of Conversion Methods

 

int a= 200;
double b= 505.20;
bool c= true;

Console.WriteLine(Convert.ToString(a));    // convert int to string
Console.WriteLine(Convert.ToDouble(a));    // convert int to double
Console.WriteLine(Convert.ToInt32(b));  // convert double to int
Console.WriteLine(Convert.ToString(c));   // convert bool to string

For example

 

 

2021-10-03