Search code examples
c#oopsyntaxresharperconventions

Are private fields needed in a class where no methods exist?


I've been using ReSharper to do some work on cleaning up a C# codebase. I had been using both private fields in model classes along with public properties. However, I'm finding that I can simply take the properties that have no backing fields and convert them into auto-properties. These are model classes; no methods exist within them to impact the data in the objects. Is it better to just use the auto-properties?

EDIT: Including example of "Backing fields"

public class Gizmo
{
    //this is what I call the "backing" field, only because it's "behind" the
    //publicly-accessible property and you access it through the property
    private Int32 _count;

    //and this is the property, of course
    public Int32 Count
    {
        get { return _count; }
        set { _count = value; }
    }
}

Solution

  • Is it better to just use the auto-properties

    If your property involve is simple get;set, you can just use a "auto-property". If I am not wrong, compiler will create a private backing field behind the scenes.

    If in your property, you are doing some kind of validation before; say before set then it makes sense to use a property with a backing field (non-auto)

    An example would be

    private string name;
    
    public string MyName {
        get {
            return name;
        }
        set {
            name = (value == null)
                ? "Anonymous" : value;
        }
    }