I got the following code:
object var3 = 3;
Console.WriteLine(var3.GetType().ToString());
Console.WriteLine(typeof(object).ToString());
The output is:
System.Int32
System.Object
Why aren't they both System.Object
?
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System. Object instance and stores it on the managed heap. Unboxing extracts the value type from the object.
If I look up what unboxing and boxing does you see that the difference is that boxing allocates memory on the heap and unboxing moves a value-type variable to the stack. Accesing the stack is faster than the heap and therefore unboxing is in your case faster.
The GetType()
function returns the actual type of the instance in the variable.
Even though your variable is declared as object
, it's actually holding a boxed Int32
instance.
If you're asking why the boxedObject.GetType() does not return Object.. check out the image under the Section 'Boxing Conversion' on the MSDN Boxing and Unboxing page. Good question btw.. atleast my understanding of your question.
Although I may not be technically correct, it looks like
Ignoring the topic of boxing, all classes inherit from type object. This is true for both reference types and value types. GetType shows the most derived type, which in this case is System.Int32.
One of the few times GetType is going to return System.Object is if you do this:
object var = new Object();
Console.WriteLine(var.GetType().ToString());
Boxing refers to when a value type is pointed to by a reference type. Generally this is done as a System.Object reference. TypeOf will return the most derived actual type, not the reference type.
class A
{
}
class B : A
{
}
class C : B
{
}
object obj1 = new ClassA();
ClassB obj2 = new ClassB();
ClassB obj3 = new ClassC();
GetType will do similar things for these types.
System.Console.WriteLine(obj1.GetType().ToString());
System.Console.WriteLine(obj2.GetType().ToString());
System.Console.WriteLine(obj3.GetType().ToString());
ClassA
ClassB
ClassC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With