C# Type Casting - Complete Guide
Introduction to Type Casting
Type casting in C# is the process of converting a value from one data type to another. This is necessary when you want to perform operations between different types or when you need to store a value of one type in a variable of another type.
C# provides two types of casting: implicit casting (automatically by the compiler) and explicit casting (manually by the programmer). Understanding when and how to use each type is crucial for writing correct and efficient code.
Implicit Casting
Implicit casting happens automatically when converting from a smaller type to a larger type, and there's no risk of data loss:
using System;
namespace ImplicitCastingExample
{
class Program
{
static void Main(string[] args)
{
// Integer implicit casting (smaller to larger)
byte byteValue = 100;
short shortValue = byteValue; // byte → short
int intValue = shortValue; // short → int
long longValue = intValue; // int → long
Console.WriteLine($"Byte: {byteValue}");
Console.WriteLine($"Short: {shortValue}");
Console.WriteLine($"Int: {intValue}");
Console.WriteLine($"Long: {longValue}");
// Floating-point implicit casting
float floatValue = 3.14f;
double doubleValue = floatValue; // float → double
Console.WriteLine($"Float: {floatValue}");
Console.WriteLine($"Double: {doubleValue}");
// Integer to floating-point implicit casting
int integerNumber = 100;
float floatNumber = integerNumber; // int → float
double doubleNumber = integerNumber; // int → double
Console.WriteLine($"Integer: {integerNumber}");
Console.WriteLine($"Float: {floatNumber}");
Console.WriteLine($"Double: {doubleNumber}");
// Char to integer implicit casting
char charValue = 'A';
int charToInt = charValue; // char → int (gets ASCII value)
Console.WriteLine($"Char: {charValue}");
Console.WriteLine($"Char to Int: {charToInt}");
// Note: Some implicit conversions that might be unexpected
int smallInt = 300;
long bigLong = smallInt; // int → long (implicit)
float smallFloat = bigLong; // long → float (implicit, possible precision loss but allowed)
Console.WriteLine($"Int: {smallInt} → Long: {bigLong} → Float: {smallFloat}");
}
}
}
Byte: 100 Short: 100 Int: 100 Long: 100 Float: 3.14 Double: 3.140000104904175 Integer: 100 Float: 100 Double: 100 Char: A Char to Int: 65 Int: 300 → Long: 300 → Float: 300
Explicit Casting
Explicit casting is required when converting from a larger type to a smaller type, where data loss might occur:
using System;
namespace ExplicitCastingExample
{
class Program
{
static void Main(string[] args)
{
// Larger to smaller type casting (requires explicit cast)
double doubleValue = 9.78;
int intValue = (int)doubleValue; // double → int (explicit)
Console.WriteLine($"Double: {doubleValue}");
Console.WriteLine($"Int: {intValue}"); // Loses decimal part
// Integer type explicit casting
long longValue = 1000;
int intFromLong = (int)longValue; // long → int
short shortFromInt = (short)intValue; // int → short
byte byteFromShort = (byte)shortFromInt; // short → byte
Console.WriteLine($"Long: {longValue} → Int: {intFromLong} → Short: {shortFromInt} → Byte: {byteFromShort}");
// Potential data loss with explicit casting
double largeDouble = 123456789.99;
float floatValue = (float)largeDouble; // double → float
int largeInt = (int)largeDouble; // double → int
Console.WriteLine($"Large Double: {largeDouble}");
Console.WriteLine($"To Float: {floatValue}"); // May lose precision
Console.WriteLine($"To Int: {largeInt}"); // Loses decimal part
// Overflow example
int largeNumber = 500;
byte smallByte = (byte)largeNumber; // int → byte
Console.WriteLine($"Large Number: {largeNumber}");
Console.WriteLine($"To Byte: {smallByte}"); // 500 > 255, but gets 244 due to overflow
// Using Convert class for safer conversions
try
{
string numberString = "123";
int convertedInt = Convert.ToInt32(numberString);
Console.WriteLine($"Converted String to Int: {convertedInt}");
// This will throw an exception
string invalidString = "Hello";
int invalidConvert = Convert.ToInt32(invalidString);
}
catch (FormatException ex)
{
Console.WriteLine($"Conversion error: {ex.Message}");
}
}
}
}
Double: 9.78 Int: 9 Long: 1000 → Int: 1000 → Short: 1000 → Byte: 232 Large Double: 123456789.99 To Float: 1.234568E+08 To Int: 123456789 Large Number: 500 To Byte: 244 Converted String to Int: 123 Conversion error: Input string was not in a correct format.
Type Conversion Methods
C# provides several methods for type conversion beyond simple casting:
using System;
namespace ConversionMethodsExample
{
class Program
{
static void Main(string[] args)
{
// Parse method (string to other types)
string intString = "123";
string doubleString = "45.67";
string boolString = "true";
int parsedInt = int.Parse(intString);
double parsedDouble = double.Parse(doubleString);
bool parsedBool = bool.Parse(boolString);
Console.WriteLine($"Parsed Int: {parsedInt}");
Console.WriteLine($"Parsed Double: {parsedDouble}");
Console.WriteLine($"Parsed Bool: {parsedBool}");
// TryParse method (safer alternative)
string maybeNumber = "123abc";
int result;
bool success = int.TryParse(maybeNumber, out result);
Console.WriteLine($"TryParse success: {success}, Result: {result}");
// Convert class methods
decimal decimalValue = 123.45m;
int convertedInt = Convert.ToInt32(decimalValue);
string convertedString = Convert.ToString(decimalValue);
Console.WriteLine($"Decimal: {decimalValue} → Int: {convertedInt} → String: {convertedString}");
// ToString method (any type to string)
int number = 42;
DateTime now = DateTime.Now;
object obj = new { Name = "John", Age = 25 };
string numberString = number.ToString();
string dateString = now.ToString("yyyy-MM-dd");
string objString = obj.ToString();
Console.WriteLine($"Number as string: {numberString}");
Console.WriteLine($"Date as string: {dateString}");
Console.WriteLine($"Object as string: {objString}");
// Boxing and unboxing (value types to object and back)
int valueType = 100;
object boxed = valueType; // Boxing (implicit)
int unboxed = (int)boxed; // Unboxing (explicit)
Console.WriteLine($"Original: {valueType}, Boxed: {boxed}, Unboxed: {unboxed}");
}
}
}
Parsed Int: 123 Parsed Double: 45.67 Parsed Bool: True TryParse success: False, Result: 0 Decimal: 123.45 → Int: 123 → String: 123.45 Number as string: 42 Date as string: 2023-10-15 Object as string: { Name = John, Age = 25 } Original: 100, Boxed: 100, Unboxed: 100