15

There is no (explicit) reference to a firstName private variable which FirstName is supposed to be hiding. Could you explain how this works? I assume there is some private variable that is being getted and setted. Thanks.

// auto-implemented property FirstName
public string FirstName { get; set; }
user776676
  • 4,265
  • 13
  • 58
  • 77
  • This is a duplicate. See related links on the side. – leppie Feb 13 '12 at 07:22
  • possible duplicate of [C# 3.0 :Automatic Properties - what would be the name of private variable created by compiler](http://stackoverflow.com/questions/1277018/c-sharp-3-0-automatic-properties-what-would-be-the-name-of-private-variable-c) – nawfal Jun 03 '13 at 17:48

4 Answers4

30

Basically the compiler converts your code into something like this:

private string <__>firstName;

public string FirstName
{
    get { return <__>firstName; }
    set { <__>firstName = value; }
}

That's unlikely to be the exact name, but the use of angle brackets in the name is important - because it makes it an unspeakable name. (That's unofficial terminology, but widely used - I don't know whether Eric Lippert actually coined it, or whether he was just the first person to use it in something I read.) It's a name which isn't a valid C# identifier, but which the CLR is quite happy with. That has two benefits:

  • The compiler doesn't need to worry about naming collisions with your identifiers
  • The compiler doesn't need to worry about whether you're trying to refer to the field in your own code - you can't, because the name is unspeakable!

It uses the same technique for all kinds of other generated code - anonymous types, anonymous functions, iterator blocks etc.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
8

yes, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors. (c) msdn

EDIT:
When you define a property, compiler will emit 2 methods: get_XXX and set_XXX. When the C# compiler sees code that's trying to get or set a property, the compiler actually emits a call to one of these methods. (c) "CLR via C#"

Sergey Gavruk
  • 3,538
  • 2
  • 20
  • 31
4

C# compiler creates the backing store field behind the scenes, you can try to decompile it. using Reflector. you will come to know, how it's created backing fields . here's the same reply

MSDN Auto-Implemented property

Auto implemented property

Community
  • 1
  • 1
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83
2

The other guys have answered this, but a little further info ... you can find the backing field at run time using reflection. Look for fields with naming like << PropertyName>>k__BackingField.

Another post that may help:

Community
  • 1
  • 1
Rob Smyth
  • 1,768
  • 11
  • 19