Free mag vol1 | Page 227

CHAPTER 5 Understanding Encapsulation In the Chapters 3 and 4, you investigated a number of core syntactical constructs that are commonplace to any .NET application you might be developing. Here, you will begin your examination of the objectoriented capabilities of C#. The first order of business is to examine the process of building well-defined class types that support any number of constructors. After you understand the basics of defining classes and allocating objects, the remainder of this chapter will examine the role of encapsulation. Along the way, you will learn how to define class properties, and come to understand the role of static members, object initialization syntax, read-only fields, constant data, and partial classes. Introducing the C# Class Type As far as the .NET platform is concerned, the most fundamental programming construct is the class type. Formally, a class is a user-defined type that is composed of field data (often called member variables) and members that operate on this data (such as constructors, properties, methods, events, and so forth). Collectively, the set of field data represents the “state” of a class instance (otherwise known as an object). The power of object-oriented languages, such as C#, is that by grouping data and related functionality in a unified class definition, you are able to model your software after entities in the real world. To get the ball rolling, create a new C# Console Application named SimpleClassExample. Next, insert a new class file (named Car.cs) into your project using the Project  Add Class... menu selection. Choose the Class icon from the resulting dialog box, as shown in Figure 5-1, and click the Add button. A class is defined in C# using the class keyword. Here is the simplest possible declaration: class Car { } After you have defined a class type, you will need to consider the set of member variables that will be used to represent