Calculating Net Promoter Score is one of those programming tasks that initially looks too simple to deserve a dedicated application.
You count the number of promoters, subtract the number of detractors, divide by the total number of responses and multiply by 100. A few lines of C# should be enough.
However, things become a little more interesting when you start working with actual survey data.
What should happen if a CSV file contains missing responses? Can we calculate an overall NPS by averaging scores from different customer segments? How do we know whether an improvement of five points is statistically meaningful?
These are the kinds of problems I find interesting about building analytics applications. The calculation itself is rarely the difficult part. Making sure the result is something people can trust requires considerably more thought.
In this article, I will walk through how to build an NPS calculation engine using C# and .NET, import survey responses from CSV files, calculate approximate confidence intervals and expose the results through an API.
1. Understanding Net Promoter Score
Net Promoter Score, commonly known as NPS, measures a customer's willingness to recommend a product, service or business.
Customers respond to a survey question using a scale from 0 to 10. Their responses are divided into three groups.
Category | Score |
|---|---|
Detractors | 0–6 |
Passives | 7–8 |
Promoters | 9–10 |
The formula is:
NPS = ((Promoters − Detractors) / Total Responses) × 100
Suppose we receive the following survey results:
55 promoters
25 passives
20 detractors
The NPS is:
(55 − 20) / 100 × 100 = +35
The result ranges from -100 to +100.
One detail worth remembering is that passives still contribute to the total number of responses. Excluding them from the denominator is a surprisingly easy mistake to make when implementing this formula.
2. Setting up the .NET project
I would keep the calculation logic separate from the application that consumes it. This makes it easier to reuse the same implementation in a console application, web API or analytics dashboard.
We will use .NET 10 for this example.
Create three projects:
mkdir NpsCalculator
cd NpsCalculator
dotnet new classlib -n Nps.Core
dotnet new console -n Nps.Cli
dotnet new xunit -n Nps.Tests
dotnet add Nps.Cli/Nps.Cli.csproj reference Nps.Core/Nps.Core.csproj
dotnet add Nps.Tests/Nps.Tests.csproj reference Nps.Core/Nps.Core.csprojFor CSV processing, we will use CsvHelper. Rather than depending on whichever package version happens to be installed, this example uses version 33.1.0.
dotnet add Nps.Core/Nps.Core.csproj package CsvHelper --version 33.1.0The project structure will look like this:
NpsCalculator/
Nps.Core/
NpsCounts.cs
NpsCalculator.cs
CsvImporter.cs
Nps.Cli/
Program.cs
Nps.Tests/
NpsCalculatorTests.csThe core library will have no dependency on the user interface.
3. Representing survey results efficiently
We could store every survey response in a list of integers. For a small dataset, there is nothing particularly wrong with that approach.
However, calculating NPS only requires three numbers: promoter, passive and detractor counts.
If we are processing a CSV containing a million responses, there is no need to retain all those individual scores in memory just to calculate NPS.
Create a file called NpsCounts.cs inside Nps.Core.
namespace Nps.Core;
public readonly record struct NpsCounts
{
public long Promoters { get; }
public long Passives { get; }
public long Detractors { get; }
public long Total =>
Promoters + Passives + Detractors;
public NpsCounts(
long promoters,
long passives,
long detractors)
{
if (promoters < 0 ||
passives < 0 ||
detractors < 0)
{
throw new ArgumentOutOfRangeException(
nameof(promoters),
"Response counts cannot be negative.");
}
// Detect overflow before storing the counts.
_ = checked(
promoters + passives + detractors);
Promoters = promoters;
Passives = passives;
Detractors = detractors;
}
public NpsCounts Merge(NpsCounts other)
{
return new NpsCounts(
checked(Promoters + other.Promoters),
checked(Passives + other.Passives),
checked(Detractors + other.Detractors)
);
}
}There are a couple of decisions behind this implementation.
First, using long rather than int gives us more room when combining large datasets.
Second, the checked expressions prevent integer overflow from silently corrupting the result.
Finally, the structure is immutable. Once a set of survey counts has been created, another part of the application cannot accidentally modify it.
This representation requires constant memory for the aggregated result, regardless of how many survey responses we process.
Of course, if we need to display the distribution of all 11 possible scores, we would need an 11-element histogram instead. If we need to analyse written feedback or identify duplicate respondents, we would need to retain additional information.
For this example, three counters are enough.
4. Implementing the calculation engine
Let us create NpsCalculator.cs.
namespace Nps.Core;
public sealed record NpsResult(
long Responses,
double? Score,
double? Lower95,
double? Upper95
);
public static class NpsCalculator
{
public static NpsResult Calculate(
NpsCounts counts)
{
long n = counts.Total;
if (n == 0)
{
return new NpsResult(
0, null, null, null);
}
double p =
(double)counts.Promoters / n;
double d =
(double)counts.Detractors / n;
double score =
100.0 *
(counts.Promoters - counts.Detractors) / n;
// Conservative guard for the normal approximation.
if (n < 30 ||
counts.Promoters < 5 ||
counts.Passives < 5 ||
counts.Detractors < 5)
{
return new NpsResult(
n, score, null, null);
}
double variance =
p + d - Math.Pow(p - d, 2);
double standardError =
100 * Math.Sqrt(
Math.Max(0, variance) / n);
double margin = 1.96 * standardError;
return new NpsResult(
n,
score,
Math.Max(-100, score - margin),
Math.Min(100, score + margin)
);
}
}The calculation engine returns null when there are no survey responses.
I prefer this to returning zero because zero is a perfectly valid NPS score. It means promoters and detractors are balanced. An empty dataset tells us something entirely different: we have no data.
Another decision is to avoid rounding the score inside the calculation engine. Rounding belongs in the presentation layer.
The confidence interval calculation will be explained in more detail shortly.
5. Importing survey responses from a CSV file
Most businesses collect customer feedback through survey platforms, CRM systems or helpdesks. The results are frequently exported as CSV files.
Consider the following example:
customer_id,score,feedback
A001,10,"Excellent support"
A002,9,"Very helpful"
A003,8,"Good, but slightly slow"
A004,6,"Issue not fully resolved"
A005,,"No response"
A006,11,"Invalid score"This small dataset contains several situations we need to handle.
There is a missing score, an invalid score and a feedback field containing a comma.
Splitting every line using string.Split(',') would not correctly handle quoted CSV fields.
I would use a proper CSV parser rather than attempting to implement the format myself.
Create CsvImporter.cs:
using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration;
namespace Nps.Core;
public sealed record ImportResult(
NpsCounts Counts,
long InvalidRows
);
public static class CsvImporter
{
public static ImportResult Import(
TextReader reader)
{
var config = new CsvConfiguration(
CultureInfo.InvariantCulture)
{
DetectColumnCountChanges = true
};
using var csv = new CsvReader(
reader, config, leaveOpen: true);
long promoters = 0;
long passives = 0;
long detractors = 0;
long invalidRows = 0;
if (!csv.Read())
{
return new ImportResult(
new NpsCounts(0, 0, 0), 0);
}
csv.ReadHeader();
var headers = csv.HeaderRecord
?? throw new FormatException(
"CSV header is missing.");
var scoreColumns = headers
.Select((name, index) =>
new { Name = name, Index = index })
.Where(x => string.Equals(
x.Name.Trim(),
"score",
StringComparison.OrdinalIgnoreCase))
.ToArray();
if (scoreColumns.Length != 1)
{
throw new FormatException(
"CSV must contain exactly one score column.");
}
int scoreIndex = scoreColumns[0].Index;
while (csv.Read())
{
string? raw = csv.GetField(scoreIndex);
bool valid = int.TryParse(
raw?.Trim(),
NumberStyles.None,
CultureInfo.InvariantCulture,
out int score
);
checked
{
if (!valid || score < 0 || score > 10)
{
invalidRows++;
continue;
}
if (score >= 9)
{
promoters++;
}
else if (score >= 7)
{
passives++;
}
else
{
detractors++;
}
}
}
return new ImportResult(
new NpsCounts(
promoters,
passives,
detractors),
invalidRows
);
}
}The implementation processes one record at a time rather than loading every response into a collection.
Invalid scores are counted separately and excluded from the calculation. Structurally malformed CSV records can cause the import to fail rather than being silently accepted.
Notice that we explicitly identify the score column by its header. I would not automatically choose the first numeric column because survey exports might contain customer IDs, transaction amounts, dates and several different survey questions.
6. Running the calculator
Replace Program.cs inside Nps.Cli with:
using Nps.Core;
if (args.Length != 1)
{
Console.WriteLine(
"Usage: Nps.Cli <csv-file>");
return;
}
using var reader = File.OpenText(args[0]);
var imported = CsvImporter.Import(reader);
var result = NpsCalculator.Calculate(
imported.Counts);
Console.WriteLine(
$"Valid responses: {result.Responses}");
Console.WriteLine(
$"Invalid rows: {imported.InvalidRows}");
Console.WriteLine(
$"Promoters: {imported.Counts.Promoters}");
Console.WriteLine(
$"Passives: {imported.Counts.Passives}");
Console.WriteLine(
$"Detractors: {imported.Counts.Detractors}");
Console.WriteLine(
$"NPS: {result.Score?.ToString("F2") ?? "N/A"}");
if (result.Lower95.HasValue &&
result.Upper95.HasValue)
{
Console.WriteLine(
$"95% CI: {result.Lower95.Value:F2} " +
$"to {result.Upper95.Value:F2}");
}
else
{
Console.WriteLine(
"Confidence interval unavailable " +
"under the selected approximation.");
}Save the example CSV as responses.csv and run:
dotnet run --project Nps.Cli -- responses.csvThe expected output is:
Valid responses: 4
Invalid rows: 2
Promoters: 2
Passives: 1
Detractors: 1
NPS: 25.00
Confidence interval unavailable under the selected approximation.I would always display the number of rejected responses alongside the result.
If a customer uploads 10,000 survey records and 2,000 are invalid, the application should make that visible. Otherwise, someone might make a business decision without realising that a significant portion of their data was excluded.
Join the conversation! Your thoughts help the community grow.