Example usage of the C# SDK
1 min
After installing the C# SDK, import the Optimizely library, get your project's datafile, and create a client. Use the client to evaluate flag rules like A/B tests and flag deliveries.
This example walks through the following three key steps:
- Evaluate a flag with the key product_sort using the Decide method. This also sends a decision event to Optimizely to record that the user was exposed to the experiment.
- Run code based on the flag result. The SDK evaluates your flag rules and determines which variation the user is in. You can either:
- Check the flag's enabled state and read a configuration variable (sort_method) to determine which experience the user gets.
- Check the flag variation directly and run the corresponding control or treatment code.
- Track a conversion event called purchased to measure the experiment's impact. The TrackEvent method ties the purchase back to the A/B test and sends it to Optimizely so it displays on your Experiment Results page.
//Import Optimizely SDK
using OptimizelySDK;
using OptimizelySDK.Entity;
// Instantiate an Optimizely client
var optimizely = OptimizelyFactory.NewDefaultInstance("YOUR_SDK_KEY");
// Set custom user attributes
var attributes = new UserAttributes
{
{ "logged_in", true }
};
// Create a user context
var user = optimizely.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");