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=?;
}
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.
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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With