The next feature on our list is one with a more positive feel. It??™s aimed at a very specific
??”although widely encountered??”situation, and allows a solution that is neither
ugly nor breaks encapsulation, which was the choice available in C# 1.
7.3 Separate getter/setter property access
I??™ll admit to being slightly bemused when I first saw that C# 1 didn??™t allow you to have
a public getter and a private setter for properties. This isn??™t the only combination of
access modifiers that is prohibited by C# 1, but it??™s the most commonly desired one. In
fact, in C# 1 both the getter and the setter have to have the same accessibility??”it??™s
declared as part of the property declaration rather than as part of the getter or setter.
There are perfectly good reasons to want different accessibility for the getter and
the setter??”often you may want some validation, logging, locking, or other code to be
executed when changing a variable that backs the property but you don??™t want to
make the property writable to code outside the class. In C# 1 the alternatives were
either to break encapsulation by making the property writable against your better
judgment or to write a SetXXX() method in the class to do the setting, which frankly
looks ugly when you??™re used to ???real??? properties.
C# 2 fixes the problem by allowing either the getter or the setter to explicitly have a
more restrictive access than that declared for the property itself.
Pages:
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378