Question

Possible Duplicate:
What is the difference between a field and a property in C#?

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.

Was it helpful?

Solution

The difference is that, if at a later point you need to add some logic to the getter/setter methods, the calling code won't break.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top