Classes and objects in C#: fields, constructors and properties
Lesson 7 of 15 · C#
A class is a description (a template) of a kind of data: what data it has and what it can do. An object is a concrete instance of a class, created with the new operator. This lesson covers fields, constructors, object methods, properties and static members – the basis of object-oriented programming in C#.
Before you start: required prior knowledge – methods, arrays. How to learn: type in and run every example, and solve the tasks at the end on your own first; open the hint and the solution only after that. All programs are C# console applications (.NET 8 or later, without "top-level statements"); every one has been tested and gives the output shown.
Class, object and constructor
using System;
class Student
{
// fields – the data every object has
public string Name;
public int Grade;
// constructor – called when the object is created, its name is the same as the class name
public Student(string name, int grade)
{
Name = name;
Grade = grade;
}
// an object method – works with the data of this particular object
public void Introduce()
{
Console.WriteLine($"I am {Name} and I am in grade {Grade}.");
}
}
class Program
{
static void Main()
{
Student s1 = new Student("Anna", 7);
var s2 = new Student("Mark", 8);
s1.Introduce();
s2.Introduce();
s2.Grade = 9; // a public field can be changed from outside
Console.WriteLine($"{s2.Name} is now in grade {s2.Grade}.");
}
}
Every object has its own field values: s1.Name and s2.Name are different pieces of data. The word public means that the member is available outside the class too, and private (the default) that it is available only inside the class.
Encapsulation and properties
An object's data is usually hidden (private), and it is accessed from outside in a controlled way – through methods and properties. A property looks like a field, but it has get (reading) and set (writing) parts in which the value can be checked.
using System;
class Account
{
private decimal balance; // a private field – not accessible from outside
public string Owner { get; } // a read-only property (set by the constructor)
public decimal Balance => balance; // a computed read-only property
public Account(string owner, decimal initial)
{
Owner = owner;
balance = initial;
}
public void Deposit(decimal amount)
{
if (amount <= 0)
{
Console.WriteLine("The amount must be positive.");
return;
}
balance += amount;
}
public bool Withdraw(decimal amount)
{
if (amount > balance) return false; // not enough money – the balance does not change
balance -= amount;
return true;
}
}
class Program
{
static void Main()
{
var a = new Account("Helen", 1000);
a.Deposit(500);
a.Deposit(-20);
Console.WriteLine(a.Withdraw(2000) ? "Withdrawn" : "Insufficient funds");
Console.WriteLine(a.Withdraw(300) ? "Withdrawn" : "Insufficient funds");
Console.WriteLine($"{a.Owner}: {a.Balance} dinars");
// a.balance = 1000000; // error: the field is private
}
}
Now the account balance cannot be changed "against the rules" – only through Deposit and Withdraw. This is called encapsulation.
using System;
class Rectangle
{
private double width = 1;
public double Width
{
get { return width; }
set { width = value > 0 ? value : 1; } // value = the value being written
}
public double Height { get; set; } = 1; // an auto-property with an initial value
public double Area => Width * Height; // a computed property
public override string ToString() => $"Rectangle {Width} x {Height}, A = {Area}";
}
class Program
{
static void Main()
{
var r = new Rectangle { Width = 4, Height = 2.5 }; // object initializer
Console.WriteLine(r); // ToString() is called
r.Width = -3; // an invalid value
Console.WriteLine(r.Width);
Console.WriteLine(r);
}
}
The ToString() method determines how an object is printed. The word override means that we are changing an existing method that every class inherits from the class object – more about this in the lesson on inheritance.
Static members and an array of objects
A static field or method (static) belongs to the class, not to an individual object – there is only one value, shared by all objects. It is used through the class name: Product.ProductCount, just like Math.Sqrt.
using System;
class Product
{
public static int ProductCount = 0; // shared by all objects
public string Name { get; }
public decimal Price { get; set; }
public Product(string name, decimal price)
{
Name = name;
Price = price;
ProductCount++;
}
}
class Program
{
static void Main()
{
Product[] basket =
{
new Product("Notebook", 120),
new Product("Pencil", 45.5m),
new Product("Ruler", 80)
};
decimal total = 0;
foreach (var p in basket)
{
Console.WriteLine($"{p.Name,-9}{p.Price,8:F2}");
total += p.Price;
}
Console.WriteLine($"{"Total",-9}{total,8:F2}");
Console.WriteLine($"Products created: {Product.ProductCount}");
}
}
A variable holds a reference to an object
A variable of a class type does not contain the object itself, but a reference (the address) of the object. The assignment p2 = p1 does not create a new object, and == for classes checks whether it is the same object.
using System;
class Point
{
public int X, Y;
public Point(int x, int y) { X = x; Y = y; }
public override string ToString() => $"({X}, {Y})";
}
class Program
{
static void Main()
{
var p1 = new Point(1, 2);
var p2 = p1; // p2 points to the SAME object
p2.X = 10;
Console.WriteLine(p1); // the change is visible through p1 too
var p3 = new Point(10, 2); // a new object with the same values
Console.WriteLine(p1 == p2);
Console.WriteLine(p1 == p3);
}
}
Practice tasks
Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.
TASK 01Difficulty: medium
Fraction
Write a class Fraction with the properties Numerator and Denominator. The constructor reduces the fraction immediately, the method Add returns a new fraction (the sum), and ToString returns the notation a/b. Read two fractions (four positive numbers on one line: the numerator and denominator of the first, then of the second) and print their sum.
Example 1
Input
1 6 1 3
Output
1/2
Example 2
Input
3 4 5 6
Output
19/12
Hint
Reducing: divide the numerator and the denominator by their GCD. The sum: a/b + c/d = (a·d + c·b) / (b·d) – the constructor reduces it by itself.
Solution (C#)
using System;
class Fraction
{
public int Numerator { get; }
public int Denominator { get; }
public Fraction(int numerator, int denominator)
{
int d = Gcd(numerator, denominator);
Numerator = numerator / d;
Denominator = denominator / d;
}
static int Gcd(int a, int b) => b == 0 ? a : Gcd(b, a % b);
public Fraction Add(Fraction f) =>
new Fraction(Numerator * f.Denominator + f.Numerator * Denominator, Denominator * f.Denominator);
public override string ToString() => $"{Numerator}/{Denominator}";
}
class Program
{
static void Main()
{
int[] x = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
var a = new Fraction(x[0], x[1]);
var b = new Fraction(x[2], x[3]);
Console.WriteLine(a.Add(b));
}
}
TASK 02Difficulty: medium
Cinema reservations
Write a class Hall that remembers the taken seats (a bool[,] matrix) and has a method Reserve(row, seat) that returns OK, TAKEN or DOES NOT EXIST, and a property Free. Input: the number of rows and the number of seats in a row, then the number of reservations k and k lines with a pair row seat (numbered from 1). Print the answer for each reservation, then the number of free seats.
Example
Input
3 4
5
1 1
2 3
1 1
4 1
3 4
Output
OK
OK
TAKEN
DOES NOT EXIST
OK
Free: 9
Hint
The row and seat numbered from 1 are converted into indexes from 0 (row - 1). First check the bounds, then whether the seat is taken. Make Free a property with a private set, which decreases with every successful reservation.
Solution (C#)
using System;
class Hall
{
private readonly bool[,] taken;
public int Free { get; private set; }
public Hall(int rows, int seats)
{
taken = new bool[rows, seats];
Free = rows * seats;
}
public string Reserve(int row, int seat)
{
if (row < 1 || row > taken.GetLength(0) || seat < 1 || seat > taken.GetLength(1))
return "DOES NOT EXIST";
if (taken[row - 1, seat - 1])
return "TAKEN";
taken[row - 1, seat - 1] = true;
Free--;
return "OK";
}
}
class Program
{
static void Main()
{
int[] rs = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
var hall = new Hall(rs[0], rs[1]);
int k = int.Parse(Console.ReadLine());
for (int i = 0; i < k; i++)
{
int[] r = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
Console.WriteLine(hall.Reserve(r[0], r[1]));
}
Console.WriteLine($"Free: {hall.Free}");
}
}
Common mistakes and tips
The name of the constructor is the same as the name of the class and it has no return type (not even void).
Keep fields private, and open to the outside only what is needed – properties and methods.
Without new there is no object: a variable of a class type with no assignment has the value null.
A static member is used through the class name, not through an object.
Check your knowledge
Open the quiz
Classes and objects in C#
1. What does the new operator create?
2. When is the constructor called?
3. What is the set part of a property for?
4. After var p2 = p1; p2.X = 10; what is p1.X (Point is a class)?
Podešavanja kolačića
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.