4

In C#, auto-implemented properties are quite a handy thing. However, although they do nothing but encapsulate their backing field, they still cannot be passed as ref or out arguments. For example:

public int[] arr { get; private set; } /* Our auto-implemented property */
/* ... */
public void method(int N) { /* A non-static method, can write to this.arr */
    System.Array.Resize<int>(ref this.arr, N); /* Doesn't work! */
}

In this specific case, we can go around the problem with a hack like this:

public void method(int N) { /* A non-static method, can write to this.arr */
    int[] temp = this.arr;
    System.Array.Resize<int>(ref temp, N);
    this.arr = temp;
}

Is there a more elegant way to use a reference to the backing field of an auto-implemented property in C#?

2 Answers2

7

Is there a more elegant way to use a reference to the backing field of an auto-implemented property in C#?

As far as I know, it's not. Properties are methods, that's why you can't pass them this way when a parameter expects a type of its backing field.

What you described as a solution is a solution if you want to use auto-properties. Otherwise, you would have to define a backing field yourself and let a property to work with it.

Note: you can get auto-property's backing field by reflection, but that's a hacky solution I would not use.

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
  • While yes, properties are methods, auto-properties have both a property and a field with the same conceptual "name", and the compiler should be smart enough to determine that you want to refer to the field rather than the property in that context. This is similar to the magic that happens with the `event` keyword -- it is both a delegate field and a collection of add/remove methods that act on that field. Sadly, however, this is not the case and you have to convert the auto-property to a regular one with explicit backing field if you want this behaviour. – Miral Oct 13 '15 at 00:26
3

from MSDN,

You can't use the ref and out keywords for the following kinds of methods:

  • Async methods, which you define by using the async modifier.
  • Iterator methods, which include a yield return or yield break statement.
  • Properties are not variables. They are methods, and cannot be passed to ref parameters.
Rohit Prakash
  • 1,975
  • 1
  • 14
  • 24