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

Getting type information at runtime in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Runtime Type Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Type Name Retrieval
What is the output of this C# code snippet?
C Sharp (C#)
int number = 42;
Console.WriteLine(number.GetType().Name);
A"System.Int32"
B"int"
C"Number"
D"Int32"
Attempts:
2 left
💡 Hint
Use GetType() and check the Name property.
Predict Output
intermediate
2:00remaining
Output of Checking Type Equality
What will this code print?
C Sharp (C#)
object obj = "hello";
if (obj.GetType() == typeof(string))
    Console.WriteLine("Match");
else
    Console.WriteLine("No Match");
AMatch
BNo Match
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
Compare the runtime type of obj with typeof(string).
🔧 Debug
advanced
2:00remaining
Identify the Error in Type Checking
What error does this code produce when run?
C Sharp (C#)
object val = null;
if (val.GetType() == typeof(object))
    Console.WriteLine("Object");
else
    Console.WriteLine("Not Object");
APrints "Not Object"
BPrints "Object"
CNullReferenceException
DCompilation error
Attempts:
2 left
💡 Hint
Check what happens when calling GetType() on null.
🧠 Conceptual
advanced
2:00remaining
Understanding typeof vs GetType()
Which statement is true about typeof and GetType() in C#?
Atypeof gets the compile-time type; GetType() gets the runtime type of an instance
Btypeof gets the runtime type; GetType() gets the compile-time type
CBoth typeof and GetType() return the same type information always
Dtypeof can only be used on variables; GetType() only on types
Attempts:
2 left
💡 Hint
Think about when you use typeof and when you call GetType().
Predict Output
expert
2:00remaining
Output of Type Checking with Inheritance
What is the output of this code?
C Sharp (C#)
class Animal {}
class Dog : Animal {}

Animal pet = new Dog();
Console.WriteLine(pet.GetType() == typeof(Animal));
ATrue
BFalse
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
GetType() returns the actual runtime type, not the declared type.