# Legacy .NET Server SDK

## Setup the SDK

{% steps %}
{% step title="Install the SDK" %}
The package is hosted on [Nuget](https://www.nuget.org/packages/Statsig/). Install it through Visual Studio's Nuget package manager or through the NuGet CLI:

```bash
nuget install Statsig
```
{% /step %}

{% step title="Initialize the SDK" %}
After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys).

{% callout type="warning" %}
Don't embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. If you accidentally expose it, you can create a new one in the Statsig console.
{% /callout %}

```csharp
using Statsig;
using Statsig.Server;

await StatsigServer.Initialize(
    "server-secret-key",
    // optionally customize the SDKs configuration via StatsigOptions
    new StatsigOptions(
        environment: new StatsigEnvironment(EnvironmentTier.Development)
    )
);
```

`initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independently of API calls.
{% /step %}
{% /steps %}

## Working with the SDK

## Checking a Feature Flag/Gate

After you initialize the SDK, you can check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default.

All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user:

```csharp
var user = new StatsigUser { UserID = "some_user_id", Email = "user@email.com" };
var useNewFeature = await StatsigServer.CheckGate(user, "use_new_feature");
if (useNewFeature)
{
  // Gate is on, enable new feature
}
else
{
  // Gate is off
}
```

## Reading a Dynamic Config

Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters.

```csharp
var config = await StatsigServer.GetConfig(user, "awesome_product_details");
var itemName = config.Get<string>("product_name", "Awesome Product v1");
var price = config.Get<double>("price", 10.0);
```

## Getting a Layer/Experiment

Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) for faster iterations with parameter reuse.

```csharp
// Values via GetLayer
var layer = await StatsigServer.GetLayer(user, "user_promo_experiments");
var title = layer.Get<string>("title", "Welcome to Statsig!");
var discount = layer.Get<double>("discount", 0.1);

// or, via GetExperiment
var experiment = await StatsigServer.GetExperiment(user, "new_user_promo");
var expTitle = experiment.Get<string>("title", "Welcome to Statsig!");
var expDiscount = experiment.Get<double>("discount", 0.1);

var price = msrp * (1 - discount);
```

## Logging an Event

To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object:

```csharp
StatsigServer.LogEvent(user, "add_to_cart", "SKU_12345", 
    new Dictionary<string, string> {
        { "price", "9.99" },
        { "item_name", "diet_coke_48_pack" }
    });
```

For more about identifying users, group analytics, and best practices, go to the [logging events guide](https://docs.statsig.com/guides/logging-events).

## Statsig User

When calling APIs that require a user, pass as much information as possible. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to [userID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail.

In addition to `userID`, the top-level fields on StatsigUser are `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them.

Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's no operator to match a value within that array.

### Private Attributes

To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. The SDK uses any attribute set in `privateAttributes` only for evaluation/targeting and removes it from all logs before Statsig sends them to its servers.

For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user.

## Shutdown

To gracefully shutdown the SDK and flush all events:

```csharp
await StatsigServer.Shutdown();
```
