C# ยท Chapter 9 of 46

C# Type Casting

Type casting means converting a value from one data type to another. C# supports implicit casting (automatic, safe conversions) and explicit casting (manual conversions that may lose data).

Implicit casting happens automatically when converting a smaller type to a larger one, like int to double. Explicit casting requires a cast operator and is needed when converting a larger type to a smaller one, like double to int.

Syntax
(type)value;
Convert.ToInt32(value);
int.Parse(stringValue);

Implicit casting

Implicit casting happens automatically when there's no risk of data loss, such as converting an int to a double. The compiler performs this conversion for you.

Explicit casting and Convert/Parse

Explicit casting uses parentheses, like `(int)myDouble`, and may lose data. The Convert class and Parse methods (like int.Parse) are used to convert strings to numbers and vice versa.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    int myInt = 9;
    double myDouble = myInt;
    Console.WriteLine(myDouble);
  }
}
Output
9

int is implicitly converted to double since no data is lost.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    double myDouble = 9.78;
    int myInt = (int)myDouble;
    Console.WriteLine(myInt);
  }
}
Output
9

Explicit casting truncates the decimal part when converting double to int.

Key points

  • Implicit casting is automatic and safe (small type to large type).
  • Explicit casting requires a cast operator and can lose data.
  • Convert.ToInt32() and int.Parse() convert strings to numbers.
  • ToString() converts a value into its string representation.
๐Ÿ’ก Note: Casting a double to an int truncates (cuts off) the decimal part rather than rounding it.

๐Ÿ“ Quick Quiz

1. Which cast happens automatically without data loss?

2. What does (int)9.78 evaluate to?

3. Which method converts a string to an integer?