Encapsulation

Even though the previous discussion has pretty much introduced the concept of encapsulation already, let’s translate the sample to the C# world first. Encapsulation enables members (including fields for state, as well as all the other members discussed in Chapter 11, “Fields, Properties, and Indexers,” Chapter 12, “Constructors and Finalizers,” and Chapter 13, “Operator Overloading and Conversions”) to be associated with a type. In fact, C# doesn’t allow global members that are defined outside a type (even though the CLR does). In this world, our counter looks like this:

class Counter {    private readonly int _id;    private int _i;    private static int s_n;    public Counter() {       _id= s_n++; ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.