Type conversion and casting let you change a value from one type to another. This helps when you want to use data in different ways.
Type conversion and casting in C Sharp (C#)
Type targetVariable = (Type)sourceVariable; // casting Type targetVariable = Convert.ToType(sourceVariable); // conversion
Casting uses parentheses and works when types are compatible.
Conversion methods are safer and can handle more cases, like strings to numbers.
int a = 10; double b = (double)a; // cast int to double
double x = 9.78; int y = (int)x; // cast double to int (fraction lost)
string s = "123"; int n = Convert.ToInt32(s); // convert string to int
object obj = "hello"; string str = (string)obj; // cast object to string
This program shows casting between int and double, converting a string to int, and casting an object to string. It prints the results to the console.
using System; class Program { static void Main() { int wholeNumber = 42; double decimalNumber = (double)wholeNumber; // cast int to double Console.WriteLine($"Double value: {decimalNumber}"); double pi = 3.14159; int truncatedPi = (int)pi; // cast double to int Console.WriteLine($"Truncated int value: {truncatedPi}"); string numberString = "100"; int number = Convert.ToInt32(numberString); // convert string to int Console.WriteLine($"Converted number: {number}"); object obj = "Hello World"; string message = (string)obj; // cast object to string Console.WriteLine($"Message: {message}"); } }
Casting can cause data loss if the target type cannot hold the original value fully.
Use conversion methods like Convert.ToInt32 when changing from strings to numbers to avoid errors.
Invalid casts cause runtime errors, so be sure the types are compatible before casting.
Type conversion changes data from one type to another.
Casting uses parentheses and works when types are compatible.
Conversion methods are safer for changing strings to numbers and other types.