0

I'm wondering whether there's any significant performance (or correctness) difference in using private fields in class constructors, instead of Properties that change those private fields.

Sample:

class Pt<T>
{
    public Pt(T _x, T _y)   // More efficient/correct?
    {
        this.x = _x;    // or x = _x
        this.y = _y;    // or y = _y
    }

    public Pt(T _x, T _y)   // Less efficient/correct?
    {
        X = _x;
        Y = _y;
    }

    private T x, y;

    T X { get { return x; } set { x = value; } }
    T Y { get { return y; } set { y = value; } }
}
mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
eduherminio
  • 1,514
  • 1
  • 15
  • 31
  • 4
    There will be a big difference in correctness if the properties perform an additional action (log the new value, raise a `NotifyPropertyChanged` event, or simlar)... – RB. Sep 15 '17 at 11:21
  • 2
    This will help you understand it better: https://stackoverflow.com/a/17578356/3365113 – TechGirl Sep 15 '17 at 11:22
  • Properties tend to serialise 'better' than fields. For `private` variables that is rarely a concern, so it doesn't matter much either way. – mjwills Sep 15 '17 at 11:23
  • Only if the property setter performs some logic. Remember, the whole point of a property is to control how a field is exposed outside of your class - inside the type, without custom logic in your getters and setters, that's not a concern. – thisextendsthat Sep 15 '17 at 11:23

1 Answers1

1

In terms of correctness, there is absolutely no difference in your code. From a performance point of view, there is a slight overhead when using the property version, because setting/getting a property requires an additional method call, because properties are translated to methods by the compiler. This performance hit is so minor it will not be noticeable, so write the version which is most readable and consistent with .NET standards.

Kapol
  • 6,383
  • 3
  • 21
  • 46