Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


1 Answers

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.

like image 69
Ondrej Janacek Avatar answered Sep 15 '25 10:09

Ondrej Janacek