Automatic Property

  • Thread starter Thread starter Man T
  • Start date Start date
M

Man T

public int MyIntProp
{
get;
set;
}

How does this automatic property knows which private field to be accessed?
 
public int MyIntProp
It knows because it creates its own private field to use (hidden from your
own code).

Then how does the class access this hidden private field?
 
How does this automatic property knows which private field to be
It doesn't. Only the implementation of the automatic property does.

Even for explicitly implemented properties, you should think twice, maybe
even a half-dozen times, before writing code that accesses the backing
field rather than going through the property. For automatic properties,
this is just not an option.

So this automatic property is not being used by the other class members?
 
So this automatic property is not being used by the other class members?

Here's the deal. In a normal property, you have this:

private int _myIntProp;
public int MyIntProp
{
get { return _myIntProp; }
set { _myIntProp = value; }
}

Now your code can refer to the value that the property represents in one of
two ways:

int x = _myIntProp;

or

int x = this.MyIntProp; // "this." is of course optional

Many people consider it bad programming practice to refer to the backing
variable ( _myIntProp ) directly, because in many properties, code may be
getting executed in the getter, setter, or both, and accessing or changing
the variable directly would bypass this code. In the above example, this is
NOT an issue.

In an attempt to "save you from yourself," these new automatic properties
were created. Now you can NEVER directly access the backing variable because
it's hidden from you. So if you do this:

public int MyIntProp
{ get; set; }

you can ONLY refer to the value with "this.MyIntProp". Get it?
 
Back
Top