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

Posted by Edward Tanguay on Stack Overflow See other posts from Stack Overflow or by Edward Tanguay
Published on 2010-05-23T10:11:08Z Indexed on 2010/05/23 10:20 UTC
Read the original article Hit count: 262

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

  • at some point I want to use an internal variable from outside the class, so I have to refactor it into a property which makes me wonder why I don't just make all my internal variables properties in case I have to access them externally anyway, since most classes are internal classes anyway it aren't exposed on an API so it doesn't really matter if the internal variables are accessible from outside the class or not

  • but then since C# doesn't allow you to instantiate e.g. List<string> property in the definition, then these properties have to be initialized in every possible constructor, so these variables I would rather have internal variables just to keep things cleaner in that they are all initialized in one place

  • C# code reads more cleanly if constructor/method parameters are camel case and you assign them to pascal case properties instead of the ambiguity of seeing "templateIdCode" and having to look around to see if it is a local variable, method parameter or internal class variable, e.g. it is easier when you see "TemplateIdCode = templateIdCode" that this is a parameter being assigned to a class property. This would be an argument for always using only properties on internal classes.

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about properties