Type Conversion and Manipulation

Changing and working with data types in C#

Posted by Rodrigo Castro on October 19, 2024

Often, you’ll need to change one type into another. C# gives you ways to do this safely.

🔄 Implicit and Explicit Conversion

Implicit: C# does it automatically (no risk of data loss):

1
2
int a = 10;
double b = a; // int to double is safe

Explicit: You must tell C# (possible data loss!):

1
2
double x = 3.7;
int y = (int)x; // Explicit cast: 3 (decimal part lost)

🎛️ Useful Conversion Methods

  • ToString() — Any type to string:
    1
    2
    
      int score = 95;
      string s = score.ToString();
    
  • int.Parse() / double.Parse() — String to number:
    1
    2
    
      string input = "42";
      int n = int.Parse(input); // 42
    
  • Convert.ToInt32(), Convert.ToDouble(), etc. — Flexible and safe:
    1
    2
    
      string value = "123";
      int number = Convert.ToInt32(value);
    

⚠️ Safe Parsing

If you’re not sure if a string is a valid number, use TryParse:

1
2
string input = "abc";
bool ok = int.TryParse(input, out int num); // ok is false, num is 0

💡 Try It!

Prompt a user for a number and double it:

1
2
3
4
5
6
7
Console.Write("Enter a number: ");
string? s = Console.ReadLine();
if (int.TryParse(s, out int n)) {
    Console.WriteLine($"Twice your number is {n * 2}");
} else {
    Console.WriteLine("That’s not a valid number!");
}

Boxing and Unboxing in C#

C# distinguishes between value types (like int, double, struct) and reference types (like object, string, arrays). Sometimes, you may need to convert a value type to a reference type or back (this is where boxing and unboxing come into play).

What is Boxing?

Boxing is the process of converting a value type to a reference type by wrapping the value inside an object. This allows value types to be treated as objects.

1
2
int number = 42;
object boxed = number; // Boxing: int to object
  • The value of number is copied into a new object on the heap.
  • Changes to the boxed value do not affect the original variable.

What is Unboxing?

Unboxing is the reverse process, extracting the value type from the object.

1
2
object boxed = 42;
int number = (int)boxed; // Unboxing: object back to int
  • You must explicitly cast the object back to the correct value type.
  • If the object does not actually contain the correct value type, an InvalidCastException will occur.

Why Does Boxing/Unboxing Matter?

  • Performance: Boxing and unboxing involve memory allocation and can impact performance, especially in tight loops or with collections.
  • Collections: Prior to generics, collections like ArrayList stored elements as object, requiring boxing for value types. Generics (like List<int>) avoid this by storing items as their true type.

Example

1
2
3
int a = 10;
object o = a;            // Boxing
int b = (int)o;          // Unboxing

Tip: Use generics to minimize boxing/unboxing and improve performance.

Next: Discover control flow structures in C#.