C# / .NET · Gender prediction
Predict gender from names in C# with .NET 8
Gender responses use snake_case fields such as result_status and confidence_kind, while C# properties are PascalCase. .NET 8 added JsonNamingPolicy.SnakeCaseLower, so a single JsonSerializerOptions instance maps the GenderPrediction record in both directions without attributes. The example sends each name with a country code, because names like Andrea and Kim lean differently between countries, then prints either the gender with its confidence or the reason the result is unknown.
Gender and Confidence are nullable on purpose. When result_status is unknown, gender is null and reason explains why, for example not_found or insufficient_evidence. The PredictAsync helper retries a 429 only when the response carries a Retry-After delta, and maps 400, 401 and an exhausted quota to distinct exceptions using a switch expression. For bulk enrichment, post up to 50 items to /v1/gender/batch instead.
Steps
- 1
Paste the example into Program.cs and export FINOWL_API_KEY.
- 2
Keep one JsonSerializerOptions instance with SnakeCaseLower and reuse it for every gender call.
- 3
Pass the ISO 3166-1 alpha-2 country code from your customer record when you have one.
- 4
Check ResultStatus before reading Gender, and store unknown results along with their reason.
- 5
Switch to the batch endpoint when you enrich records in a background job.
dotnet new console -n FinowlQuickstart
cd FinowlQuickstartusing System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
// Finowl gender fields are snake_case (result_status, confidence_kind...).
var json = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
using var http = new HttpClient
{
BaseAddress = new Uri("https://api.finowl.co"),
Timeout = TimeSpan.FromSeconds(15),
};
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
Environment.GetEnvironmentVariable("FINOWL_API_KEY") ?? throw new InvalidOperationException("Set FINOWL_API_KEY."));
foreach (var (name, country) in new[] { ("Andrea", "IT"), ("Andrea", "US"), ("Kim", "KR") })
{
var prediction = await PredictAsync(name, country);
Console.WriteLine(prediction.ResultStatus == "unknown"
? $"{name}/{country}: unknown ({prediction.Reason})"
: $"{name}/{country}: {prediction.Gender} {prediction.Confidence:P0} via {prediction.Source}");
}
async Task<GenderPrediction> PredictAsync(string name, string country)
{
while (true)
{
using var response = await http.PostAsJsonAsync("/v1/gender/name", new { name, country }, json);
if (response.IsSuccessStatusCode)
return (await response.Content.ReadFromJsonAsync<GenderEnvelope>(json))!.Data;
if (response.StatusCode == HttpStatusCode.TooManyRequests && response.Headers.RetryAfter?.Delta is { } wait)
{
await Task.Delay(wait); // rate_limited: safe to retry after the header value
continue;
}
throw response.StatusCode switch
{
HttpStatusCode.BadRequest => new ArgumentException($"Invalid name or country code: {name}, {country}"),
HttpStatusCode.Unauthorized => new InvalidOperationException("FINOWL_API_KEY was rejected."),
HttpStatusCode.TooManyRequests => new InvalidOperationException("Out of Finowl credits (quota_exceeded)."),
_ => new HttpRequestException($"Finowl returned {(int)response.StatusCode}."),
};
}
}
record GenderEnvelope(GenderPrediction Data);
record GenderPrediction(
string ResultStatus, string? Gender, double? Confidence, string? ConfidenceKind,
int? SampleCount, string? Source, string? Reason);IN PRODUCTION
Production tips
Cache JsonSerializerOptions in a static field. Creating a new instance per call throws away the metadata cache System.Text.Json builds, which adds measurable overhead under load.
Use predictions for dashboards and segment-level analysis. They estimate how a name is typically used, not how a person identifies, so never feed them into pricing, eligibility or access decisions.
Requesting AI with ai_mode always or forceToGenderize costs 3 credits per lookup instead of 1, so reserve it for handles and nicknames that the dataset cannot resolve.
Each lookup costs 1 credit (3 when it requests AI), with 100 free credits every month. See pricing and error codes.
A FEW GOOD QUESTIONS
Common questions
Related guides
- Check email breaches in C# with HttpClient
- Check breached passwords in C# and .NET 8
- Predict gender from names in Python
- Predict gender from a name in Node.js
- Batch gender prediction in TypeScript
- Predict gender from names in Go with net/http
- Gender analytics from names for fintech audiences
- Gender insights from names for e-commerce analytics
- Gender estimates for SaaS user research and analytics
Predict gender from names in C# with .NET 8
Grab an API key, paste the example and run it. 100 free credits every month.