Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Sum Method

This C# example program uses the Sum extension method. It requires System.Linq.

Sum totals values in an array.

It computes the sum total of all the numbers in an array, or List, of integers. This extension method in LINQ provides an excellent way to do this with minimal calling code. It has some drawbacks.

Example. The Sum method described here does not exist on either the array abstract base class or the List type. It is instead an extension method found in the System.Linq namespace, which you must include with a using directive.

Tip: The method can be used on objects that implement IEnumerable with a type of decimal, double, int or long.


C# program that uses Sum

using System;
using System.Collections.Generic;
using System.Linq;

class Program
    static void Main()
	// Declare two collections of int elements.
	int[] array1 = { 1, 3, 5, 7 };
	List<int> list1 = new List<int>() { 1, 3, 5, 7 };

	// Use Sum extension on their elements.
	int sum1 = array1.Sum();
	int sum2 = list1.Sum();

	// Write results to screen.

    (All element values were added together to get the result.)


The program declares an int array and populates it with four odd numbers, and then declares a List with the same numbers. Sum() is invoked on those two variable references. It loops over the values and returns the sum of the elements.

Int Array

Finally: The program writes the sums to the screen. It uses Console.WriteLine to do this.


Discussion. There are drawbacks associated with the Sum extension method. The Sum method has some overhead that will make it slower than a simple for-loop in the C# language. It inserts a null check at the start of its method body.


Also: It uses a foreach-loop, which can produce slower execution on value types.


By using Sum, you avoid copying code into your program source and instead exploit code inside the Framework that is more tested. This will reduce the assembly's code size and number of lines of C# code. This could be preferable.

Summary. You can use the Sum extension method to total the values of elements in an array or List. We noted the implementation in the base class library of the Sum extension, as well as some overloads you can use.

And: It provides a way for you to write less code that requires less thought to maintain, at the price of runtime performance.