c# - Why don't number types share a common interface? -


i ran across problem, wanted function work on both doubles , integers , wondered, why there no common interface number types (containing arithmetic operators , comparisons).

it make writing functions math.min (which exist in gazillion overloads) way more convenient.

would introducing additional interface breaking change?

edit: think using like

public t add<t>(t a, t b) t: inumber {     return a+b; } 

or

public t range<t>(t x, t min, t max) t:inumber {     return max(x, min(x, max), min); } 

if want such kind of "generic" arithmetics option in strongly-typed language such c# quite limited. marc gravell described problem follows:

.net 2.0 introduced generics .net world, opened door many elegant solutions existing problems. generic constraints can used restrict type-arguments known interfaces etc, ensure access functionality - or simple equality/inequality tests comparer<t>.default , equalitycomparer<t>.default singletons implement icomparer<t> , iequalitycomparer<t> respectively (allowing sort elements instance, without having know "t" in question).

with this, though, there still big gap when comes operators. because operators declared static methods, there no imath<t> or similar equivalent interface numeric types implement; , indeed, flexibility of operators make hard in meaningful way. worse: many of operators on primitive types don't exist operators; instead there direct il methods. make situation more complex, nullable<> demands concept of "lifted operators", inner "t" describes operators applicable nullable type - implemented language feature, , not provided runtime (making reflection more fun).

however, c# 4.0 introduced dynamic keyword can use choose correct overload @ runtime:

using system;  public class program {     static dynamic min(dynamic a, dynamic b)     {         return math.min(a, b);             }      static void main(string[] args)     {         int = min(3, 4);         double d = min(3.0, 4.0);     } } 

you should aware removes type-safety , might exceptions @ runtime if dynamic runtime cannot find suitable overload call, e.g. because mixed types.

if want type-safety might want have @ classes available in miscutil library providing generic operators basic operations.

please note if after specific operations might use interfaces built-in types implement. example, type-safe generic min function this:

public static t min<t>(params t[] values) t : icomparable<t> {     t min = values[0];     foreach (var item in values.skip(1))     {         if (item.compareto(min) < 0)             min = item;     }     return min; } 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -