0
0
C Sharp (C#)programming~20 mins

Type conversion and casting in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Type Conversion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of implicit and explicit conversions
What is the output of the following C# code?
C Sharp (C#)
int a = 100;
long b = a;
int c = (int)b;
Console.WriteLine(c);
A100
B0
CCompilation error
DOverflowException at runtime
Attempts:
2 left
💡 Hint
Implicit conversion from int to long is safe; explicit cast back to int is valid here.
Predict Output
intermediate
2:00remaining
Result of casting double to int
What is the output of this C# code snippet?
C Sharp (C#)
double d = 9.99;
int i = (int)d;
Console.WriteLine(i);
A10
B9
C9.99
DCompilation error
Attempts:
2 left
💡 Hint
Casting from double to int truncates the decimal part.
Predict Output
advanced
2:00remaining
Behavior of unchecked overflow in casting
What will be printed by this C# code?
C Sharp (C#)
byte b = 255;
int i = b + 1;
byte c = (byte)i;
Console.WriteLine(c);
AOverflowException
B256
C255
D0
Attempts:
2 left
💡 Hint
Casting int to byte truncates higher bits without exception in unchecked context.
Predict Output
advanced
2:00remaining
Casting reference types and invalid cast exception
What happens when this C# code runs?
C Sharp (C#)
object obj = "hello";
int num = (int)obj;
Console.WriteLine(num);
AInvalidCastException at runtime
B0
Chello
DCompilation error
Attempts:
2 left
💡 Hint
Casting object holding a string to int is invalid.
Predict Output
expert
3:00remaining
Output of custom conversion operator
Given the following code, what is the output?
C Sharp (C#)
class Temperature {
    public double Celsius { get; set; }
    public static explicit operator int(Temperature t) {
        return (int)(t.Celsius * 9 / 5 + 32);
    }
}

Temperature temp = new Temperature { Celsius = 25 };
int fahrenheit = (int)temp;
Console.WriteLine(fahrenheit);
ACompilation error due to missing implicit operator
B25
C77
DRuntime error
Attempts:
2 left
💡 Hint
The explicit operator converts Celsius to Fahrenheit as int.