class Program {
static void Main(string[] args) {
Int32 i = 123;
Double d = 123.456;
FunPrint(i);
FunPrint(d);
}
static void FunPrint(object obj) {
Console.WriteLine(obj);
}
}
My understanding of this sample is that FunPrint()
first creates a new object and builds it based on the value of the ValueType being passed (Int32
in this case). Second, the Object.ToString()
is called and correctly displays ValueType-specific string formatting.
Value types do not contain virtual functions so...
What I do not understand is how the Object
knows what type it is holding internally in order to do the proper string formatting.
The calling function boxes the argument before calling
FunPrint
.Actually they can. You can implement an interface from a value type. You just can't derive from one, which limits the level of overriding.
However to call a
virtual functionfunction virtually, you need to box the value type.The mechanism applies equally here. The value is already boxed, so you can call its virtual members.
Edit to clarify calling interface methods on a value types:
Edit to include suggestion from Jon Hanna. Calling a non-virtual method of
System.Object
on a value type does require boxing.You can see that in the corresponding IL:
Object.GetType()
is not able to be called virtually, and has signature:Yet it still requires boxing.