Advertisement
Beginner C# Lesson 3 of 5

Lesson 3: Type Conversion & Casting in C#

In real programs, data rarely stays in one type. You might read a number as a string from user input, need to multiply an integer by a decimal, or convert Celsius to Fahrenheit. C# provides several ways to convert between types — and knowing which to use is critical to writing safe, correct code.

Advertisement

1. Implicit Conversion (Automatic)

C# automatically converts a smaller type to a larger type when there is no risk of data loss. This is called widening:

int    myInt    = 100;
long   myLong   = myInt;    // int → long   ✅ safe, no data loss
float  myFloat  = myInt;    // int → float  ✅ safe
double myDouble = myFloat;  // float → double ✅ safe

Console.WriteLine(myDouble);  // Output: 100
FromCan implicitly convert to
byteshort, int, long, float, double, decimal
intlong, float, double, decimal
floatdouble
charint, long, float, double, decimal

2. Explicit Conversion (Casting)

When converting a larger type to a smaller type (narrowing), you must explicitly cast — this tells the compiler "I know what I'm doing". Data loss is possible:

double myDouble = 9.78;

// Explicit cast using (type) syntax
int myInt = (int)myDouble;
Console.WriteLine(myInt);  // Output: 9  (decimal part is truncated, not rounded!)

long bigNumber = 3_000_000_000L;
int  smallInt  = (int)bigNumber;
Console.WriteLine(smallInt); // Output: -1294967296 (overflow — data corrupted!)

⚠️ Warning: Casting truncates (cuts off) the decimal — it does not round. And casting a value that exceeds the target type's range causes silent overflow. Always validate before casting.

3. The Convert Class

The Convert class (from System) provides safe, explicit conversions between common types. Unlike casting, it rounds instead of truncating and throws clear exceptions on bad input:

double price = 19.99;
int rounded = Convert.ToInt32(price); // rounds to 20, not truncates!

string input = "42";
int    num   = Convert.ToInt32(input);   // "42" → 42
double dbl   = Convert.ToDouble(input);  // "42" → 42.0
bool   flag  = Convert.ToBoolean("true"); // "true" → true
string str   = Convert.ToString(100);    // 100 → "100"

4. Parse and TryParse

When converting strings to numbers, Parse and TryParse are the most common tools:

// Parse — throws FormatException if input is invalid
int age = int.Parse("25");        // ✅ works
int bad = int.Parse("hello");     // ❌ throws exception!

// TryParse — safe, returns bool, never throws
bool success = int.TryParse("25", out int result);
if (success)
    Console.WriteLine($"Parsed: {result}");  // Parsed: 25

// TryParse with invalid input
bool ok = int.TryParse("abc", out int val);
Console.WriteLine(ok);   // False
Console.WriteLine(val);  // 0 (default value)

💡 Best Practice: Always prefer TryParse over Parse when handling user input. It prevents unhandled exceptions from crashing your application.

5. ToString() — Every Type Has It

Every C# type inherits ToString() from object, making any value easy to convert to a string:

int num = 42;
double pi = 3.14;
bool flag = true;

Console.WriteLine(num.ToString());     // "42"
Console.WriteLine(pi.ToString("F1")); // "3.1" (1 decimal place)
Console.WriteLine(flag.ToString());   // "True"

// Format currency
decimal price = 19.99m;
Console.WriteLine(price.ToString("C")); // "$19.99" (locale-dependent)
Advertisement

🧠 Quick Check — Lesson 3

A user types their age in a text box. Which is the safest way to convert it to an int?

Lesson Summary

Implicit conversion happens automatically when converting to a larger type with no data loss.

Explicit casting uses (type) syntax — may truncate decimals or overflow.

Convert class methods like Convert.ToInt32() round instead of truncate and work with more types.

TryParse is the safest way to convert user-entered strings — it never throws an exception.

ToString() converts any value to a string, and accepts format strings like "C", "F2".

Up Next

Lesson 4: Arithmetic & Assignment Operators

Next Lesson →