Sabari M Sabari M
Updated date Nov 15, 2020
In this blog, we will learn what is typecasting, types of casting, and a few examples.

Typecasting is converting one data type into another data type. It is also known as "type conversion".

Types of Casting in C#:

  • Implicit Conversion (Automatic)
  • Explicit Conversion (Manual)

Implicit Conversion:

 If the data types are compatible, then C# does automatic type conversion. It converts a smaller data type to a larger data type.

byte > int > long > float > double

int i = 60;    
long l = i;    // Automatic casting: int to long

Console.WriteLine("Integer value: "  + i); 
Console.WriteLine("Long value: "  + l); 

// Output
// Integer value: 60
// Long value: 60

Explicit Conversion:

If the data types are not compatible, then we need to convert explicitly which is called an explicit conversion.

double > float > long > int > byte

double d = 60.15;
int i = (int) d;    // Explicit casting: double to int

Console.WriteLine("Double value: " + d);
Console.WriteLine("Integer value: " + i);

// Output
// Double value: 60.15
// Integer value: 60

C# Type Conversion Methods (Built-in methods for Type Conversions):

  • Convert.ToBoolean
  • Convert.ToDouble
  • Convert.ToString
  • Convert.ToChar
  • Convert.ToByte
  • Convert.ToDecimal
  • Convert.ToInt16
  • Convert.ToInt32
  • Convert.ToInt64
  • Convert.ToUInt16
  • Convert.ToUInt32
  • Convert.ToUInt64

For example, 

int i = 32;
double d = 155.56;
string s = "24";

// Built-In Type Conversion                // Output  
Console.WriteLine(Convert.ToString(i));    // 32
Console.WriteLine(Convert.ToInt32(d));     // 156
Console.WriteLine(Convert.ToUInt32(s));    // 24
Console.WriteLine(Convert.ToDouble(i));    // 32

 

ABOUT THE AUTHOR

Sabari M
Sabari M

IT professional with 14+ years of experience in Microsoft Technologies with strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices, V...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!
×