Why does C# reject Interlocked.Increment(ref stats.Hits) with CS0206 when Hits is an auto-property, and what may a ref argument be?
answer
- an address is required
- properties are accessor methods
- arrays yes, List<T> no
- readonly only during construction
basics
~20 sA ref or out argument must be a variable: a local, a parameter, a field or an array element. A property or a List<T> indexer is a method call that returns a value, so the compiler reports CS0206.
solid answer
~40 s`Interlocked.Increment(ref int location)` needs a reference to an `int` it can update atomically, and only a **variable** has one: a local, a parameter, a field, an array element, or the result of a ref-returning member. An auto-property looks like a field but compiles to `get_Hits()` and `set_Hits(int)` around a backing field that code outside the accessors cannot reach, so `ref stats.Hits` is CS0206. A `List<T>` indexer is the same (`ref counts[0]`), while `ref slots[0]` on an `int[]` compiles. A literal or computed value is CS1510, and a `readonly` field outside construction is CS0192. The fix is a private field incremented with `Interlocked` and exposed through a read-only property; copying the property into a local and back compiles but loses the atomicity the call was for.
code
csharp · 17 linesvar stats = new Stats();
var slots = new int[3];
Parallel.For(0, 1000, i =>
{
Interlocked.Increment(ref stats.Total); // a field is a variable
Interlocked.Increment(ref slots[i % 3]); // so is an array element
stats.RecordHit();
});
Console.WriteLine($"{stats.Total} {slots[0] + slots[1] + slots[2]} {stats.Hits}");
public class Stats
{
public int Total;
private int _hits;
public int Hits => Volatile.Read(ref _hits);
public void RecordHit() => Interlocked.Increment(ref _hits);
}go deeper
Recall that ref and out arguments must be variables, and that a property, even an auto-property, is not one.
Explain why: accessors return copies, arrays expose real elements, and name CS0206, CS1510 and CS0192 with the case each one covers.
Fix shared counters correctly with a private field, Interlocked and a read-only property, and catch the copy-and-write-back pattern that compiles but loses updates.
Decide how far encapsulation bends for hot paths: when a field or a ref-returning member is acceptable in a public type, and how that choice is documented.
## Arguments that need a location A `ref` or `out` parameter is an alias for a variable the caller owns, so the caller has to supply something that *is* a storage location: the runtime passes a reference to that location, and every write in the method lands there. `Interlocked.Increment(ref int location)` makes this concrete. It performs an atomic read-modify-write on the memory the reference points to, which only works if the argument names real memory. C# calls such an argument a **variable**. Values that are merely *computed*, such as the result of a method call, a literal or an arithmetic expression, have no location of their own and cannot be passed by `ref` or `out`. ## What counts as a variable | Argument | Allowed for `ref` / `out`? | Diagnostic | |---|---|---| | Local or parameter (`count`) | yes | none | | Field of a class instance (`stats.Total`) | yes | none | | Array element (`slots[i]`) | yes | none | | Auto-property (`stats.Hits`) | no | CS0206 | | `List<T>` indexer (`counts[0]`) | no | CS0206 | | Literal or expression (`5`, `stats.Total + 1`) | no | CS1510 | | `readonly` field outside construction | no | CS0192 | | `static readonly` field outside the static constructor | no | CS0199 | The texts the SDK prints are *A non ref-returning property or indexer may not be used as an out or ref value* (CS0206) and *A ref or out value must be an assignable variable* (CS1510). ## Why properties and indexers are excluded A property is a pair of **accessor methods**. `public int Hits { get; set; }` compiles to `get_Hits()` and `set_Hits(int)` plus a compiler-generated backing field that code outside the accessors cannot name. Reading `stats.Hits` is a method call that returns a copy of the value; there is no location for `ref` to point at, and the compiler will not reach behind the accessors to the hidden field, because that would bypass any logic the setter has or might gain later. An indexer is a property with parameters, so `List<T>`'s `this[int index]` behaves the same way: `counts[0]` calls `get_Item(0)` and returns a copy of the element. An **array** element is different. The runtime gives arrays direct element access, so `slots[i]` is a genuine variable and `ref slots[i]` compiles. The exception to the property rule is a member that returns `ref T`, such as the indexer of `Span<T>`, because it hands out a reference rather than a value; ref returns themselves belong to the lesson on ref locals and ref structs. ## Fixing the counter 1. **Keep a private field and expose it read-only.** `private int _hits;`, `public void RecordHit() => Interlocked.Increment(ref _hits);` and `public int Hits => Volatile.Read(ref _hits);`. The field is a variable, so the atomic call works, and callers still see a property. 2. **Do not copy out and back.** `var h = stats.Hits; Interlocked.Increment(ref h); stats.Hits = h;` compiles, but each thread now increments a private copy and writes it back. Two threads that read the same value both write the same result, and an increment is lost. 3. **Promote to a field only deliberately.** A public mutable field passes by `ref` fine, but it gives up encapsulation for every caller to fix one call site. ## readonly fields and construction A `readonly` field can be assigned only while its object is being constructed, so it can be passed as `ref` or `out` only then: inside an instance constructor, or an `init` accessor, of the declaring type (a `static readonly` field only inside the static constructor). This is how a constructor can initialise a field through a helper such as `Set(out Limit)`. Anywhere else the compiler reports CS0192 or CS0199. Passing a `readonly` field to an `in` or `ref readonly` parameter is allowed anywhere, because those parameters cannot write. ## Quick rules to remember - `ref` and `out` need an assignable variable; check the argument is a local, parameter, field or array element. - Properties and non-ref indexers never qualify, however simple their accessors are. - An `in` parameter is the one by-reference parameter that accepts a property or literal without a modifier: the compiler copies the value into a hidden temporary and passes a reference to that.
- Why can you pass an array element by ref but not a List<T> element?An array element is a variable: the runtime can hand out a reference straight into the array's storage. `List<T>`'s indexer is an accessor pair, `get_Item` and `set_Item`, and the getter returns a copy of the element, so there is no location to reference and the compiler reports CS0206. `Span<T>`'s indexer differs because it returns `ref T`.
- Is copying the property into a local, incrementing it by ref and writing it back an acceptable fix?It compiles but defeats the purpose. Each thread reads the property, increments its own local and writes it back, so two threads that read the same value both write the same result and one increment is lost. Atomicity needs the shared field itself as the `ref` argument.
- When can a readonly field be passed as a ref or out argument?Only while the object is being constructed: in an instance constructor or an `init` accessor of the declaring type, or the static constructor for a `static readonly` field. Elsewhere the compiler reports CS0192 or CS0199. Passing it to an `in` or `ref readonly` parameter is fine anywhere, since those cannot write.
- An auto-property can be passed by ref because the compiler uses its backing field.
- Any element access, on a List<T> or an array, can be passed by ref.
- Copying a property into a local, incrementing it by ref and writing it back is still atomic.
- A readonly field can never be passed as ref or out, not even in a constructor.
- CS0206 means the property is not accessible from the calling code.