C# – Using a private auto-implemented property vs. a private field

ccoding-standardsnet

If I have a need for simple, private fields, is there any reason I shouldn't just make it a convention to use private, auto-implemented properties instead?

For instance, I could do this:

private MyClass _foo;

or I could do this:

private MyClass Foo { get; set; }

It seems like the only time I need actual fields is when I'm doing something like lazy loading:

private MyClass Foo
{
    get
    {
        if (_foo == null) _foo = new MyClass();
        return _foo;
    }
}

Best Answer

The two features of fields that I feel you might run into more commonly that you would lose by converting them to properties are the following:

  1. You can't modify members of a property value if it's a value type.

    // Rectangle is a value type:
    struct Rectangle { int X, Y, Width, Height; }
    
    Rectangle rect;
    Rectangle RectProperty { get; set; }
    
    void Test()
    {
        // This works with a field:
        rect.X = 45;
    
        // but fails with a property:
        RectProperty.X = 45; // compiler error
    
        // The only way to update a value-type property 
        // is to construct & assign a completely new value:
        RectProperty = new Rectangle(45, RectProperty.Y, RectProperty.Width, RectProperty.Height);
    }
    
  2. You can't pass a property as an out or ref parameter

    int field;
    int SomeProperty { get; set; }
    
    void Test()
    {
        // Works with a field:
        int.TryParse("some text", out field); 
    
        // but fails with a property:
        int.TryParse("some text", out SomeProperty); // compiler error.
    
        // you need to create temporary storage instead:
        int x;
        if (int.TryParse("some text", out x)) { SomeProperty = x; }
    }
    

If neither of these is an issue for you, then you probably won't notice the difference. There are of course other differences if you're reflecting over your type, or using libraries that reflect over your type and expect things to be properties or fields, etc.

Related Topic