GuidesAPI Reference
Submit Documentation FeedbackJoin Developer CommunityLog In

Example usage

Once you've installed an SDK, import the Optimizely library into your code, get your Optimizely project's datafile, and instantiate a client. Then, you can use the client to evaluate flag rules, including A/B tests and flag deliveries.

This example demonstrates the basic usage of each of these concepts:

  1. Evaluate a flag with the key product_sort using the Decide method. As a side effect, the Decide function also sends a decision event to Optimizely to record that the current user has been exposed to the experiment.

  2. Conditionally execute your feature code. You have a couple of options:

  • Fetch the flag enabled state, then check a configuration variable on the flag called sort_method. The SDK evaluates your flag rules and determines what flag variation the user is in, and therefore which sort method variable they should see.
  • Fetch on the flag variation, then run 'control' or 'treatment' code.
  1. Use event tracking to track an event called purchased. This conversion event measures the impact of an experiment. Using the Track Event method, the purchase is automatically attributed back to the running A/B test for which we made a decision, and the SDK sends a network request to Optimizely via the customizable event dispatcher so we can count it in your Results page.
//Import Optimizely SDK
using OptimizelySDK;
using OptimizelySDK.Entity;

// Instantiate an Optimizely client
 var optimizelyInstance = OptimizelyFactory.NewDefaultInstance("<YOUR SDK KEY>");
var attributes = new UserAttributes();
attributes.Add("logged_in", true);

// Create a user context
var user = optimizelyInstance.CreateUserContext("user123", attributes);

var decision = user.Decide("product_sort");

// Execute code based on decision's variation key
if (string.IsNullOrEmpty(decision.VariationKey)) {
    Console.WriteLine("decision error: " + string.Join(" ", decision.Reasons));
} else if (decision.VariationKey == "control") {
    Console.WriteLine("control variation");
} else if (decision.VariationKey == "treatment") {
    Console.WriteLine("treatment variation");
} else {
    // Unknown variation
}

// Execute code based on flag enabled state
if (decision.Enabled) {
    var sortMethod = decision.Variables.ToDictionary()["sort_method"];
    Console.WriteLine("sort_method: ", sortMethod);
}

// Track an event
user.TrackEvent("purchased");

Did this page help you?