Consider this C# code where object is used as a universal base type. What will be printed?
object val = 123;
Console.WriteLine(val.GetType());Remember that object can hold any type, but GetType() returns the actual runtime type.
The variable val holds an integer value 123. Although declared as object, the actual type is System.Int32. So GetType() returns System.Int32.
What will this code print?
object val = "hello";
string s = (string)val;
Console.WriteLine(s.Length);Check the length of the string stored inside the object.
The object val holds a string "hello". Casting it back to string works fine. The length of "hello" is 5.
Examine the code below. Why does it throw an exception at runtime?
object val = 42;
string s = (string)val;
Console.WriteLine(s);Think about what types can be cast directly to string.
The variable val holds an int boxed as object. Casting directly to string causes InvalidCastException because int and string are unrelated types.
What does this code print?
object a = 10; object b = "10"; Console.WriteLine(a.Equals(b));
Check if Equals compares values or types.
The Equals method returns false because a is an int and b is a string, so they are not equal.
Given this array of objects holding different types, what will be printed?
object[] arr = { 1, "two", 3.0 };
foreach (var item in arr)
{
Console.WriteLine(item.GetType().Name);
}Remember GetType() returns the runtime type of each element.
The array holds an int, a string, and a double boxed as objects. GetType().Name returns their actual type names: Int32, String, Double.