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

Type conversion and casting in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the difference between implicit and explicit type conversion in C#?
Implicit conversion happens automatically when there is no risk of data loss, like converting an int to a double. Explicit conversion (casting) requires you to specify the type because it might lose data or cause errors, like converting a double to an int.
Click to reveal answer
beginner
How do you perform explicit casting from a double to an int in C#?
You use parentheses with the target type before the value, like this: int number = (int)3.14;. This cuts off the decimal part and keeps only the whole number.
Click to reveal answer
intermediate
What happens if you try to cast an object to an incompatible type using (Type) casting?
You get an InvalidCastException at runtime because the object cannot be converted to that type. You should check the type before casting or use safe casting methods.
Click to reveal answer
intermediate
What is the difference between as operator and regular casting in C#?
The as operator tries to cast an object to a type and returns null if it fails, instead of throwing an exception. Regular casting throws an exception if the cast is invalid.
Click to reveal answer
intermediate
Explain boxing and unboxing in C#.
Boxing is converting a value type (like int) to an object type, wrapping the value inside an object. Unboxing extracts the value type back from the object. Boxing and unboxing can affect performance if overused.
Click to reveal answer
Which of these conversions is implicit in C#?
Adouble to int
Bobject to string
Cint to double
Dstring to int
What does this code do? int x = (int)5.99;
AConverts 5.99 to 5 by dropping the decimal
BThrows an error
CRounds 5.99 to 6
DStores 5.99 as an int
What will happen if you cast an object to an incompatible type using (Type) casting?
AThrows InvalidCastException
BConverts silently
CReturns null
DReturns default value
Which operator returns null instead of throwing an exception when casting fails?
Acast operator (Type)
Bas operator
Cis operator
Dtypeof operator
What is boxing in C#?
AConverting a reference type to a value type
BConverting a string to a number
CCasting between two reference types
DConverting a value type to an object
Describe how implicit and explicit type conversions work in C# and when you should use each.
Think about when the computer converts types automatically versus when you must tell it to convert.
You got /4 concepts.
    Explain boxing and unboxing in C# and why they might affect program performance.
    Consider how value types become objects and back.
    You got /5 concepts.