In Haskell, the language I'm most familiar with, there is a fairly precise way to determine the type of a variable. However, in the process of learning C#, I've become somewhat confused in this regard. For example, the signature for the Array.Sort
method is:
public static void Sort(
Array array
)
Yet, this method will raise an exception if the argument is null
, multidimensional, or does not implement the IComparable
interface. So, why isn't the type IComparable[]
, if possible?
If one were to write the method today you'd use something like this:
public static void Sort<T>(T[] array)
where T : IComparable // or even IComparable<T>
{ ... }
This can't enforce that the array isn't null at compile time (sadly) but it can ensure that the array is of a type that is comparable and that it is single dimensional. The null check would still need to be a runtime check.
But this relies on generics, which weren't added to the language until .NET 2.0. (This also uses method level generics, rather than class level generics, which weren't added until .NET 3.5) Array.Sort
was added to the language in .NET 1.0. It hasn't been changed because that would be a breaking change, one that the language designers choose not to make.
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