Dev guideAPI Reference
Dev guideAPI ReferenceUser GuideGitHubNuGetDev CommunityDoc feedbackLog In
GitHubNuGetDev CommunityDoc feedback

Initialize the C# SDK

Lists the steps required to initialize the Optimizely Feature Experimentation C# SDK in your application.

Use the builder to initialize the C# SDK and instantiate an instance of the Optimizely Feature Experimentation client class that exposes API methods like the Decide methods.


SDK v3.2.0 and higher


The constructor accepts a configuration object to configure Optimizely Feature Experimentation.

The SDK provides a default implementation, but you may want to override the optional parameters for your production environments. For example, you can override these to set up an error handler and logger to catch issues, an event dispatcher to manage network calls, and a User Profile Service to ensure sticky bucketing.


The table lists the required and optional parameters for initializing the C# SDK:

stringThe JSON string representing the project.
ProjectConfigManagerThe project config manager provides the project config to the client.
IEventDispatcherAn event handler to manage network calls.
ILoggerA logger implementation to log issues.
IErrorHandlerAn error handler object to handle errors.
UserProfileServiceA user profile service.
booleanSpecifies whether the JSON should be validated. Set to true to skip JSON validation on the schema, or false to perform validation.
string(Server-side only) An access token for Optimizely Feature Experimentation SDKs (in combination with an SDK key) to fetch the datafile from an authenticated endpoint. Find your datafile access token in the Optimizely app at Settings > Environments. Select your secure environment, and copy the Datafile access token.
Array"Array of OptimizelyDecideOption enums. This parameter sets default decide options applied to all the Decide calls made during the lifetime of the Optimizely client. Additionally, you can pass options to individual Decide methods (does not override defaults).

For details on decide options, see OptimizelyDecideOption."


Instantiates an instance of the Optimzely class.

Automatic datafile management (ADM)

Optimizely Feature Experimentation provides out-of-the-box functionality to dynamically manage datafiles (configuration files) on either the client or the server. The C# SDK provides default implementations of an Optimizely ProjectConfigManager. The package also includes a factory class, OptimizelyFactory, which you can use to instantiate the Optimizely Feature Experimentation SDK with the default configuration of HttpProjectConfigManager.

Whenever the experiment configuration changes, the SDK uses automatic datafile management (ADM) to handle the change for you. In the C# SDK, you can provide either sdkKey or datafile or both.

  • When initializing with just the SDK key, the SDK polls for datafile changes in the background at regular intervals.
  • When initializing with just the datafile, the SDK does not poll for datafile changes in the background.
  • When initializing with both the SDK key and datafile, the SDK uses the given datafile and start polling for datafile changes in the background.

Basic example

The following code example shows basic C# ADM usage.

using OptimizelySDK;

public class Program
    public static void Main(string[] args)
       var sdkKey = args[0];
     	 var optimizely = OptimizelyFactory.NewDefaultInstance(sdkKey);

Advanced examples



When you configure a logger, you should pass it into the ProjectConfigManager instance as well.

In the C# SDK, you only need to pass the SDK key value to instantiate a client. Whenever the experiment configuration changes, the SDK handles the change for you.

Include sdkKey as a string property in the options object you pass to the CreateInstance method.

When you provide the sdkKey, the SDK instance downloads the datafile associated with that sdkKey. When the download completes, the SDK instance updates itself to use the downloaded datafile.



Pass all components (Logger, ErrorHandler, NotificationCenter) to the Optimizely Feature Experimentation constructor. Not passing a component fails to enable its respective functionality. In other words, components only work when passed to the constructor.

// Initialize with SDK key and default configuration
const string sdkKey = "YOUR_SDK_KEY"; // replace with your SDK Key
var optimizely = OptimizelyFactory.NewDefaultInstance(sdkKey);

// You can also customize the SDK instance with custom configuration. 
// In this example we are customizing the project config manager to poll every 5 minutes for the datafile.
var projectConfigManager = new HttpProjectConfigManager.Builder()
  // .WithLogger(logger) // needed if you are configuring a logger
  // .WithErrorHandler(errorHandler) // needed if you are configuring an error handler
  // .WithNotificationCenter(notificationCenter) // needed if you are subscribing config update

optimizely = new Optimizely(projectConfigManager);

// Initialize with Logger
optimizely = new Optimizely(projectConfigManager, logger: logger);

// Initialize with Logger, ErrorHandler
optimizely = new Optimizely(projectConfigManager, errorHandler: errorHandler, logger: logger);

// Initialize with NotificationCenter, Logger, ErrorHandler
optimizely = new Optimizely(projectConfigManager, notificationCenter: notificationCenter, errorHandler: errorHandler, logger: logger);

// Note: Use OptimizelyFactory NewDefaultInstance method to use same logger, errorHandler and notificationCenter for all of its Components (Optimizely, EventProcessor, HttpProjectConfigManager)    

Here is a code example showing advanced configuration for C# ADM. The following sections describe advanced configuration properties. This advanced example shows how to construct the individual components directly to override various configurations. This gives you full control over which implementations to use and how to use them.

using OptimizelySDK;
using OptimizelySDK.Config;

public class Program
    public static void Main(string[] args)
      var sdkKey = args[0];
      // You can also use your own implementation of the ProjectConfigManager interface
      var projectConfigManager = new HttpProjectConfigManager.Builder()
      var optimizely = new Optimizely(projectConfigManager);


HttpProjectConfigManager is an implementation of the abstract PollingProjectConfigManager. The Poll method is extended and makes an HTTP GET request to the configured URL to asynchronously download the project datafile and initialize an instance of the ProjectConfig.

By default, HttpProjectConfigManager blocks until the first successful datafile retrieval, up to a configurable timeout. Set the frequency of the polling method and the blocking timeout with HttpProjectConfigManager.Builder.

var projectConfigManager = new HttpProjectConfigManager.Builder()

SDK key

The SDK key composes the outbound HTTP request to the default datafile location on the Optimizely CDN.

Polling interval

The polling interval specifies a fixed delay between consecutive HTTP requests for the datafile, using any range supported by Timespan.

Initial datafile

You can provide an initial datafile via the builder to bootstrap the ProjectConfigManager, letting you use it immediately without blocking execution. The initial datafile also serves as a fallback datafile if HTTP connection cannot be established. This is useful in mobile environments, where internet connectivity is not guaranteed.

The SDK discards the initial datafile after the first successful datafile poll.

Builder methods

Use the following builder methods to customize the HttpProjectConfigManager configuration.

PropertyDefault valueDescription
WithDatafile(string)nullInitial datafile, typically sourced from a local cached source
WithUrl(string)nullURL override location used to specify custom HTTP source for the Optimizely datafile
WithFormat(string)nullParameterized datafile URL by SDK key
WithPollingInterval(TimeSpan)5 minutesFixed delay between fetches for the datafile
WithBlockingTimeoutPeriod(TimeSpan)15 secondsMaximum time to wait for initial bootstrapping. The valid timeout duration is 1 to 4294967294 milliseconds.
WithSdkKey(string)nullOptimizely Feature Experimentation project SDK key; required unless source URL is overridden

Update config notifications

The SDK triggers a notification signal after fetching a new datatfile. To subscribe to these notifications, use method NotificationCenter.AddNotification().

    () => Console.WriteLine("Received new datafile configuration")


OptimizelyFactory provides basic utility to instantiate the Optimizely Feature Experimentation SDK with a minimal number of configuration options.

OptimizelyFactory does not capture all configuration and initialization options. For more use cases, build the resources with their constructors.

You must provide the SDK key at runtime, directly via the factory method:

var optimizely = OptimizelyFactory.NewDefaultInstance("YOUR_SDK_KEY");

Instantiate using datafile

You can also instantiate with a hard-coded datafile. If you do not pass in an SDK key, the Optimizely Client does not automatically sync newer versions of the datafile. Any time you retrieve an updated datafile, just re-instantiate the same client.

For simple applications, all you need to provide to instantiate a client is a datafile specifying the project configuration for a given environment. For most advanced implementations, you should customize the logger or error handler for your specific requirements.

using OptimizelySDK;

// Instantiate an Optimizely client
var optimizely = new Optimizely(datafile);

Use authenticated datafile in secure environment

You can fetch the datafile from an authenticated endpoint using a server-side (only) Optimizely Feature Experimentation SDK, like the C# SDK.

To use an authenticated datafile, download your environment's access token from the Optimizely app at Settings>Environments. Select your secure environment, and copy the Datafile access token. The example below shows how to initialize the Optimizely client using an access token and sdk_key, enabling the client to fetch the authenticated datafile and complete initialization.

// fetch the datafile from an authenticated endpoint
var datafileAccessToken = "YOUR_DATAFILE_ACCESS_TOKEN";
var sdkKey = "YOUR_SDK_KEY";
var optimizely = OptimizelyFactory.NewDefaultInstance(sdkKey, null, datafileAccessToken);

Source files

The language and platform source files containing the implementation for C# are available on GitHub.