I routinely have a need to create protected variables in my class/subclass hierarchies. However I keep seeing others implementations which use a simple get/set property instead of a variable.

Since there is no code that needs to execute in the getter or setter and since their scope is always protected, is there a difference?

protected int foo1;
// vs
protected int foo2{ get; set; }

I know the advantage of the former is you can directly initialize it with a value, but I'm wondering if there are any other things/limitations I need to be aware of.

Note: There will never be a case where there is code in the getter/setter. These are simply placeholders for internally-calculated metrics and performance is critical (even to the millisecond-level) which has me thinking the first is better as it bypasses the getter/setter completely.

Not the only question. Simplicity too. Again, you can inline init a member variable but you have to use a constructor to init a prop with an auto-generated backing field, or implement the backing field yourself, in which case the property isn't needed. Either way, I just went with member variables for protected and private, and properties for public or mixed-accessor-scope values.
–
MarqueIVDec 29 '12 at 3:20

Well said Justin, and honestly, when you're the one who has to maintain it this can be a lifesaver.
–
Michael PerrenoudDec 28 '12 at 15:36

This is SOLID - closed for modification, open for extension.
–
TomTomDec 28 '12 at 15:38

Surely you could just re-implement the field as a property in this case, breaking nothing? (apart from maybe reflection-based stuff..)
–
Dave BishDec 28 '12 at 15:43

@DaveBish - It would break binary compatibility. The code wouldn't need to change, but it would require a re-compile.
–
Justin NiessnerDec 28 '12 at 15:44

1

@MarqueIV Did you profile it? There's no way an extra layer in the stack matters for your performance, the CLI is usually pretty darn well optimized for that. In the 0.0001% of cases where this actually matters then yeah - do whatever you need to get it running fast but don't make that trade-off without profiling first. And honestly, some other pattern will likely serve you better than protected members. I'm not sure but I think they might get a runtime check for memory access.
–
George MauerDec 28 '12 at 15:49

I use getters and setters for protected members unless it's read-only in which case a protected readonly will do just fine. In all honesty, unless someone is using reflection to iterate over properties it really doesn't matter - you can always switch one to the other and it will compile just fine.

Actually, come to think of it, I usually just use methods since the thing I usually want to inherit is the base behaviors, not the explicit base state.

Having lots of protected properties is honestly a code smell as it somewhat breaks encapsulation.