Reputation: 31
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
.
Upvotes: 1
Views: 632
Reputation: 186668
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
Upvotes: 3
Reputation: 1073
the shorthand version uses a "hidden" variable to store the values in.
if you write public int hWorked {get; set;}
it reads and writes from a unnamed variable in the background.
Upvotes: 1