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.
Practice
Solution
Step 1: Understand casting in C#
Casting uses parentheses and works only when types are compatible, like int to double or object to string.Step 2: Understand conversion methods
Conversion methods like Convert.ToInt32 or int.Parse are safer and can handle strings and other types more flexibly.Final Answer:
Casting requires compatible types and uses parentheses, conversion can be safer and more flexible. -> Option CQuick Check:
Casting vs Conversion = Casting requires compatible types and uses parentheses, conversion can be safer and more flexible. [OK]
- Thinking casting works with all types automatically
- Confusing conversion methods with casting syntax
- Assuming casting changes data format like conversion
d to an int in C#?Solution
Step 1: Recall casting syntax in C#
Casting uses parentheses with the target type before the variable, like (int)d.Step 2: Check each option
int i = (int)d; uses correct casting syntax. int i = int(d); is invalid syntax. int i = Convert.ToInt(d); uses wrong method name (should be Convert.ToInt32). int i = d as int; uses 'as' which works only with reference types.Final Answer:
int i = (int)d; -> Option AQuick Check:
Correct cast syntax = int i = (int)d; [OK]
- Using 'as' keyword for value types
- Calling non-existent Convert.ToInt method
- Using function-like syntax for casting
double d = 9.7; int i = (int)d; Console.WriteLine(i);
Solution
Step 1: Understand casting from double to int
Casting double to int truncates the decimal part, it does not round.Step 2: Apply casting to value 9.7
Truncating 9.7 results in 9, so i = 9.Final Answer:
9 -> Option DQuick Check:
Double to int cast truncates decimals = 9 [OK]
- Assuming casting rounds the number
- Expecting a compilation error
- Confusing output with original double value
string s = "123abc"; int num = Convert.ToInt32(s); Console.WriteLine(num);
Solution
Step 1: Understand Convert.ToInt32 behavior
Convert.ToInt32 tries to convert the whole string to an integer and throws an exception if format is invalid.Step 2: Analyze string "123abc"
String contains non-digit characters, so conversion fails and throws FormatException at runtime.Final Answer:
FormatException at runtime due to invalid string format -> Option AQuick Check:
Invalid string format causes FormatException [OK]
- Assuming partial conversion succeeds
- Expecting zero instead of exception
- Thinking Convert.ToInt32 is compile-time error
obj that holds an integer value. Which code safely converts obj to an int without risking an exception if obj is not an int?Solution
Step 1: Understand casting and conversion risks
Direct cast (int)obj throws exception if obj is not int. Convert.ToInt32 may throw exceptions too. 'as' cannot be used with value types like int.Step 2: Analyze safe pattern
Using pattern matching with 'is' checks type safely and assigns value or default 0 if not int, avoiding exceptions.Final Answer:
int i = obj is int val ? val : 0; -> Option BQuick Check:
Pattern matching safely converts or defaults = int i = obj is int val ? val : 0; [OK]
- Using 'as' with value types causing compile errors
- Casting without checking type causing exceptions
- Assuming Convert.ToInt32 always safe
Ready to prove it?
Pass the test and this pattern moves unknown
