Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# using setters or getters from base class

Is it recommended to set member variables of a base class to protected, so that subclasses can access these variables? Or is it more recommended to set the member variables to private and let the subclasses get or set the varible by getters and setters?

And if it is recommended to use the getters and setters method, when are protected variables used?

like image 383
Martijn Avatar asked Dec 05 '22 07:12

Martijn


2 Answers

This is very similar to this question, about whether to access information within the same class via properties or direct access. It's probably worth reading all those answers too.

Personally, I don't like any fields to be non-private with the occasional exception of static readonly fields with immutable values (whether const or not). To me, properties just give a better degree of encapsulation. How data is stored is an implementation decision, not an API decision (unlike properties). Why should class Foo deriving from class Bar care about the implementation of class Bar?

In short, I'd always go for properties, and I don't use protected variables for anything other than throwaway test code.

With automatically implemented properties in C# 3.0, it's easier than ever before to turn fields into properties. There's precious little reason not to do it.

like image 147
Jon Skeet Avatar answered Dec 07 '22 21:12

Jon Skeet


Classes in other assemblies can derive from your unsealed classes and can access protected fields. If you one day decide to make those fields into properties, those classes in other assemblies will need to be recompiled to work with the new version of your assembly. That's called "breaking binary compatibility", and is perhaps the one solid reason why you shouldn't ever expose fields outside of an assembly.

like image 28
Daniel Earwicker Avatar answered Dec 07 '22 19:12

Daniel Earwicker