Chapter 3. Types

C# does not limit us to the built-in data types shown in Chapter 2. You can define your own types. In fact, you have no choice: if you want to write code at all, C# requires you to define a type to contain that code. Everything we write, and any functionality we consume from the .NET Framework class library (or any other .NET library) will belong to a type.

C# recognizes multiple kinds of types. I’ll begin with the most important.

Classes

Whether you’re writing your own types or using other people’s, most of the types you work with in C# will be classes. A class can contain both code and data, and it can choose to make some of its features publicly available, while keeping other features accessible only to code within the class. So classes offer a mechanism for encapsulation—they can define a clear public programming interface for other people to use, while keeping internal implementation details inaccessible.

If you’re familiar with object-oriented languages, this will all seem very ordinary. If you’re not, then you might want to read a more introductory-level book first, because this book is not meant to teach programming.[16] I’ll just describe the details specific to C# classes.

I’ve already shown some examples of classes in earlier chapters, but let’s look at the structure in a bit more detail. Example 3-1 shows a simple class. (See the sidebar Naming Conventions for information about naming conventions for types and their members.)

Example 3-1. A simple class

public ...

Get Programming C# 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.