简体   繁体   中英

C# - How do properties access a private field using getter/setter short hand

I am perplexed as in my spare time I've been reading through C# books to become familiar with the language.

I stumbled upon the use of properties; in this context it is in regards to using a getter/setter for a privately declared field in my class.

This is what I have in my code as to keep it simple:

class ClassName
{
   private int hWorked = 24;
   public int HoursWorked
     {
       get
        {
          return hWorked;
        }
     }
}

Now the book says that:

If I use the short hand version - public int HoursWorked {get;} - that it is the same as the above code.

But what I need clarification on is how the shorthand is able to return the hWorked value without specifying that the hWorked = value .

In simple terms: How does the HoursWorked getter know to target my privately declared hWorked .

Well public int HoursWorked {get;} creates its own backing field and doesn't address hWorked . The equivalent of the code in the question (shorthand version) is

  class ClassName {
    public int HoursWorked { get; } = 24;
  }

You can see the backing field with a help of Reflection :

  using System.Reflection;

  ... 

  var fields = string.Join(", ", typeof(ClassName)
    .GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
    .Select(f => f.Name));

  Console.Write(fields);

Outcome (may vary):

  <HoursWorked>k__BackingField

If you inspect the initial ClassName implementation you'll get

  hWorked

the shorthand version uses a "hidden" variable to store the values in.

if you write public int hWorked {get; set;} public int hWorked {get; set;} it reads and writes from a unnamed variable in the background.

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