HOWTO · Csharp
Standard Deviation in C#
Calculate population standard deviation in C# with a custom method or an extension method, and handle empty or reusable sequences.
On this page
Standard deviation describes how far values typically vary from their mean. This guide shows two ways to calculate it in C#: a custom method and an extension method. Both examples calculate the population standard deviation.
What Standard Deviation Measures
For values (x_1, x_2, \dots, x_N), first find their mean (\mu). Then square each value’s difference from the mean, average those squared differences, and take the square root:
Dividing by (N), the number of values, makes this the population standard deviation. If the values are a sample used to estimate a larger population, the sample standard deviation usually divides by (N - 1) instead. Choose the formula that matches what your data represents.
Calculate Population Standard Deviation with a Custom Method
The method below accepts IEnumerable<double>, copies it to an array, and calculates the mean and squared differences from that snapshot. The standardDeviation name is retained for callers that use it directly.
Run this example:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
class Program
{
static double standardDeviation(IEnumerable<double> sequence)
{
double[] values = sequence.ToArray();
if (values.Length == 0)
return 0;
double mean = values.Average();
double squaredDifferenceSum = values.Sum(value => Math.Pow(value - mean, 2));
return Math.Sqrt(squaredDifferenceSum / values.Length);
}
static void Main()
{
var values = new List<double> { 1, 2, 3, 4, 5 };
Console.WriteLine(string.Format(CultureInfo.InvariantCulture,
"Population standard deviation = {0:F13}", standardDeviation(values)));
}
}
Population standard deviation = 1.4142135623731
ToArray() creates one stable snapshot, so Average() and Sum() operate on the same values. The mean of this list is 3; the squared differences sum to 10, and the population variance is (10 / 5 = 2). Its square root is approximately 1.4142135623731.
Use an Extension Method
An extension method keeps the same calculation reusable while allowing call syntax such as values.standardDeviation(). It must be declared in a static class, and its first parameter uses this to identify the extended type. This complete version applies the same snapshot and empty-input convention as the custom method:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
static class StatisticsExtensions
{
public static double standardDeviation(this IEnumerable<double> sequence)
{
double[] values = sequence.ToArray();
if (values.Length == 0)
return 0;
double mean = values.Average();
double squaredDifferenceSum = values.Sum(value => Math.Pow(value - mean, 2));
return Math.Sqrt(squaredDifferenceSum / values.Length);
}
}
class Program
{
static void Main()
{
var values = new List<double> { 1, 2, 3, 4, 5 };
Console.WriteLine(string.Format(CultureInfo.InvariantCulture,
"Population standard deviation = {0:F13}", values.standardDeviation()));
}
}
Population standard deviation = 1.4142135623731
Use the custom method when a normal method call suits the surrounding API. Choose extension syntax when the operation naturally reads as behavior on a sequence. Both calculate population standard deviation; the extension syntax does not change the statistical formula.
Handle Empty and Reusable Sequences
The examples return 0 for an empty sequence so both APIs behave consistently. Because zero can also be a legitimate standard deviation for identical values, callers that need to distinguish “no data” from “no variation” should choose a different explicit policy, such as rejecting empty input or returning a nullable result.
An IEnumerable<double> is not necessarily a reusable collection. It can represent a generator, a changing data source, or a sequence that only supports one pass. Calling Any(), Average(), Sum(), and Count() separately can enumerate it repeatedly, potentially doing extra work or observing different values. Materializing once with ToArray() avoids that repeated traversal and ensures every part of the calculation uses the same values. For very large streams, use a single-pass algorithm that accumulates the count, mean, and squared differences rather than storing every value.