4.31 Mб



Each language construct of a C# program does not exist in isolation. It has its own vital part to play but is also closely interrelated with other elements. This makes it difficult to look at any one aspect of C# without requiring the knowledge of others. Due to this circular dependence among the elements of C#, this chapter, along with Chapter 4, “A Guided Tour Through C#: Part II,” and Chapter 5, “Your First Object-Oriented C# Program,” presents an overview of several important features, to give you an introductory feel for the language.

The presentation is facilitated by C# source code examples containing several essential elements of C#. Each element will be presented, discussed, and related to other parts of the C# program in a practically related fashion. This will enable you to start writing your own programs during this chapter. I hope you will grab this opportunity to play with and explore C#. Some of the most important parts of this and the following two chapters are the programming exercises at the end of each chapter. You don’t become a proficient C# programmer just by learning lots of definitions by heart but by doing and unleashing your creativity. So have a go at these exercises and use your imagination to come up with other ideas of how to improve the programs or, even better, create your own programs.

Abstraction and Encapsulation

Object-oriented programming is at the core of C#. Practically speaking, everything in C# is an object. Even the simple program you encountered in Chapter 2, “Your First C# Program” relies on OO principles. So before we dive into the first C# example, it is useful to expand on our OO introduction by looking at two core concepts of OO called abstraction and encapsulation.


Consider an airplane. Initially, it seems an impossible task to represent an airplane in a computer program. Just think about all the details—intricately designed jet engines, extremely complex onboard computers, entertainment systems. It is dizzying. However, by looking at the role we want the airplane to play in our application, we can significantly reduce the features to be represented. Perhaps we just need an airplane to be a position on a map. Perhaps we need to test the aerodynamic characteristics of an airplane in which case we only need to represent its outer shape. Perhaps an interior designer is making a 3D presentation of the airplane’s interiors, in which case, he needs to represent only the interior surfaces of the airplane.

In every airplane role mentioned, it is possible to identify the key characteristics of the airplane relevant to that particular application. Essentially, we are coping with the intricacies of the airplane by abstracting away from them.

Abstraction is one of the fundamental concepts utilized by programmers to cope with complexity.


When an object (or system) is specified or depicted in a simpler, less detailed fashion than its real counterpart, this specification is called an abstraction. Highlighting the properties that are relevant to the problem at hand, while ignoring the irrelevant and unduly complicating properties, creates a useful abstraction in OOP.

When creating an abstraction, it is important to include only the features that are part of the object being specified. The behavior of an object must not go beyond that of the expected. For example, creating an abstract car with the ability to draw architectural plans should be avoided. It creates confusion among yourself and other programmers trying to understand your source code.


Recall the elevator simulation discussion from Chapter 2, “Your First C# Program.” When designing an elevator simulation program, we must first ignore (by abstraction) all the unnecessary characteristics and parameters of the real world. For example, the color of each elevator and the hairstyle of each person in them can be disregarded. On the other hand, important information is the speed of each elevator, the number of people wanting to catch an elevator, and the floors to which they want to travel.

The simulation enables us to calculate statistics concerning waiting times and eventually an estimate for the number and types of elevators needed to service the building, just as Big Finance Ltd. requested in Chapter 2.

You have already seen one example of an abstraction in the C# program example in Chapter 2. It contained a class called Shakespeare.

Lacking arms, legs, inner organs, and a brain, the class had very little resemblance to the writer and person named Shakespeare, but it could still recite one very short quote of Shakespeare. Thus, because a very tiny piece of Shakespeare could be found in it, we still dared to call our class Shakespeare. Our Shakespeare class was an abstraction of the real writer and person—Shakespeare.


Whereas abstraction focuses on reducing the complexity of how we view the real world, encapsulation concentrates on the design of our C# source code. It is a powerful mechanism for reducing complexity and protecting data of individual objects on the programming level.

Encapsulation is the process of combining data and the actions (methods) acting on the data into a single entity, just as you saw in Chapter 2. In OOP and hence C#, such an entity is equivalent to an object.

Encapsulation is a mechanism for hiding instance variables and irrelevant methods of a class from other objects. Only methods, which are necessary to use an object of the class, are exposed.

The term encapsulation might sound like a sophisticated academic term, but despite this first impression, we can find parallels to it from our everyday life. We might not refer to it as


encapsulation, but the analogies are so striking that an example from the real world might be instructive. The example provided here returns to the world of elevators.

Encapsulation in a Real World Elevator System

Any useful elevator has a mechanism, such as buttons, that allow a passenger to select his or her destination floor. Pressing a button is a very easy action to perform for the user of the elevator. However, for the elevator faced with many conflicting simultaneous requests from many different people, it can be a complicated matter deciding which floor to go to and fulfill the request of each traveler expediently. Many conditions complicate the design of an elevator; some examples are provided in the following Note.

The Complicated Life of an Elevator

Modern elevators rely on sophisticated algorithms residing inside computers that control every move they make. Here are a few reasons why it is a complicated matter to decide the next move of an elevator.

A person called A might enter the elevator at floor 3 and request to go to floor 30. However, another person, B, has already pressed the button on floor 1 requesting to be picked up there. If the elevator goes directly to floor 30 with person A (but without B), person A will get there as fast as he or she could ever expect. However, person B has to wait. Perhaps, by merely moving two floors down, the elevator could have taken both people to a higher floor at the same time, saving time and power. Instead, the elevator has to go all the way up to floor 30 and then back down to pick up B. With many people constantly requesting elevators and destination floors, the matter gets much more complex.

At least a couple of other aspects complicate matters further for our trusted elevator:

Several elevators are probably working together to transport people between the different floors. They consequently need a “team” approach to fulfill as many requests as possible. Densely populated buildings with large amounts of traffic between floors require approximately two elevators for every three floors. Thus, a 60-floor building would require about 40 elevators.

Certain floors are more likely to be visited and have pick-me-up requests than other floors. These probabilities might vary throughout the day. If the elevators can somehow remember these patterns, they can optimize the efficiency of the sequence of floors visited.

Sophisticated algorithms have been constructed running inside computers that control the movements of the elevators, allowing them to serve as many people as possible, fast and efficiently.

This was a bit of elevator talk, but it leads us to an essential observation.

It is easy for a person to press a button and thereby use the hidden complex services (algorithms, engines, hydraulics, gears, wires, data about current speed, maximum speed, and so on) provided by the elevator. Thus, the ignorant passenger, in terms of elevator technology, can easily utilize the services of the elevator to accomplish his or her tasks of the day.

Not only is this concealment of elevator data, algorithms, and mechanics an advantage for travelers who do not want to deal with complex matters that are irrelevant to them; but it also improves the reliability of the elevator itself. No unauthorized and incompetent person can


gain access to the inner control mechanisms of the elevator. Imagine if the elevator was equipped with a small “cockpit” where anybody traveling in the elevator could tinker with the maximum speed, or make the elevator believe it was on an incorrect floor, or force it to move to a floor other than the one calculated by its control algorithms. A chaotic situation would soon prevail.

A final advantage of segregating the buttons from the underlying elevator mechanisms is the capability of making changes to these mechanisms without altering the buttons and, hence, the way it is operated. In this way, an elevator can contain the same buttons that everyone has become accustomed to using for many years, while many underlying hardware and software upgrades have taken place to keep the system up to date.

Encapsulation in an Elevator Simulation

Let’s look at how the previously discussed issues relate to an object-oriented C# elevator simulation program.

An elevator simulation program written in C# will probably have Elevator and Person objects along with others. Even though now inside a computer program, a Person object will still be able to perform the equivalent of “pressing the button” of an Elevator object and giving it a floor request.

Each Elevator object of the simulation probably contains, like its real counterpart, many complex methods and many sensitive data. For example, many Elevator objects might, to make the simulation particularly realistic, be equipped with algorithms (similar to the algorithms of real world elevators) to calculate the most efficient sequence of floors visited.

Now the important analogy—each Person object (and the programmer implementing it) of the simulation should still not need or be allowed to “know” about the inner complexities (source code) of any Elevator object. All they should “care” about, just like their real counterparts, is to get from one floor to another. They don’t want to be confused about unnecessary complexities either. They should not be allowed to tinker with the inner workings (data and source code) of the Elevator object, and the programmers implementing the elevator should be able to change and upgrade the source code without interfering with how the Elevator object is used (operated).

To accomplish this concealment in the OO world, we say that we encapsulate (hide) the underlying data and source code that is irrelevant for all but the Elevator objects themselves.

When we write and create the Elevator objects in C#, we somehow need a way to tell the program and the other objects, including the Person objects, that the data and source code are hidden. C# has a special word for this purpose called private. Thus, by declaring the data and relevant source code to be private, we are able to prevent any other object from gaining access to these parts of our Elevator object.


Any words with a special meaning in C# as well as references made to parts of source code presented in this book appear in a special font, such as private.


private and public

The word private has a special meaning to the C# compiler. It is used to hide method and instance variables (residing inside an object) from other objects.

Likewise, the word public has a special (albeit opposing) meaning to the C# compiler. public is used to allow other objects access to methods and instance variables of a specific object.

Because private and public control the accessibility of the methods and instance variables belonging to an object, these two words are referred to as access modifiers.

However, if we hide all the instance variables and methods of an object, none of its methods can be accessed, rendering the object completely useless. For example, a Person object needs somehow the ability to “express” its floor request. A method with this capacity could arbitrarily be called NewFloorRequest. What would happen if we declared NewFloorRequest to be private? Well, an Elevator object that had just “loaded” a “passenger” (a Person object) with these characteristics would not be able to access the NewFloorRequest method, which is the only means to find out the floor to which this “passenger” “wanted” to “travel.” This would be the equivalent of a real person without any arms, who is unable to reach out and press a button. In the C# source code, we somehow need a way to put “arms” on our Person object and buttons on our Elevator object, so contact can be made between the two objects.

We do this by exposing methods like NewFloorRequest. Instead of marking this method with the private word, we use another special word from C# called public.

A Person object can now “walk into” an Elevator object. When ready, the Elevator object can send a message to the Person object and, via the NewFloorRequest method, receive the desired destination floor of this Person. Figure 3.1 illustrates this scenario. Notice the double lined arrow. It represents the message sent to the Person object. The single lined arrow going in the opposite direction represents the value (the floor number request) returned to the Elevator object from the Person object. The double lined arrow represents a method call. Programmers say that the Elevator object is calling the NewFloorRequest method.

The Elevator object, like its real counterpart, might need to somehow keep track of, for example, the speed at which it is traveling and its maximum speed; these are the instance variables (data) of the object, as mentioned previously. Just like the elevators of the real world, the Elevator objects of the C# simulation do not want any interference from other objects to mistakenly change their instance variables. Therefore, the Elevator objects declare them to be private, as shown in Figure 3.1, making them inaccessible for other objects.

Encapsulation in a Typical Class

Recall the objects displayed in Figure 2.3 of Chapter 2. They are equivalent to the objects shown in Figure 3.1. A generalized object using C#’s access modifiers and indicating the encapsulating public layer is displayed in Figure 3.2. Notice how the public area of this generic object can be viewed to surround the private area like a protective shell. The object still contains the instructions executed by the computer (flow of execution or algorithms); they have now been divided into a public part and a private part. All the data (or instance variables) are hidden inside in the private area.


Elevator object requesting information from Person object.


A generic object.


private Instance variables

private methods public methods

Person object

Elevator object






complex control algorithms


other algorithms moving elev.









Sending a message to another object

Sending back requested information

public methods

private methods private Instance variables

Flow of execution (algorithms)


instance variables









Class and Object

The class works as a template for the creation of objects. The blueprint of an elevator is to the elevator designer what the class is to the programmer.

All objects of the same class contain the same methods and the same instance variables. Consequently, a class is a logical construct; but an object has the ability to perform the actions specified by the class.

All objects of the same class are called instances of a class. When an object is formed during the execution of a program (as when a tangible elevator is manufactured), we say it is created or instantiated.


We can now depict a typical generic class as illustrated in Figure 3.3. Simply viewed, the class consists of data (instance variables) and algorithms (methods). When you write the source code for a class, you specify the methods and the instance variables that you want this class, and all objects derived from it, to contain. All instance variables and methods are collectively referred to as members or fields of the class.


A generic class illustrates encapsulation.

private Instance variables

Hidden methods


private methods

public methods


Instance variables (Data) are hidden


Communicates with external world

Encapsulation entails a layer that is meant to communicate with the outside world. Only through this part can the outside world communicate with the object. It further allows for a hidden part to exist inside this layer. This protective layer is denoted an interface and should only consist of methods.

Helper Methods

private methods can only be called by methods belonging to that same object. They provide functionality and support for other (often public) methods in the object and are frequently called helper methods or utility methods.


The main advantages of encapsulation are as follows:

It provides for an abstraction layer—Encapsulation saves the programmer who uses a class the need to know about the details of how this particular class is implemented.

It decouples the user interface of the object with its implementation—It is possible to upgrade the implementation of an object while maintaining its user interface.

It covers the object with a protective wrapper—Encapsulation protects the data inside the object from unwanted access that, otherwise, could cause the data to be corrupted and misused.


Only Methods Should Be Part of an Object’s Interface, not Instance Variables

Instance variables positioned in the interface (this is possible in C#) effectively break the protective wrapper and allow for other objects to tinker with those exposed pieces of data. If access to specific data is needed, it should always be through a method (or properties and indexers, as discussed in later chapters).

A Note on Learning Object-Oriented Programming

Object-oriented programming and its related concepts might seem a bit fuzzy and overwhelming to you right now. This is perfectly normal, so don’t despair.

In my experience, learning OOP is not like learning the content of, say, a history book by heart. While reading the history book, you gradually learn the material. It seems that an hour spent studying gives you an hour’s worth of knowledge (unless the subject is complex and interrelated with other historical events), resulting in a nearly linear relationship between the amount of hours spent studying and the amount of knowledge you have acquired (see Figure 3.4).


Comparing learning by heart and learning OOP.

Content of history book you know

Amount of OOP you think you know


Hours spent studying the history book



Fuzzy stage









Hours spent reading and programming

This is most often not the case when learning OOP because of its interrelated and dynamic aspects and because OOP implies more than just a bunch of statements being executed one after the other. Initially, you will likely learn the names of several concepts (see 1 in Figure 3.4) but without much understanding for their real purpose. You might spend some time in this fuzzy, perhaps frustrating stage. Despite your studying efforts, you might not feel you are really gaining an increased understanding for the underlying logic; new concepts presented seem to confuse rather than enlighten (see 2 in Figure 3.4). However, your mind is constantly absorbing new aspects, information, and subtleties whenever you read the theory and work through the examples. Suddenly, at a specific moment in time (perhaps at night just after waking up from your favorite dream about abstraction and encapsulation), you experience this quantum leap in understanding, this AHA! Experience. All of a sudden, the pieces of the puzzle form a meaningful picture (see 3 in Figure 3.4). Equipped with this fundamental understanding, it becomes much easier to learn the new, more advanced OOP concepts (see 4 in Figure 3.4).