In C#, why does typeof(DeployOptions).GetProperty("verbose") return null for a public Verbose property, and which BindingFlags fix it?
answer
- name matching rules
- two axes every search needs
- what the parameterless overload passes
- IgnoreCase is not enough alone
basics
~10 sReflection matches member names case-sensitively, so "verbose" misses Verbose. Passing BindingFlags.IgnoreCase alone finds nothing either; the fix is Instance | Public | IgnoreCase.
solid answer
~30 s`GetProperty(string)` matches the name case-sensitively and returns `null` when nothing matches, so `"verbose"` misses `Verbose`. Adding only `BindingFlags.IgnoreCase` still returns `null`: a flags overload needs one of `Instance` or `Static` *and* one of `Public` or `NonPublic`, or nothing matches. The working lookup is `Instance | Public | IgnoreCase`. The parameterless overloads use `Public | Instance | Static`, so `GetProperties()` includes declared public static properties and inherited public instance ones, but no private members (`NonPublic`) and no base-class statics (`FlattenHierarchy`). Once found, `SetValue` can call even a private setter.
code
csharp · 30 lines#:property PublishAot=false
using System.Reflection;
Type t = typeof(DeployOptions);
Console.WriteLine(string.Join(", ", t.GetProperties().Select(p => p.Name)));
// Verbose, RunId, DefaultRegion, Environment
Console.WriteLine(t.GetProperty("verbose") is null); // True
Console.WriteLine(t.GetProperty("verbose", BindingFlags.IgnoreCase) is null); // True
var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase;
PropertyInfo verbose = t.GetProperty("verbose", flags)!; // found
Console.WriteLine(string.Join(", ", t.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic).Select(p => p.Name)));
// Token
Console.WriteLine(string.Join(", ", t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy).Select(p => p.Name)));
// DefaultRegion, RetryLimit
var o = new DeployOptions();
verbose.SetValue(o, true);
t.GetProperty("RunId")!.SetValue(o, "r-7"); // private setter: still works
Console.WriteLine($"{o.Verbose} {o.RunId}"); // True r-7
class OptionsBase { public string Environment { get; set; } = "dev"; public static int RetryLimit { get; set; } = 3; }
class DeployOptions : OptionsBase
{
public bool Verbose { get; set; }
public string RunId { get; private set; } = "";
private string Token { get; set; } = "";
public static string DefaultRegion { get; set; } = "eu";
}go deeper
Remember that reflection matches names case-sensitively and returns null for a miss, and that BindingFlags controls which members a lookup can see.
Explain the two axes a flags overload needs, the Public | Instance | Static default of the parameterless overloads, and what NonPublic, DeclaredOnly and FlattenHierarchy each change.
Show the production version: a binder that caches PropertyInfo per type, filters out statics and get-only properties, converts strings to PropertyType and detects case-insensitive collisions at startup.
Weigh reaching NonPublic members by design against the coupling it creates to another type's internals, and set a rule for when reflection over private members is acceptable.
## What a reflective lookup searches `Type.GetProperty`, `GetProperties`, `GetMethod`, `GetMethods`, `GetFields` and `GetMember` all filter members with a `BindingFlags` value. `BindingFlags` is a `[Flags]` enum, so you combine values with `|`. For *finding* members, the important values are: | Flag | Effect on the search | |---|---| | `Instance` | include instance members | | `Static` | include static members | | `Public` | include public members | | `NonPublic` | include private, protected and internal members | | `IgnoreCase` | match the name without regard to case | | `DeclaredOnly` | skip members inherited from base classes | | `FlattenHierarchy` | also return public and protected **static** members of base classes | The rule that trips people up: a flags overload finds nothing unless the flags name **at least one of `Instance` or `Static` and at least one of `Public` or `NonPublic`**. Those two pairs are the axes of the search, and an empty axis matches no member. ## Why `GetProperty("verbose")` returns null The CLI tool in this scenario parses `--verbose` and looks up a property called `"verbose"` on its options class. Two separate things defeat the naive lookup. 1. **Names are case-sensitive by default.** `GetProperty("verbose")` does not match `Verbose`, so it returns `null` (lookups by name return `null` for "not found"; they do not throw). 2. **`IgnoreCase` alone is an empty search.** `GetProperty("verbose", BindingFlags.IgnoreCase)` also returns `null`, because neither axis is named. The fix spells out the whole search: `BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase`. If two properties differed only by case, a case-insensitive `GetProperty` would have two candidates and throw `AmbiguousMatchException`. ## What the parameterless overloads use The overloads without a `BindingFlags` argument (`GetProperties()`, `GetProperty(string)`, `GetMethods()`, `GetFields()` and the rest) pass a default of **`Public | Instance | Static`**. The .NET 10 source declares it as `DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public` in `Type.cs`. So `GetProperties()`: - returns public instance properties, **inherited ones included**, such as `Environment` from the base class; - returns public static properties **declared on the type itself**, such as `DefaultRegion`, which is easy to forget when you copy options onto "every property"; - does **not** return private or protected properties, such as `Token`, until you add `NonPublic`; - does **not** return public static properties of base classes, such as `RetryLimit`, until you add `FlattenHierarchy`. `DeclaredOnly` goes the other way: `Instance | Public | DeclaredOnly` drops `Environment` and keeps only what `DeployOptions` itself declares. ## Reading and writing once you have the `PropertyInfo` Finding a property and setting it are separate steps, with separate failure modes. - `PropertyInfo.SetValue(target, value)` calls the property's setter. A **private setter still works** through reflection, so `RunId { get; private set; }` can be set. Visibility filters only control what the search *returns*. - A get-only property such as `int Computed => 1` has no setter: `CanWrite` is `false` and `SetValue` throws `ArgumentException`. - A value of the wrong type (a `string` for a `bool` property) also throws `ArgumentException`. Reflection does not convert `"true"` to `true` for you, so a binder parses strings to the property's `PropertyType` before setting. - A binder that copies options should usually skip static properties, so it either filters on `Instance` explicitly or checks the accessor. ## The same rules for methods and fields `GetMethods()`, `GetFields()` and `GetMember()` follow the same flags and the same default. Two results surprise people the first time: - `typeof(DeployOptions).GetMethods()` lists `get_Verbose` and `set_Verbose`, the compiler-generated accessor methods behind the property, alongside your own methods. - It also lists `GetType`, `ToString`, `Equals` and `GetHashCode`, public instance methods inherited from `System.Object`. Add `DeclaredOnly` when you want only what the class itself declares. ## A lookup that does what the binder means For a command whose options are public instance properties, the binder wants: ```csharp var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase; PropertyInfo? prop = command.GetType().GetProperty(optionName, flags); if (prop is { CanWrite: true }) prop.SetValue(command, Convert.ChangeType(rawValue, prop.PropertyType)); ``` Look the `PropertyInfo` objects up once per command type and keep them in a dictionary keyed by option name, rather than searching on every call. Each `GetProperties()` call returns a new array and each name lookup filters the member list again; doing it once per type moves that work out of the loop. Reaching private members by design (setting `Token`) is a different decision. It means `NonPublic` and a coupling to implementation details the type's author never promised to keep stable.
- Your binder sets every property `GetProperties()` returns, and a run of one command changes a setting for every command. What happened?The parameterless `GetProperties()` uses `Public | Instance | Static`, so it also returned a public static property declared on the options class. Setting it changed shared state for every instance. Ask for `BindingFlags.Instance | BindingFlags.Public` explicitly, or skip properties whose setter is static.
- What does `GetProperty(name, Instance | Public | IgnoreCase)` do when a class declares both `Region` and `region`?Both match case-insensitively, so the lookup has two candidates and throws `AmbiguousMatchException` rather than picking one. A binder that must accept any casing should detect that case when it builds its per-type map of option names, so the failure appears once at startup instead of on a user's command.
- GetProperties() returns only public instance properties
- BindingFlags.IgnoreCase on its own is enough to find a public property
- GetProperty throws when the name does not match
- Reflection cannot call a private setter found on a public property
- BindingFlags.DeclaredOnly also returns members inherited from base classes
- FlattenHierarchy returns inherited instance members