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 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

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 others 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. I’ll just describe the details specific to C# classes.

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

Example 3-1. A simple class
public class Counter
{
    private int _count;

    public int GetNextValue()
    {
        _count += 1;
        return _count ...

Get Programming C# 8.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.