-
boxing and generics
I have two ref parameters for a generic method like this:
Code:
static T Min<T>(ref T a, ref T b) where T : IComparable<T>
{
return a.CompareTo(b) < 0 ? a : b ;
}
Now when I call this with int parameters
Code:
int a = 0, b = 1;
int c = Min(ref a, ref b);
will a and b get boxed or not?
-
I believe if you're relying on the ICompareable<T>.CompareTo() method, then yes, because the parameter is type object. int has another overload that takes an int as a parameter, which would avoid boxing, but that isn't available in your generic method.
EDIT: You might find this interesting. A value copy of MyType is returned from the Min() function so the original value stays the same:
Code:
class Program
{
static void Main(string[] args)
{
MyType lower = new MyType { Num = 5 }, higher = new MyType { Num = 7 };
MyType min = Min(ref lower, ref higher);
min.Num = 100;
Console.WriteLine("lower = {0}, higher = {1}, min = {2}", lower.Num, higher.Num, min.Num);
}
static T Min<T>(ref T a, ref T b) where T : IComparable<T>
{
return a.CompareTo(b) < 0 ? a : b;
}
}
struct MyType : IComparable<MyType>
{
public int Num;
public int CompareTo(MyType other)
{
return Num.CompareTo(other.Num);
}
}
My output:
Code:
lower = 5, higher = 7, min = 100
-
I found the answer by accident in the book CLR via C#
they are not boxed because T has the IComparable<T> constraint and not IComparable.
If you do the following it would be boxed:
Code:
int x =1, y = 2;
IComparable c = x;
x.CompareTo(y); // boxed
This will not be boxed:
Code:
int x =1, y = 2;
IComparable<int> c = x;
x.CompareTo(y); // not boxed