Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine the appropriate type for method parameters in C#?

Tags:

c#

.net

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?

like image 654
user2939875 Avatar asked Nov 14 '13 22:11

user2939875


1 Answers

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.

like image 64
Servy Avatar answered Sep 17 '22 23:09

Servy