C# .Net – Type Casting

Type casting:

  • Conversion of data from one data type to another data type.
  • Type casting classified into
    • Implicit cast: Auto conversion of data from one type to another type.
    • Explicit cast: Manual conversion of data from one type to another type.

Convert Character to Integer: this conversion happens implicitly when we assign character to integer type.

using System;				
public class Program
{
	public static void Main()
	{
		char ch = 'A' ;
		int x = ch ; 
		Console.WriteLine("x value : " + x);
	}
}

Convert Integer to Character: this conversion must be done manually

using System;				
public class Program
{
	public static void Main()
	{
		int x = 97 ;
		char ch = (char)x ;
		Console.WriteLine("ch value : "+ch);
	}
}

Convert Upper case to Lower case Character:

Lower Case to Upper CaseUpper Case to Lower Case
A(65) + 32 -> a(97)
B(66) + 32 -> b(98)


Z(90) + 32 -> z(122)
a(97) – 32 -> A(65)
b(98) – 32 -> B(66)


z(122) – 32 -> Z(90)

Conversion Code:

using System;				
public class Program
{
	public static void Main()
	{
		char up = 'A';
		char lw = (char)(up+32);
		Console.WriteLine("Result : " + lw);
	}
}

Convert Digit to Number: We can convert character type digit into number as follows

Digit to Number:
‘0’ – 48 -> 48-48 -> 0
‘1’ – 48 -> 49-48 -> 1
..
..
‘9’ – 48 -> 57-9 -> 9

Conversion Code:

using System;				
public class Program
{
	public static void Main()
	{
		char d = '5';
		int n = d-48;
		Console.WriteLine("Result : " + n);
	}
}
Scroll to Top