Does an uppercase property automatically create a lowercase private property in C #?

Take this code:

public int Foo {get;set;}

In contrast to this more complete hand-written code:

private int x;
public int X 
{
    get { return x; }
    set { x = value; }
}

In the first example, does the compiler automatically create a private property foo?

I'm not sure if this convention I saw that has a lowercase private property disguised as publicly uppercase is just a convention, or if it really is part of the language / compiler, and you can either write it or let it be made for you.

+4
source share
3 answers

Why not just see what happens?

  public class Test {
    // private int myProp;

    public int MyProp {
      get;
      set;
    }
  }

...

  string report = String.Join(Environment.NewLine, typeof(Test)
    .GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
    .Select(field => field.Name));

  Console.Write(report);

And you get a rather strange name

<MyProp>k__BackingField

, ( - , , .., <).

:, // private int myProp;,

myProp
<MyProp>k__BackingField

, , myProp myProp

+4

.

,

public int x { get; set; }

, get/set.

+3

, ( x, , <X>_BackingField). , . .

:

the compiler creates a private, anonymous support field, access to which can only be accessed through the get and set accessors property.

Having said that, the two sample codes in your question are identical in meaning.

+1
source

All Articles