<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. C#
  3. Object-oriented programming
All lessons in this course

Lesson 17 of 60 15 minIntermediate

Classes and objects

Model real things in code: define a class, create objects with new, give them data and behaviour, and understand references.

So far our programs used loose variables: string profile, double length. Real software deals with things: beams, columns, customers, invoices. Each thing has data (what it is) and behaviour (what it can do). Object-oriented programming (OOP) keeps the two together.

WordMeaningReal-world example
ClassA blueprint: describes what data and behaviour things of this kind haveThe drawing and spec sheet for a beam type
ObjectOne actual thing built from the class (an instance)Beam B12 on grid line 3, level 2
FieldA variable that belongs to an objectits length, its profile
MethodA function that belongs to the classcalculate its weight

Defining a class

Beam.cs
public class Beam{    // fields: the data each Beam object carries    public string Profile = "IPE200";    public double Length;            // metres    public double KgPerMetre = 22.4;     // method: behaviour that uses the object's own data    public double Weight()    {        return Length * KgPerMetre;    }     public void Print()    {        Console.WriteLine($"{Profile}, {Length} m, {Weight():F1} kg");    }}

Creating and using objects

Program.cs
Beam b1 = new Beam();       // build an object from the blueprintb1.Length = 6;              // set its fields with the dot operatorb1.Print(); Beam b2 = new Beam();       // a second, independent objectb2.Profile = "IPE300";b2.KgPerMetre = 42.2;b2.Length = 4.5;b2.Print();
Output
IPE200, 6 m, 134.4 kg
IPE300, 4.5 m, 189.9 kg

Each object has its own copy of every field. Changing b2.Length does nothing to b1. Inside a method, a field name like Length means “the Length of the object this method was called on”.

Objects live on the heap; variables hold references

This is the most important idea in this lesson. new builds the object in an area of memory called the heap and returns its address. The variable b1 stores only that reference. Try it:

Interactive

One blueprint, many objects

Create objects with new, change their fields, and copy a reference to see two variables pointing at the same object.

Class (blueprint)
class Beam
  string Profile
  double Length
  double Weight()
Stack: variables
none yet
Heap: objects
empty
The class only describes what a Beam has. No Beam exists until you call new.
References.cs
Beam a = new Beam { Length = 6 };Beam b = a;            // copies the reference: still ONE objectb.Length = 9;Console.WriteLine(a.Length);   // 9 — a and b point to the same Beam Beam c = null;         // c points to nothing// c.Print();          // NullReferenceException at run time
Output
9

The this keyword

Inside a method, this means “the current object”. You need it when a parameter has the same name as a field:

This.cs
public void SetLength(double length){    this.Length = length;   // field = parameter}

Organising classes

  • Put each class in its own file with the same name: Beam.cs.
  • Class names are PascalCase nouns: Beam, SteelGrade, InvoiceLine.
  • A class should represent one idea. If it does many unrelated jobs, split it.
Quick check

After Beam x = new Beam(); Beam y = x; y.Length = 3;, how many Beam objects exist?

Quick check

What is the relationship between a class and an object?

Practice

Create a class Rectangle with fields Width and Height and methods Area() and Perimeter(). Create two rectangles (3×4 and 5×2) and print both areas and perimeters.

Show the solution
Solution.cs
public class Rectangle{    public double Width;    public double Height;     public double Area() => Width * Height;    public double Perimeter() => 2 * (Width + Height);} var r1 = new Rectangle { Width = 3, Height = 4 };var r2 = new Rectangle { Width = 5, Height = 2 };Console.WriteLine($"r1: area {r1.Area()}, perimeter {r1.Perimeter()}");Console.WriteLine($"r2: area {r2.Area()}, perimeter {r2.Perimeter()}");
Output
r1: area 12, perimeter 14
r2: area 10, perimeter 14

Remember

  • A class is a blueprint of data (fields) and behaviour (methods).
  • new creates an object on the heap and returns a reference to it.
  • Assigning an object variable copies the reference, not the object.
  • Using a null reference throws NullReferenceException.
0 of 60 lessons completed