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

In Haskell, the language I'm most familiar with, there is a fairly accurate way to determine the type of a variable. However, in the process of learning C #, I was somewhat embarrassed in this regard. For example, the signature for the Array.Sort method:

 public static void Sort( Array array ) 

However, this method will throw an exception if the argument is null , multidimensional, or does not implement the IComparable interface. So why is it not an IComparable[] type, if possible?

+6
source share
1 answer

If you write a method today, you would use something like this:

 public static void Sort<T>(T[] array) where T : IComparable // or even IComparable<T> { ... } 

This cannot guarantee that the array is not null at compile time (unfortunately), but it can guarantee that the array is of type comparable and one-dimensional. A null check should still be a runtime check.

But it depends on generics that were not added to the language before .NET 2.0. (It also uses generic method-level generators, rather than generic-level classes that were not added before .NET 3.5). Array.Sort been added to .NET 1.0. This has not been changed because it would be a terrific change that language developers prefer not to.

+11
source

Source: https://habr.com/ru/post/958112/


All Articles