It's time for everyone's favourite game show: BOX OR NO BOX!
public string DoIntToString(int anInt)
{
return anInt.ToString();
}
BOX or NO BOX? Let's go to the IL:
IL_0001: ldarga.s anInt
IL_0003: call instance string [mscorlib]System.Int32::ToString()
NO BOX. ToString()
is a virtual
method on object
that is overridden by int
. Since struct
s can't participate in non-interface inheritence, the compiler knows that there are no subclasses of int
, and can generate a call to the int
version of ToString()
directly.
static Type DoIntGetType(int anInt)
{
return anInt.GetType();
}
BOX or NO BOX? Let's go to the IL:
IL_0001: ldarg.0
IL_0002: box [mscorlib]System.Int32
IL_0007: call instance class [mscorlib]System.Type [mscorlib]System.Object::GetType()
BOX. GetType()
is not virtual
on object
, so there is no int
version of the method. The argument has to be boxed, and the call is made on the new boxed object.
private static string DoIntToStringIFormattable(int anInt)
{
return anInt.ToString(CultureInfo.CurrentCulture);
}
BOX or NO BOX? Let's go to the IL:
IL_0001: ldarga.s anInt
IL_0003: call class [mscorlib]System.Globalization.CultureInfo [mscorlib]System.Globalization.CultureInfo::get_CurrentCulture()
IL_0008: call instance string [mscorlib]System.Int32::ToString(class [mscorlib]System.IFormatProvider)
NO BOX. Even though ToString(IFormattable)
is an implementation of the IFormatProvider
interface, the call itself is being made directly against the int
. For the same reason as the first method, no box is required.
So for the final round, we have your method:
public int CompareIntValues(int left, int right)
{
return left.CompareTo(right);
}
Knowing that CompareTo(int)
is implicit implementation of IComparable<int>
, you make the call: BOX or NO BOX?