Search code examples
c#instance-variables

Why are instance variables always private, but the auto property sets them public? Still the same?


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; }
}

Solution

  • 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.