Reference to the backing field of auto-implemented property

1.7k Views Asked by At

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

There are 2 best solutions below

1
On BEST ANSWER

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.

0
On

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.