2

When creating an auto-implemented property, C# generates a member for that property somewhere in the background. I for the life of me can't remember what this is called, or what the naming convention for the member is called. After Googling for a while, I thought it might be an idea to just ask.

Property:

public int Age { get; set; }

My guess (from memory) of the hidden member:

private int i_age;

Edit #1

To clarify, I was looking for the term of the auto generated member, which was answered by Dmitry Bychenko below. The term is "backing field"

Oyyou
  • 610
  • 5
  • 13
  • 1
    Why do you need this name? The name might change between C# versions. – Wazner Jul 25 '18 at 10:28
  • See https://stackoverflow.com/questions/8817070/is-it-possible-to-access-backing-fields-behind-auto-implemented-properties to get the name of the private backing-field. – MakePeaceGreatAgain Jul 25 '18 at 10:28
  • 2
    It's an implementation detail and you should never ever write any code relying on that. This said...no, it generates an unique name which you can't create in your code then it will, for sure, includes _special characters_ which can't be used as C# identifiers. – Adriano Repetti Jul 25 '18 at 10:29
  • Why do you care? you don't have access to that field anyway (except through reflection), and it is an implementation detail, as Adriano wrote in his comment... – Zohar Peled Jul 25 '18 at 10:33
  • I guess I phrased the question wrong, but what I wanted was the term used. So as Dmitry answered below, it's "backing field". – Oyyou Jul 25 '18 at 10:43

2 Answers2

6

Why not carry out a simple experiment?

using System.Reflection;

...

public class Experiment {
  public int Age { get; set; }
}

...

var fieldNames = string.Join(", ", typeof(Experiment)
    .GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
    .Select(field => field.Name));

Console.Write(fieldNames);

Outcome:

<Age>k__BackingField

Please, notice that unlike i_age actual field's name <Age>k__BackingField doesn't conflict with any field (we can't declare a field with such a name)

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    I'm not _too_ experienced with reflection, so I didn't know this was an option. This answer is exactly what I was hoping for. Thank you very much! – Oyyou Jul 25 '18 at 10:45
0

Hi You may want to try this.

private int i_age;
public int Age 
{ 
    get {return i_age;} 
    set {i_age = value;}
}