Prev | Current Page 367 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

This is most easily
seen with an example:
string name;
public string Name
{
get { return name; }
private set
{
// Validation, logging etc here
name = value;
}
}
In this case, the Name property is effectively read-only to all other types,2 but we can
use the familiar property syntax for setting the property within the type itself. The
2 Except nested types, which always have access to private members of their enclosing types.
193 Namespace aliases
same syntax is also available for indexers as well as properties. You could make the setter
more public than the getter (a protected getter and a public setter, for example)
but that??™s a pretty rare situation, in the same way that write-only properties are few and
far between compared with read-only properties.
NOTE Trivia: The only place where ???private??? is required??”Everywhere else in C#, the
default access modifier in any given situation is the most private one possible.
In other words, if something can be declared to be private, then leaving
out the access modifiers entirely will default it to being private. This is
a nice element of language design, because it??™s hard to get it wrong accidentally:
if you want something to be more public than it is, you??™ll notice
when you try to use it. If, however, you accidentally make something ???too
public,??? then the compiler can??™t help you to spot the problem.


Pages:
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379