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

Object type as universal base in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Object Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code using object as base?

Consider this C# code where object is used as a universal base type. What will be printed?

C Sharp (C#)
object val = 123;
Console.WriteLine(val.GetType());
ASystem.Int32
BSystem.Object
C123
DSystem.String
Attempts:
2 left
💡 Hint

Remember that object can hold any type, but GetType() returns the actual runtime type.

Predict Output
intermediate
2:00remaining
What is the output when casting object to string?

What will this code print?

C Sharp (C#)
object val = "hello";
string s = (string)val;
Console.WriteLine(s.Length);
ASystem.String
B5
Chello
DRuntime error
Attempts:
2 left
💡 Hint

Check the length of the string stored inside the object.

🔧 Debug
advanced
2:00remaining
Why does this code cause an exception?

Examine the code below. Why does it throw an exception at runtime?

C Sharp (C#)
object val = 42;
string s = (string)val;
Console.WriteLine(s);
ACompile-time error due to invalid cast
BNullReferenceException because val is null
CInvalidCastException because int cannot be cast to string
DNo exception, prints 42
Attempts:
2 left
💡 Hint

Think about what types can be cast directly to string.

🧠 Conceptual
advanced
2:00remaining
What is the result of using object.Equals with different types?

What does this code print?

C Sharp (C#)
object a = 10;
object b = "10";
Console.WriteLine(a.Equals(b));
AFalse
BRuntime exception
CCompile-time error
DTrue
Attempts:
2 left
💡 Hint

Check if Equals compares values or types.

Predict Output
expert
3:00remaining
What is the output of this polymorphic object array?

Given this array of objects holding different types, what will be printed?

C Sharp (C#)
object[] arr = { 1, "two", 3.0 };
foreach (var item in arr)
{
    Console.WriteLine(item.GetType().Name);
}
A
1
two
3.0
B
Object
Object
Object
C
int
string
double
D
Int32
String
Double
Attempts:
2 left
💡 Hint

Remember GetType() returns the runtime type of each element.