Classes

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 that 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 name;}
  }
  // property
  public double Gravity {
    get {return gravity;}
  }
}

Next, we define the Astronaut class. As with the Planet class, we first define our data members. Here an astronaut has two fields: the astronaut’s fitness and the current planet the astronaut is on. We then provide a constructor, which initializes ...

Get C# Language Pocket Reference 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.