Type Casting

Type casting is the process of converting one data type into another data type. Type casting can be explicit or implicit. The programmer does explicit type casting while the compiler does implicit type casting.

1. Implicit Casting

  • This type of casting occurs when you convert a smaller type to a larger type.
  • The order of implicit casting is charintlongfloatdouble.
  • For example, consider the following code snippet:
int myInt = 10;
double myDouble = myInt; // Automatic casting:- int to double
Console.WriteLine(myInt); // Outputs 10
Console.WriteLine(myDouble); // Outputs 10

2. Explicit Casting

  • Explicit casting is done manually by placing the type in parentheses before the value.
  • It involves converting a larger type to a smaller size type, For instance:
double myDouble = 123.99;
int myInt = (int)myDouble; // Manual casting:- double to int
Console.WriteLine(myDouble); // Outputs- 123.99
Console.WriteLine(myInt); // Outputs- 123

C# Type Conversion Methods

You can also explicitly convert data types using built-in methods like Convert.ToBooleanConvert.ToDoubleConvert.ToStringConvert.ToInt32 (for int), and Convert.ToInt64 (for long), Example:

bool myBool = false;
int myInt = 12;
double myDouble = 7.75;
Console.WriteLine(Convert.ToInt32(myDouble)); // Convert double to int
Console.WriteLine(Convert.ToString(myBool)); // Convert bool to string
Console.WriteLine(Convert.ToString(myInt)); // Convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // Convert int to double
Post a comment

Leave a Comment

Scroll to Top