O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Creating Types in C#

In this chapter, we cover creation of types in C#, including classes, inheritance, access modifiers, structs, interfaces, and enums.

Classes

               attributes? unsafe? access-modifier?
new? 
[ abstract | sealed ]?
class class-name 
[: base-class | 
 : interface+ | 
 : base-class, interface+ ]?
{ class-members }

In C#, a program is built by defining new types, each with a set of data members and function members. Custom types should form higher-level building blocks that are easy to use, and closely model your problem space.

In this example, we simulate an astronaut jumping on different planets, using three classes: Planet, Astronaut, and Test to test our simulation.

First, let’s define the Planet class. By convention, we define the data members of the class at the top of the class declaration. There are two data members here: the name and gravity fields, which store the name and gravity of a planet. We then define a constructor for the planet. Constructors are function members that allow you to initialize an instance of your class. We initialize the data members with values fed to the parameters of the constructor. Finally, we define two more function members, which are properties that allow us to get the “Name” and “Gravity” of a planet. The Planet class looks like this:

using System; class Planet { string name; // field double gravity; // field // constructor public Planet (string n, double g) { name = n; gravity = g; } // property public string Name { get {return ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required