3

Classes in C#

3.1 INTRODUCTION AND OBJECTIVES

In this chapter we discuss how to create classes in C#. The emphasis here is on using C# to create robust and maintainable code. We also introduce the inheritance relationship and its implementation in C#.

The topics that we discuss in this chapter are:

  • Creating classes in C#; implementing methods and member variables.
  • Value types.
  • Reference types and the new keyword.
  • Implementing set/get methods using C# properties.
  • Extension methods.
  • Grouping related constants and the enum keyword.

This chapter assumes some familiarity with object-oriented principles. An introduction to these principles is given in Appendix 1. In Chapter 4 we continue our discussion of C# classes by introducing interfaces, polymorphism and delegates.

3.2 THE STRUCTURE OF A CLASS: METHODS AND DATA

The essential components of classes are data and methods. The main method categories in C# are:

  • Constructors: methods that are responsible for the creation of objects (class instances). The name of a constructor is the same as the name of its class and method overloading is applicable; in other words, we can create multiple constructors for a given class. Special constructors are the default constructor – that has no input argument – and the copy constructor whose input argument is an object of the same type. Constructors are responsible for the initialisation of the class member data and they have no return types.
  • Selector methods: These are methods that do not modify ...

Get C# for Financial Markets 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.