Edward Tanguay
Edward Tanguay

Reputation: 193472

Strategies for when to use properties and when to use internal variables on internal classes?

In almost all of my classes, I have a mixture of properties and internal class variables. I have always chosen one or the other by the rule "property if you need it externally, class variable if not". But there are many other issues which make me rethink this often, e.g.:

e.g.:

public class TextFile
{
    private string templateIdCode;
    private string absoluteTemplatePathAndFileName;
    private string absoluteOutputDirectory;
    private List<string> listItems = new List<string>();

    public string Content { get; set; }
    public List<string> ReportItems { get; set; }

    public TextFile(string templateIdCode)
    {
        this.templateIdCode = templateIdCode;
        ReportItems = new List<string>();
        Initialize();
    }
    ...

When creating internal (non-API) classes, what are your strategies in deciding if you should create an internal class variable or a property?

Upvotes: 4

Views: 657

Answers (1)

derek
derek

Reputation: 4886

If I have a private variable that I find needs public access at a later point, I just create a property that uses it as it's private member, ex:

private List<string> listItems = new List<string>();

Public List<string> ListItems
{
     get{return listItems;}
     set{listItems = value;}
}

This allows you to create public access to the data, without having to refactor any code. It also allows you to initialize the data in the private member, and not have to do it in the constructor.
One more advantage is that any modifications to the data that you want to perform for anyone accessing the public property, can be done in the property's getter. Even though VS2008 introduced Automatic Properties as a feature, I still prefer the VS2005 style of properties.

Upvotes: 1

Related Questions