简体   繁体   中英

Reference to the backing field of auto-implemented property

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#?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM