Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Abs(T value) generics c#

Tags:

c#

math

generics

I would like to create generic function Math.Abs() but i don't know how to make this. if i create a class Math i can't create method Abs for T value because i don't know the type of T.

If someone know how to do this ?

Thanks

like image 616
Econus Avatar asked Oct 15 '25 22:10

Econus


1 Answers

Six options:

  • Use reflection based on the execution-time type of T
  • Use an overload for each type you care about
  • Use if/else for every type you care about
  • Create a Dictionary<Type, Func<object, object>> containing a delegate for every type you care about
  • Use dynamic in .NET 4:

    public T Foo<T>(T value)
    {
        dynamic d = value;
        return Math.Abs(d);
    }
    
  • Use something like Marc Gravell's generic operators part of MiscUtil

I'd probably go for the overload option if possible. It will constrain you appropriately at compile-time, and avoid any potentially time-consuming boxing/reflection.

like image 167
Jon Skeet Avatar answered Oct 17 '25 12:10

Jon Skeet