Classes and objects
Model real things in code: define a class, create objects with new, give them data and behaviour, and understand references.
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.
| Word | Meaning | Real-world example |
|---|---|---|
Defining a class
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
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();IPE200, 6 m, 134.4 kg IPE300, 4.5 m, 189.9 kg
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
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:
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 time9
The this keyword
this means “the current object”. You need it when a parameter has the same name as a field:
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.
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
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()}");r1: area 12, perimeter 14 r2: area 10, perimeter 14
Remember
A class is a blueprint of data (fields) and behaviour (methods). newcreates an object on the heap and returns a reference to it.Assigning an object variable copies the reference, not the object. Using a nullreference throwsNullReferenceException.