Ad

Public Variables Vs Private Variables With Accessors

- 1 answer

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?

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad