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
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
Six options:
T
Dictionary<Type, Func<object, object>>
containing a delegate for every type you care aboutUse 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.
You can't do this with generics - there are no generic type constraints that will ensure that the passed in type is a numeric type.
I think it's simply illogical write a generic method for essentially something that behaves differently. Floats and doubles works in a similar way, but int doesn't work in that way (they don't have a decimal part).
Write an overload for each method should be the correct way to handle this, otherwise you'll end up doing bunch of if typeof which is basically wrong.
You can take type of T by T.GetType(). But it will not help you. You can't write generic method but can write Abs method for object:
private static object Abs(object num)
{
var type = num.GetType();
if (type == typeof(Int32))
{
return Math.Abs((int) num);
}
if (type == typeof(Int64))
return Math.Abs((long)num);
if (type == typeof(Int16))
return Math.Abs((short)num);
if (type == typeof(float))
return Math.Abs((float)num);
if (type == typeof(double))
return Math.Abs((double)num);
if (type == typeof(decimal))
return Math.Abs((decimal)num);
throw new ArgumentException(string.Format("Abs is not defined for type {0}", type.FullName));
}
One thing you can do is just request the Abs function:
T someGenericFunction<T>(
T value1,
T value2,
Func<T, T> absFunction
) {
...
var abs1 = absFunction(value1);
...
}
...
var decimalResult = someGenericFunction<decimal>(1.2m, -2.3m, Math.Abs);
var intResult = someGenericFunction<int>(5, 7, Math.Abs);
//etc.
// also allows you to use other kinds of abs function
var customResult = someGenericFunction<CustomType>(value1, value2, CustomType.Abs);