Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an array of ints to a function that accepts array of IComparable?

I have a C# function that accepts an array of IComparable

public static void sort(IComparable[] a){//...}

If I send an array of strings to this function it is accepted, but an array of ints is not accepted even though the structure Int32 extends IComparable.

public struct Int32 : IComparable, IFormattable, 
IConvertible, IComparable<int>, IEquatable<int>

First question is why it is not possible to send an array of value type to such a function.

Second question is how should I send the array of value type to the function that accepts array of IComparable.

like image 519
Horea Avatar asked Jan 29 '15 15:01

Horea


1 Answers

Although an int is an IComparable, an int[] isn't an IComparable[]. Imagine if it were:

int[] x = new int[10];
IComparable[] y = x;
y[0] = "hello";

That would be trying to store a reference in an int[]. Badness.

Basically, value-type arrays aren't covariant. (Reference type arrays are covariant at compile-time, but will throw if you try to store an invalid value at execution time. That's a design flaw IMO, but never mind...)

The way to fix this is to use generics:

public static void Sort<T>(T[] array) where T : IComparable

Or even better use the generic form of IComparable:

public static void Sort<T>(T[] array) where T : IComparable<T>

(That way you'll avoid boxing when you call CompareTo.)

like image 141
Jon Skeet Avatar answered Nov 14 '22 23:11

Jon Skeet