Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Create a Generic Method for Sum In C# [duplicate]

Tags:

c#

generics

Possible Duplicate:
Generics - where T is a number?

I have created a generic method for maximum and I use IComparable interface

Does anybody know how can I create a generic method for Sum? Which interface is useful in this method?

Here is my code for GetMax:

public static T GetMax<T>(T[] array) where T : IComparable
    {
        T min = array[0];

        foreach (T item in array)
        {
            if (min.CompareTo(item) < 0)
            {
                min = item;
            }
        }
        return min;
    }
like image 506
Rasul jalalifar Avatar asked Jan 26 '13 21:01

Rasul jalalifar


People also ask

Can we create a generic method inside a non generic class?

Yes, you can define a generic method in a non-generic class in Java.

What is the correct way of defining a generic method?

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

How do you add generic constraints?

You can specify one or more constraints on the generic type using the where clause after the generic type name. The following example demonstrates a generic class with a constraint to reference types when instantiating the generic class.

What are generics in C?

Generics are similar to templates in C++ but are different in implementation and capabilities. Generics introduces the concept of type parameters, because of which it is possible to create methods and classes that defers the framing of data type until the class or method is declared and is instantiated by client code.


3 Answers

this operation already exists Linq.Sum()

var sum = new List<int>{1,2,3}.Sum();
like image 75
burning_LEGION Avatar answered Oct 17 '22 19:10

burning_LEGION


No, you can't create one generic method for all types. But you can use LINQ extension method Sum for some types: decimal, double, int, long, ... See more types here: Enumerable.Sum.

int[] array1 = { 1, 3, 5, 7 };
int sum1 = array1.Sum();

For your own types you can create and implement interface ISummable:

interface ISummable<T>
{
   T Add(T a, T b);
}

Then your generic method will be similar to this one:

T Sum<T>(T a, T b) where T:ISummable<T>
{
    return a.Add(a,b);
}

See more information here: Making generics add up.

like image 26
algreat Avatar answered Oct 17 '22 20:10

algreat


I assume you want to write a generic method Sum like this:

static T Sum<T>(this IEnumerable<T> values) where T : ??
{
    T result = 0;
    foreach (var value in values)
    {
        result = result + value;
    }
    return result;
}

Unfortunately there is no constraint that you could put in place of ?? to make this work.

The data types built into .NET implement certain interfaces. For example, int implements IComparable, IFormattable, IConvertible, IComparable<int>, and IEquatable<int>. None of these provide an Add method (or + operator) that would allow you to implement a Sum method. And you cannot add interface implementation to existing types.

What you can do, is pass a an object to the Sum method that knows how to add two values of the generic type:

static T Sum<T>(this IEnumerable<T> values, IAdder<T> adder)
{
    T result = adder.Zero;
    foreach (var value in values)
    {
        result = adder.Add(result, value);
    }
    return result;
}

with

interface IAdder<T>
{
    T Zero { get; }

    T Add(T a, T b);
}

and

class Int32Adder : IAdder<Int32>
{
    public static readonly Instance = new Int32Adder();

    public int Zero { get { return 0; } }

    public int Add(int a, int b) { return a + b; }
}
like image 23
dtb Avatar answered Oct 17 '22 20:10

dtb