C# Type Casting

In C#, data types play a crucial role in defining how data is stored and manipulated.

But what happens when you need to convert one data type into another?

This is where Type Casting in C# comes into the picture.

Type casting allows you to convert a variable from one data type to another, making your code more flexible and efficient.


What is Type Casting in C#?

Type casting is the process of converting a variable from one data type to another.

It is commonly used when working with different data types in calculations, user input, database values, and APIs.

double price = 99.99;
int roundedPrice = (int)price;

Here, we converted a double value into an int.


Why Type Casting is Important

Let’s understand this with a real-world scenario.

Imagine you are building an e-commerce application:

  • User enters quantity as string → needs conversion to int
  • Price calculations involve decimals → convert to int for display
  • Database values may come in different formats

Without type casting, handling such scenarios would be difficult.

Type casting helps in:

  • Performing calculations between different data types
  • Saving memory by converting to smaller data types
  • Ensuring type safety
  • Working with external data sources

Types of Type Casting in C#

C# supports two main types of type casting:

  • Implicit Casting (Automatic)
  • Explicit Casting (Manual)

1. Implicit Type Casting

Implicit casting is done automatically by the compiler when there is no risk of data loss.

It usually happens when converting from a smaller type to a larger type.

int → double

int num = 10;
double result = num;

The integer value is automatically converted to double.

char → int

char letter = 'A';
int ascii = letter;

Console.WriteLine(ascii); // 65

Characters are internally stored as numeric values.

int → long

int smallValue = 100;
long bigValue = smallValue;

No data loss occurs, so conversion is automatic.


Why Implicit Casting is Safe

  • No data loss
  • No exception risk
  • Handled by compiler automatically

2. Explicit Type Casting

Explicit casting is required when converting from a larger type to a smaller type.

This may result in data loss, so it must be done manually.

double → int

double price = 99.99;
int rounded = (int)price;

Console.WriteLine(rounded); // 99

The decimal part is truncated.

long → int

long large = 50000;
int small = (int)large;

If the value exceeds range, overflow may occur.

int → byte

int number = 300;
byte b = (byte)number;

Console.WriteLine(b); // 44 (overflow)

This demonstrates how incorrect casting can lead to unexpected results.


Type Casting with Strings

Strings are commonly used when working with user input.

string → int

string input = "100";
int value = int.Parse(input);

Using Convert

string input = "50";
int value = Convert.ToInt32(input);

Using TryParse (Safe Method)

string input = "abc";
int result;

if (int.TryParse(input, out result))
{
    Console.WriteLine(result);
}
else
{
    Console.WriteLine("Invalid input");
}

This avoids runtime exceptions.


Boxing and Unboxing

C# allows conversion between value types and reference types.

Boxing

int num = 10;
object obj = num;

Unboxing

object obj = 20;
int num = (int)obj;

Boxing stores value in heap, unboxing retrieves it.


Memory and Performance Impact

Type casting can help optimize memory usage.

  • Using smaller data types saves memory
  • Avoid unnecessary boxing (performance cost)
  • Choose correct data type for efficiency

Common Mistakes Developers Make

  • Ignoring overflow issues
  • Using Parse without validation
  • Unnecessary boxing/unboxing
  • Wrong data type conversions

Best Practices

  • Prefer implicit casting when safe
  • Use TryParse for user input
  • Avoid unnecessary conversions
  • Always validate data

Summary

Type casting in C# is essential for converting data between different types.

It enables flexibility, improves memory usage, and helps in handling real-world scenarios like user input, APIs, and databases.

Understanding implicit and explicit casting, along with safe conversion methods, is crucial for writing robust applications.

In the next chapter, we will explore Boxing and Unboxing in deeper detail.