Search code examples
c#propertiesmember-variables

Should you use member variables or property getter/setter?


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.


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.