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 ]? classclass-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 ...
Get C# in a Nutshell, Second Edition 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.