0

What I don't get is,

I know that auto property is suppose to make things easier.

Normally:

private string name;

public string Name
{
    get { return name; }
    set { name = value; }
}

With Auto Property:

public string Name { get; set; }

But if we can just declare the instance variables as public, like in the auto property, why don't we declare instance variable in the normal version as public as well?

So would this be exactly the same as the previous ones? :

public string name;

public string Name
{
    get { return name; }
    set { name = value; }
}
BeLambda
  • 887
  • 1
  • 10
  • 19
  • field or variable is not typically exposed outside of the class while property is exposed. It is a more common practice that way. The auto property is designed following the common practice. – Ian Feb 16 '16 at 04:39
  • 1
    You Can find more at this Link. http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c – The_Mind_Hunter Feb 16 '16 at 04:49

2 Answers2

2

All though you could do that, imagine working with this API and seeing that you have object.Name and object.name. How would you know which one to use?

Generally, public fields are considered bad practice, because you're giving the user of that class full power to field. Even though an auto property gives the same amount of power, it makes it easier to add calculations/filters to the setter or getter, or remove a setter or getter altogether.

By making the backing field public, you are giving the user the power to completely ignore anything validation you had set up.

I think you might be getting confused here.

As you can see in this sharplab.io example,

public string Name { get; set; }

Compiles into:

private string <Name>k__BackingField;
public string Name
{
    get { return this.<Name>k__BackingField;  }
    set { this.<Name>k__BackingField = value; }
}

So you can see, the actual field exists, however its inaccessible to everyone, so its like super-private. Sometimes you may not want this, however. I've ran into a few times where I actually wanted the class of the property to be able to access the private backing field to avoid calling the set and gets, to avoid infinite loops, though I feel this can be a bad practice, and should be avoided.

But point being, auto properties do have a private field behind the scenes and are not a private field unto themselves.

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
0

In an ideal programming scenario, properties are declared public as they are exposed outside.

Fields on the other hand are private as they should not be exposed because we do not have control over them when their value changes. On the other hand, we have such control in properties.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208