Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Implement Generic Method to do Math calculations on different value types

Tags:

I have a method that accepts an IEnumerable-decimals and performance various math functions. I want to use the same method on an IEnumerable-int-. How do I implement this? For example to find a simple sum?

void Calculate<T>(IEnumerable <T> ListOFNumbers)
{
   int count= ListofNumbers.Count();
   ?sum=?;
}
like image 953
zsharp Avatar asked May 02 '09 05:05

zsharp


People also ask

Where is generic method?

The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.

How to use generic method in java?

For static generic methods, the type parameter section must appear before the method's return type. The complete syntax for invoking this method would be: Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util. <Integer, String>compare(p1, p2);

What is generic calculation?

A generic formula is not really a formula at all: it contains no code and does no processing. The only purpose of a generic formula is to provide an alternative formula ID (metric ID) for the metrics produced by a collection formula.

What is generic in C#?

Generic means the general form, not specific. In C#, generic means not specific to a particular data type. C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods, properties, events, delegates, and operators using the type parameter and without the specific data type.


1 Answers

This is all freely available in MiscUtil. The Operator class provides access to generic arithmetic; and there are generic implementations (as extension methods) of Sum, Average, etc - and works with any type with suitable operators in addition to the primitives. So for example, you could use Sum with of Complex<T>, etc.

Note that it currently uses .NET 3.5; I did have a 2.0 version somewhere, but it isn't as tested....

A simplified example of sum is shown in the usage document:

public static T Sum<T>(this IEnumerable<T> source)
{
    T sum = Operator<T>.Zero;
    foreach (T value in source)
    {
        if (value != null)
        {
            sum = Operator.Add(sum, value);
        }
    }
    return sum;
}

Although IIRC the actual implementation has a bit more...

As an aside, note that dynamic (in .NET 4.0 / C# 4.0) supposedly supports operators, but we'll have to wait for the beta to see what it does. From my previous looks at dynamic in the CTP, I expect it to be a bit slower than the MiscUtil code, but we shall see.

like image 198
Marc Gravell Avatar answered Oct 05 '22 14:10

Marc Gravell