public variables vs private variables with accessors

Kevin picture Kevin · Oct 3, 2008 · Viewed 7.2k times · Source

Has anyone else seen people do this:

private string _name;
public string Name{ get{ return _name; } set{ _name = value;}}

I understand using accessors if you are going to exercise some sort of control over how it gets set or perform some sort of function on it when there is a get. But if you are just going to do this, why not just make the variable public to begin with? Am I missing something?

Answer

Robert Rossney picture Robert Rossney · Oct 3, 2008

If you make the member a public field, then you can't later refactor it into a property without changing the interface to your class. If you expose it as a property from the very beginning, you can make whatever changes to the property accessor functions that you need and the class's interface remains unchanged.

Note that as of C# 3.0, you can implement a property without creating a backing field, e.g.:

public string Name { get; set; }

This removes what is pretty much the only justification for not implementing public fields as properties in the first place.