Powerful feature flagging and A/B testing for C# apps using GrowthBook
This library is based on the GrowthBook SDK specs and should be compatible with the usage examples in the GrowthBook docs. For a more complete set of examples involving usage within ASP.Net Core, take a look at the C# examples in the GrowthBook examples repository.
Down below you'll find two basic examples on how the package works.
-
Install GrowthBook
dotnet add package growthbook-c-sharp
-
Declare features
var staticFeatures = new Dictionary<string, Feature> { {"firstFeature", new Feature{ DefaultValue = true}}, {"secondFeature", new Feature{ DefaultValue = false}} };
-
Create a context and add the features
var context = new Context { Enabled = true, Url = "", Features = staticFeatures };
-
Create the
GrowthBook
object with the contextusing GrowthBook; //... var GrowthBook = new GrowthBook.GrowthBook(context);
-
Check whether a feature is enabled
GrowthBook.IsOn("firstFeature") // true GrowthBook.IsOn("secondFeature") // false
Because feature definitions are typically loaded from API calls or cache, Json.NET objects are used to represent arbitrary document types such as Attributes, Conditions, and Feature values.
To load your features from the GrowthBook API use the following example:
-
Create a result model for the API response
public class FeaturesResult { public HttpStatusCode Status { get; set; } public IDictionary<string, Feature>? Features { get; set; } public DateTimeOffset? DateUpdated { get; set; } }
-
call the endpoint and deserialize result
var url = "YOUR_GROWTHBOOK_URL/api/features/YOUR_API_KEY"; var response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); var featuresResult = JsonConvert.DeserializeObject<FeaturesResult>(content); }
-
Construct a context and initialize GrowthBook
var GrowthBook = new GrowthBook.GrowthBook( new Context { Enabled = true, Url = "", Features = featuresResult.Features, } );
To make it easier to deal with Feature values, generic getter functions are provided for the following:
- Experiment:
GetVariations<T>()
- ExperimentResult:
GetValue<T>()
- Feature:
GetDefaultValue<T>()
- FeatureResult:
GetValue<T>()
- Feature Rule:
GetVariations<T>()
- GrowthBook:
GetFeatureValue<T>(string key, T fallback)