skip to content

In ASP.NET Core, what do IConfiguration's indexer, GetSection, GetValue<T> and GetConnectionString return when a key is missing or cannot be converted?

level: middleimportance: should knowfreq 52%

answer

  1. everything is a string underneath
  2. GetSection never returns null
  3. Exists() or GetRequiredSection
  4. GetValue<T>: default(T) or InvalidOperationException
  5. GetConnectionString: null when unset

basics

~20 s

The indexer and GetConnectionString return null for a missing key; GetSection returns an empty section, never null; GetValue<T> returns default(T) or the supplied default, and throws InvalidOperationException when the string cannot be converted to T.

solid answer

~40 s

Configuration is a flat set of string values addressed by colon paths. `configuration["Features:OnlineApplications"]` returns the string or `null`. `GetSection("Features")` always returns an `IConfigurationSection`; for an unknown path it is empty, so test it with `Exists()` or use `GetRequiredSection`, which throws `InvalidOperationException`. `GetValue<int>("Shelter:MaxActiveApplications", 5)` converts the string with a type converter: a missing key gives the default you passed (or `default(T)`, so `0` or `false`), while a present value like `"ten"` throws `InvalidOperationException` ("Failed to convert configuration value..."). `GetConnectionString("Adoptions")` is `GetSection("ConnectionStrings")["Adoptions"]` and returns `null` when unset. The trap is silent defaults: a typo in a key reads as `false` or `0`, so fail fast on values that must exist.

code

json · 6 lines
json
{
  "Shelter": {
    "Name": "Riverside",
    "MaxActiveApplications": "ten"
  }
}

go deeper

for a junior

Know that config["A:B"] returns a string or null and that GetConnectionString reads the ConnectionStrings section.

for a middle

Explain the table of missing versus unconvertible behaviour for each API, and why GetSection returning an empty section hides typos.

for a senior

Turn silent defaults into startup failures for anything required, and keep raw reads to Program.cs while groups of settings go into validated options.

for a principal

Set a rule for the codebase on which settings may be read raw and which must be typed and validated, so configuration errors surface at deploy time.

## The model underneath `IConfiguration` is a view over **string keys and string values**. Every provider flattens its input into paths such as `Shelter:MaxActiveApplications` or `ConnectionStrings:Adoptions`, and keys compare case-insensitively. Each read API differs in what it does with a missing key and how it converts the string. ## The four read APIs | API | Returns when present | Returns when missing | On a bad value | |---|---|---|---| | `config["Shelter:Name"]` | the string | `null` | no conversion, so no error | | `config.GetSection("Shelter")` | a section with children | an **empty section, never null** | not applicable | | `config.GetValue<int>("Shelter:MaxActiveApplications")` | the converted value | `default(T)` (`0`) | `InvalidOperationException` | | `config.GetValue("Shelter:MaxActiveApplications", 5)` | the converted value | the supplied default (`5`) | `InvalidOperationException` | | `config.GetConnectionString("Adoptions")` | the string | `null` | no conversion | Two neighbours complete the set: - `section.Exists()` is true when the section has a value or any children. - `config.GetRequiredSection("Shelter")` returns the section or throws `InvalidOperationException` when it does not exist. ## Sections `GetSection` is a cursor, not a lookup. It returns an `IConfigurationSection` whose `Key` is the last segment, whose `Path` is the full path, and whose `Value` is the string at that path (or `null` when the path is an object). Reading through it is the same as prefixing the path: ```csharp IConfigurationSection shelter = builder.Configuration.GetSection("Shelter"); string? name = shelter["Name"]; // same as config["Shelter:Name"] foreach (var child in shelter.GetChildren()) // enumerate keys under Shelter Console.WriteLine($"{child.Path} = {child.Value}"); ``` Because an unknown section is empty rather than null, `if (config.GetSection("Shelterr") == null)` never fires. That is the most common read-API bug: a misspelt section produces nothing but defaults. ## Conversion in GetValue `GetValue<T>` takes the string and converts it with the type's `TypeConverter`, using the invariant culture. Consequences: 1. `"true"`, `"True"` and `"false"` convert to `bool`; `"yes"` does not. 2. Numbers use invariant formatting, so `"2.5"` converts to `double` on any server locale. 3. A conversion failure is wrapped in `InvalidOperationException` with the message `Failed to convert configuration value '...' at '...' to type '...'`, carrying the key path. 4. A missing key is not a failure: it returns the default, which is why `GetValue<bool>("Features:OnlineApplication")`, missing an `s`, quietly returns `false`. ## Connection strings `GetConnectionString` performs no validation and no conversion. It returns the merged value of `ConnectionStrings:{name}`, wherever it came from, or `null`. Passing that `null` straight into a database provider defers the failure to the first query; throwing at startup is clearer: ```csharp var cs = builder.Configuration.GetConnectionString("Adoptions") ?? throw new InvalidOperationException("Missing ConnectionStrings:Adoptions"); ``` ## Enumerating sections and arrays An array in JSON becomes numbered child keys, so reading one by hand means walking children: - `config.GetSection("Shelters").GetChildren()` yields sections with keys `0`, `1`, `2`, in key order. - `config.GetSection("Shelters:1").Value` reads a single element. - `config.AsEnumerable()` flattens the whole tree into path and value pairs, useful in a quick diagnostic. Children are merged across providers, so the list you enumerate already reflects every override, including the array-by-index merge between files. ## Raw reads versus typed settings Raw reads are right for a handful of values read once in `Program.cs`: a connection string, a feature switch, a port. When a group of settings is used across the app, binding the section into a class with the options pattern gives one validated object instead of string paths scattered through the code; that is a separate topic. ## Interview checklist - The indexer and `GetConnectionString` return `null`; `GetSection` never does. - `Exists()` and `GetRequiredSection` are how you detect a missing section. - `GetValue<T>` defaults on missing, throws `InvalidOperationException` on unconvertible. - Typos read as defaults, so validate required values at startup.

  • How would you make a misspelt or missing section fail at startup instead of silently reading defaults?
    Use `GetRequiredSection("Shelter")`, which throws `InvalidOperationException` when the section does not exist, or check `Exists()` and throw yourself. For a group of settings, bind them into an options class and validate it at startup.
  • What is the difference between GetSection("Shelter").Value and GetSection("Shelter")["Name"]?
    `Value` is the string stored at the path `Shelter` itself, which is `null` when `Shelter` is an object with children. The indexer on the section reads a child path, `Shelter:Name`, and returns that string or `null`.

  • GetSection returns null when the section is not in any configuration file.
  • GetValue<int> throws when the key is missing from configuration.
  • GetConnectionString throws KeyNotFoundException for an unknown name.
  • GetValue<bool> returns false when the stored string cannot be parsed.
  • Configuration keys are case-sensitive, so the casing must match the JSON exactly.