Ever tried to use IEnumerable<T>.Sum on an array of unsigned long integers? Well, you can’t, because the Sum method has not been implemented for ulong or ulong?, so to fill in the gap here’s the extension methods you need using more or less the same code as the existing Sum methods:

I used some custom PostSharp attributes here to do the parameter validation, but you can just as easily substitute them with if null then throw exception code blocks.

UPDATE 10/11/2010:

Using the dynamic type in .Net 4 you can make these extension methods even more useful by making them usable with other value types too.

Traditionally for extension methods like Sum, you’d have to provide an overload for each numeric value type (int, uint, long, etc.) because these numeric value types don’t have a common super type which defines the numeric operators +, -, /, *, etc.

Fortunately, you can now negate this compile time limitation by making it a runtime decision using the new dynamic capabilities:

The obvious fallacy with this approach is that you can now pass custom structures with no defined + operator into these extension methods and no compile errors will be thrown, but a RuntimeBinderException will be thrown by the DLR at runtime with a message like this:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Operator ‘+’ cannot be applied to operands of type ‘xxx’ and ‘xxx’

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.