---
title: .NET Feature Flags
description: Set up Datadog Feature Flags for .NET applications.
breadcrumbs: Docs > Feature Flags > Server-Side Feature Flags > .NET Feature Flags
---

> For the complete documentation index, see [llms.txt](https://docs.datadoghq.com/llms.txt).

# .NET Feature Flags

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com, us2.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ({% placeholder "user-datadog-site-name" /%}).
{% /alert %}

{% /callout %}

## Overview{% #overview %}

The Datadog .NET SDK receives flag configuration directly from Datadog by default and evaluates flags locally. No Datadog Agent is required. The provider implements [OpenFeature](https://openfeature.dev/).

## Getting started{% #getting-started %}

Install the Datadog .NET tracer 3.57.0 or later with [automatic instrumentation](https://docs.datadoghq.com/tracing/trace_collection/automatic_instrumentation/dd_libraries/dotnet-core.md). Keep the native profiler enabled even if APM tracing is disabled. Installing the OpenFeature provider package alone does not load the tracer.

Create a Boolean flag named `my-flag`. Enable its **Server** distribution channel and enable it in the target environment.

Install the provider, which includes the OpenFeature SDK dependency:

```bash
dotnet add package Datadog.FeatureFlags.OpenFeature --version 2.3.2
```

Set the application API key and flag environment before startup:

```bash
export DD_API_KEY='<DATADOG_API_KEY>'
export DD_ENV='<YOUR_ENVIRONMENT>'
```

If your organization uses a site other than `datadoghq.com`, set `DD_SITE`. For the selected site, use <YOUR_DATADOG_SITE>.

Register the provider and evaluate the flag:

```csharp
using Datadog.FeatureFlags.OpenFeature;
using OpenFeature;

await Api.Instance.SetProviderAsync(new DatadogProvider());
var client = Api.Instance.GetClient();
bool enabled = await client.GetBooleanValueAsync("my-flag", false);
Console.WriteLine(enabled);
```

No Feature Flags enablement or source setting is required for a new setup. Provider initialization starts configuration polling and waits up to 30 seconds for the first configuration. If the wait expires, polling continues and evaluations return default values until configuration arrives. For an existing Agent setup, follow [Migrate an existing Remote Configuration setup](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md#migrate-an-existing-remote-configuration-setup).

With agentless delivery, the SDK sends experiment exposures through a compatible local relay when available. Otherwise, it uses direct HTTPS intake with the application API key. The `feature_flag.evaluations` OTLP metric requires a separate [metrics setup](https://docs.datadoghq.com/feature_flags/guide/server_flag_evaluation_metrics.md). Provider versions through 2.3.2 do not emit aggregated flag evaluation events.

## Use Agent delivery{% #use-agent-delivery %}

To keep Agent delivery, configure a Datadog Agent with [Remote Configuration](https://docs.datadoghq.com/agent/remote_config.md) and an API key. Set this application variable before startup:

```bash
export DD_FEATURE_FLAGS_CONFIGURATION_SOURCE=remote_config
```

Keep automatic instrumentation loaded and register the provider as shown above. See [Server SDK Configuration Sources](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md) for Agent requirements and migration instructions.

## Initialize the SDK{% #initialize-the-sdk %}

Register the Datadog OpenFeature provider with the OpenFeature API. The provider activates the selected configuration source in the Datadog .NET tracer.

### Blocking initialization{% #blocking-initialization %}

Use `SetProviderAsync` with `await` to wait for the initial flag configuration or the initialization timeout. The default timeout is 30 seconds. If the wait expires, polling continues and evaluations return default values until configuration arrives. Verify a known flag's evaluation details before relying on its configured value.

```csharp
using OpenFeature;
using Datadog.FeatureFlags.OpenFeature;

// Create and register the Datadog provider
var provider = new DatadogProvider();
await Api.Instance.SetProviderAsync(provider);

// Create an OpenFeature client
var client = Api.Instance.GetClient("my-service");

// Your application code here
```

### Non-blocking initialization{% #non-blocking-initialization %}

Start `SetProviderAsync` without awaiting it to register the provider in the background. Flag evaluations return default values until the configuration is received.

```csharp
using OpenFeature;
using Datadog.FeatureFlags.OpenFeature;

// Create and register the Datadog provider
var provider = new DatadogProvider();
_ = Api.Instance.SetProviderAsync(provider);

// Create an OpenFeature client
var client = Api.Instance.GetClient("my-service");

// Your application code here
// Flag evaluations return defaults until configuration is received
```

## Create a client{% #create-a-client %}

Create an OpenFeature client to evaluate flags. You can create multiple clients with different names for different parts of your application:

```csharp
// Create a client for your application
var client = Api.Instance.GetClient("my-service");
```

## Set the evaluation context{% #set-the-evaluation-context %}

Define an evaluation context that identifies the user or entity for flag targeting. The evaluation context includes attributes used to determine which flag variations should be returned:

{% alert level="warning" %}
Datadog Feature Flags requires evaluation context attributes to be flat primitive values: strings, numbers, and Booleans. Do not pass nested objects or arrays; they are not supported and can cause exposure data to be dropped.
{% /alert %}

```csharp
using OpenFeature.Model;

var evalCtx = EvaluationContext.Builder()
    .SetTargetingKey("user-123")  // Targeting key (typically user ID)
    .Set("email", "user@example.com")
    .Set("country", "US")
    .Set("tier", "premium")
    .Set("age", 25)
    .Build();
```

**Note:** In server-side applications, build the evaluation context once per request based on the current user, then pass the same context to all flag evaluations within that request. Only rebuild the context if user attributes change.

The targeting key is used for consistent traffic distribution (percentage rollouts). Additional attributes enable targeting rules, such as "enable for users in the US" or "enable for premium tier users" in the example above.

## Evaluate flags{% #evaluate-flags %}

After setting up the provider and creating a client, you can evaluate flags throughout your application. Flag evaluation is local and fast—the SDK uses locally cached configuration data, so no network requests occur during evaluation.

Each flag is identified by a key (a unique string) and can be evaluated with a typed method that returns a value of the expected type. If the flag doesn't exist or cannot be evaluated, the SDK returns the provided default value.

### Boolean flags{% #boolean-flags %}

Use `GetBooleanValueAsync` for flags that represent on/off or true/false conditions:

```csharp
var enabled = await client.GetBooleanValueAsync("new-checkout-flow", false, evalCtx);

if (enabled)
{
    ShowNewCheckout();
}
else
{
    ShowLegacyCheckout();
}
```

### String flags{% #string-flags %}

Use `GetStringValueAsync` for flags that select between multiple variants or configuration strings:

```csharp
var theme = await client.GetStringValueAsync("ui-theme", "light", evalCtx);

switch (theme)
{
    case "dark":
        SetDarkTheme();
        break;
    case "light":
        SetLightTheme();
        break;
    default:
        SetLightTheme();
        break;
}
```

### Numeric flags{% #numeric-flags %}

For numeric flags, use `GetIntegerValueAsync` or `GetDoubleValueAsync`. These are appropriate when a feature depends on a numeric parameter such as a limit, percentage, or multiplier:

```csharp
var maxItems = await client.GetIntegerValueAsync("cart-max-items", 20, evalCtx);

var discountRate = await client.GetDoubleValueAsync("discount-rate", 0.0, evalCtx);
```

### Object flags{% #object-flags %}

For structured data, use `GetObjectValueAsync`. This returns a value that can be used to access complex configuration:

```csharp
using OpenFeature.Model;

var defaultConfig = new Value(new Structure(new Dictionary<string, Value>
{
    ["maxRetries"] = new Value(3),
    ["timeout"] = new Value(30)
}));

var config = await client.GetObjectValueAsync("feature-config", defaultConfig, evalCtx);

// Access configuration values
var maxRetries = config.AsStructure?["maxRetries"].AsInteger ?? 3;
var timeout = config.AsStructure?["timeout"].AsInteger ?? 30;
```

### Flag evaluation details{% #flag-evaluation-details %}

When you need more than just the flag value, use the `*DetailsAsync` methods. These return both the evaluated value and metadata explaining the evaluation:

```csharp
var details = await client.GetBooleanDetailsAsync("new-feature", false, evalCtx);

Console.WriteLine($"Value: {details.Value}");
Console.WriteLine($"Variant: {details.Variant}");
Console.WriteLine($"Reason: {details.Reason}");
Console.WriteLine($"Error Type: {details.ErrorType}");
Console.WriteLine($"Error Message: {details.ErrorMessage}");
```

Flag details help you debug evaluation behavior and understand why a user received a given value.

## Waiting for provider initialization{% #waiting-for-provider-initialization %}

With non-blocking registration, evaluations return default values until the first flag configuration is received. Event handlers can report provider life cycle changes:

```csharp
using OpenFeature;
using Datadog.FeatureFlags.OpenFeature;
using OpenFeature.Constant;

var taskCompletionSource = new TaskCompletionSource<bool>();

// Register event handler
Api.Instance.AddHandler(ProviderEventTypes.ProviderReady, (eventDetails) =>
{
    Console.WriteLine("Provider is ready");
    taskCompletionSource.SetResult(true);
});

Api.Instance.AddHandler(ProviderEventTypes.ProviderError, (eventDetails) =>
{
    Console.WriteLine($"Provider error: {eventDetails.Message}");
    taskCompletionSource.SetResult(false);
});

// Set provider
var provider = new DatadogProvider();
_ = Api.Instance.SetProviderAsync(provider);

// Wait for provider to be ready (with timeout)
var timeout = Task.Delay(TimeSpan.FromSeconds(30));
var completedTask = await Task.WhenAny(taskCompletionSource.Task, timeout);

if (completedTask == timeout)
{
    Console.WriteLine("Provider initialization timed out");
}

// Create client and evaluate flags
var client = Api.Instance.GetClient();
```

Initialization can complete after its timeout while configuration polling continues. A provider-ready event alone does not prove that configuration arrived. Check a known flag's evaluation details and verify that it resolves without `ProviderNotReady`.

## Cleanup{% #cleanup %}

When your application exits, shut down the OpenFeature API to clean up resources:

```csharp
await Api.Instance.ShutdownAsync();
```

## Evaluation events and privacy{% #evaluation-events-and-privacy %}

With tracer 3.56.0 or later and the `agentless` source, experiment exposures prefer a compatible local EVP relay. If no compatible route is available, the tracer can send exposures directly using the application's `DD_API_KEY` and `DD_SITE`. Remote Configuration retains Agent-backed delivery.

Provider versions through `Datadog.FeatureFlags.OpenFeature` 2.3.2 do not emit aggregated EVP flag evaluation events. Experiment exposures and the `feature_flag.evaluations` OTLP metric are separate signals. See [Server-Side Evaluation Events and Privacy](https://docs.datadoghq.com/feature_flags/guide/server_evaluation_events.md) for evaluation-event support in other server SDKs.

## Testing{% #testing %}

You can test against a dedicated Datadog test environment with the real `DatadogProvider`, or swap it for OpenFeature's `InMemoryProvider` to control flag values directly in test code. This section shows the in-memory approach, which keeps tests hermetic and offline. `InMemoryProvider` ships in the `OpenFeature` NuGet package (namespace `OpenFeature.Providers.Memory`), so no additional dependency is required beyond what is already installed for production.

`Api.Instance` is a singleton. Use xUnit's `IAsyncLifetime` to set the provider per test and tear it down in `DisposeAsync`, which avoids ordering-dependent tests. For faster suites that share setup, use `InMemoryProvider.UpdateFlagsAsync(...)` to mutate flag state between tests without re-registering the provider.

```csharp
using OpenFeature;
using OpenFeature.Model;
using OpenFeature.Providers.Memory;
using Xunit;

public class CheckoutFlagTests : IAsyncLifetime
{
    private FeatureClient _client = null!;

    public async Task InitializeAsync()
    {
        var flags = new Dictionary<string, Flag>
        {
            ["new-checkout-flow"] = new Flag<bool>(
                variants: new Dictionary<string, bool> { ["on"] = true, ["off"] = false },
                defaultVariant: "on"),
            ["ui-theme"] = new Flag<string>(
                variants: new Dictionary<string, string> { ["dark"] = "dark", ["light"] = "light" },
                defaultVariant: "light",
                contextEvaluator: ctx =>
                    ctx.GetValue("tier")?.AsString == "premium" ? "dark" : "light"),
        };

        await Api.Instance.SetProviderAsync(new InMemoryProvider(flags));
        _client = Api.Instance.GetClient("test");
    }

    public Task DisposeAsync() => Api.Instance.ShutdownAsync();

    [Fact]
    public async Task NewCheckoutEnabledByDefault()
    {
        Assert.True(await _client.GetBooleanValueAsync("new-checkout-flow", false));
    }

    [Fact]
    public async Task PremiumUserGetsDarkTheme()
    {
        var ctx = EvaluationContext.Builder()
            .SetTargetingKey("u1")
            .Set("tier", "premium")
            .Build();
        Assert.Equal("dark", await _client.GetStringValueAsync("ui-theme", "light", ctx));
    }
}
```

The same pattern applies to NUnit (`[SetUp]`/`[TearDown]`) and MSTest (`[TestInitialize]`/`[TestCleanup]`). For ASP.NET Core integration tests, register the `InMemoryProvider` inside `WebApplicationFactory.ConfigureTestServices` before the application boots.

To avoid coupling tests to SDK internals, prefer swapping in `InMemoryProvider` over mocking the Datadog provider with Moq or similar libraries.

## Troubleshooting{% #troubleshooting %}

### Agentless delivery not working{% #agentless-delivery-not-working %}

- Verify that tracer 3.57.0 or later is loaded and the OpenFeature provider is initialized.
- Check `DD_API_KEY`, `DD_SITE`, and `DD_ENV` in the application process.
- Confirm `DD_FEATURE_FLAGS_ENABLED` is not `false`. Leave `DD_FEATURE_FLAGS_CONFIGURATION_SOURCE` unset for a new setup, or explicitly set it to `agentless`. Remove the legacy `DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED` setting when migrating.
- Allow outbound HTTPS to `ufc-server.ff-cdn.<DD_SITE>`.
- Enable `DD_TRACE_DEBUG=true` and check tracer logs for authentication, timeout, or malformed configuration errors.

Before the first valid configuration, evaluations return caller defaults. After successful initialization, transient delivery failures retain the last valid configuration.

### Remote Configuration not working{% #remote-configuration-not-working %}

Verify the following to ensure that Remote Configuration is working:

- Datadog Agent is version 7.55 or later. See [Server SDK Configuration Sources](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md).
- Remote Configuration is enabled on the Agent
- `DD_SERVICE` and `DD_ENV` environment variables are set
- The SDK can communicate with the Agent
- The Agent was available when the application started. If problems continue after the Agent becomes available, restart the application. See [Agent availability](https://docs.datadoghq.com/feature_flags/concepts/configuration_sources.md#agent-availability).

### Async evaluation errors{% #async-evaluation-errors %}

The .NET OpenFeature SDK uses async methods for all flag evaluations. Ensure you're using `await` or properly handling the returned `Task`:

```csharp
// Correct: Using await
var enabled = await client.GetBooleanValueAsync("flag-key", false, context);

// Incorrect: Not awaiting (will not work as expected)
var enabled = client.GetBooleanValueAsync("flag-key", false, context);
```

## Further reading{% #further-reading %}

Additional helpful documentation, links, and articles:

- [Server-Side Feature Flags](https://docs.datadoghq.com/feature_flags/server.md)
- [.NET Tracing](https://docs.datadoghq.com/tracing/trace_collection/dd_libraries/dotnet-core.md)
- [Set Up Server-Side Flag Evaluation Metrics](https://docs.datadoghq.com/feature_flags/guide/server_flag_evaluation_metrics.md)
- [Set Up APM Trace Enrichment for Feature Flags](https://docs.datadoghq.com/feature_flags/guide/apm_trace_enrichment.md)
- [Feature Flag Graphs](https://docs.datadoghq.com/feature_flags/concepts/flag_graphs.md)
