Contents

Classes and Objects

By completing the Katas, you’ve written a significant amount of C# code. However, we haven’t yet discussed one of C#’s most powerful features - Object Oriented Programming. So what I’m saying is we haven’t even scratched the surface of what C#’s really about! In this chapter we’re going to discuss Object Oriented Programming so we can start coding like a pro.

Object oriented programming

There are many kinds of programming languages out there, and they all behave in vastly different ways. In order to make sense of things, the software community has up with many terms and definitions in order to categorize programming languages, and their features.

The C# programming language is considered to be an ‘Object-Oriented’ (OO) language. This means it works by storing data and code ‘objects’.

An object is something that groups data and code together. The key is that the data and code inside an object are closely linked.

An object’s code is stored inside methods, and it’s data is stored inside fields. Objects usually represent something ‘real’, like a user account on a website, or a product in a physical shop. Relating data and code to real-life things via objects is one of the big advantages of OO, as it generally makes things easier to understand.

Objects are usually defined by something called a class. A class can be thought of as a template for an object. Classes describe the fields and methods an object ought to have. A class also contains code that knows how to create a new object, known as a constructor.

A class is like a blueprint for a building. The blueprint explains what the building looks like - its dimensions and proportions. However, the blueprint is not the building - it just describes what the building ought to look like.

An object is like a building produced by following the blueprint. It looks exactly like what the blueprint says it ought to look like. You can have many buildings produced by the same blueprint - but no two buildings produced by the blueprint are the same - each one is distinct in it’s own right.

So, likewise, an object is produced by following the blueprint defined in the class. The object looks exactly like what the class says it ought to look like. The object is not the class, and the class is not the object. You can have many objects created by the same class - and each object is distinct.

More examples will definitely be needed to explain this more clearly.

Objectification

Say you were creating a program for an e-commerce store. Your program would need some sort of data structure to represent the products in stock. You know that each product has a name, and a price.

Using OO, you decide that each individual product will be represented by an object. However, before you create objects to represent products, you need to create a class which defines the product objects. Since each product has a name and a price, you need to create a class that defines ‘name’ and ‘price’ as fields.

Before writing any C# code, you decide to use pseudo-code to help clarify things.

In pseudo-code, the Product class looks like this:

Class Product
    Name: string
    Price: int

You realize that you also need a way of printing all the products you have in inventory so you can see what’s in stock. Therefore you decide you need another class that can create an object that knows how to print out the inventory.

You decide the class will be called InventoryPrinter. The InventoryPrinter will have an array of products as one of it’s fields. It’ll also have a method that prints the inventory to the Standard Output. The pseudo code for the inventory printer class looks like this:

Class InventoryPrinter
    Products: Product[]

    PrintInventory():
        for each product in Products
            StandardOutput.Write(product.Name)
            StandardOutput.Write(product.Price)
        loop
    }

In the store you want to sell printers and CDs. You imagine a few objects that are created from the Product class to help:

{
    Name = "Guns & Roses"
    Price = 900
}
{
    Name = "UltraTech Printer 2000"
    Price = 12000
}

These objects are defined by the Product class, which means they are considered to be instances of Product.

You then write a simple program in pseudo code that creates Product objects and prints the inventory using the InventoryPrinter:

Create new Product called gunsAndRosesCd
Create new Product called printer

Create new InventoryPrinter called myInventoryPrinter
    With gunsAndRosesCd and printer

InventoryPrinter.PrintInventory()

You imagine the output to be something like:

Guns & Roses
900
UltraTech Printer 2000
12000

Classes and objects in C#

Let’s write the above code in C# for real. The Product class looks like this:

class Product {
    public string Name;
    public int Price;

    public Product(string name, int price) {
        Name = name;
        Price = price;
    }
}

Let’s break this down, line by line:

class Product

This is the beginning of the class definition. It says we’re defining a class called Product.

public string Name;
public int Price;

At the top of the class, we declare two strings - Name and Price. These are the fields of the class. Notice the public keyword before each field is defined. This means that these fields will be visible to code that uses Product objects. We’ll see more of what that means later.

public Product(string name, int price) {
    Name = name;
    Price = price;
}

This is the constructor. It’s similar to a method, but notice that it has the same name as the class, and no return type. The constructor has two arguments, name and price. We assign them to the fields, Name and Price. Capitalizing the first letter is enough for C# to work out the arguments and the fields are different things.

So much for Product! Now for InventoryPrinter:

class InventoryPrinter {
    private Product[] Products;

    public InventoryPrinter(Product[] products) {
        Products = products;
    }

    public void PrintInventory() {
        for (int i = 0; i < products.Length; i++) {
            Product product = products[i];
            Console.WriteLine(product.Name);
            Console.WriteLine(product.Price);
        }
    }
}

Similarly to Product, InventoryPrinter has a field called Products, of type Product array. However this time it’s private. This means that code outside of objects of this class won’t be able to see Products. This is good because Products will only ever be needed inside InventoryPrinter.

Next, we have a method called PrintInventory. It works by using a for loop to iterate through the Product array. In each iteration it prints out the Name and Price of the product.

Remember how we used the public keyword for Name and Price on Product? That means that InventoryPrinter can look at these fields inside the Product object.

Notice I’ve used products.Length in the for loop. Length is a property of array objects. Length tells you how many items are in the array. It’s very useful when writing for loop conditions!

Putting it all together

The program would then look like this:

Product cd = new Product("Guns & Roses", 900);
Product printer = new Product("UltraTech Printer 2000", 12000);
Product[] productsArray = new Product[2];

productsArray[0] = cd;
productsArray[1] = printer;

InventoryPrinter inventoryPrinter = new InventoryPrinter(productsArray);
inventoryPrinter.PrintInventory();

Again let’s take it line by line to see what’s happening:

Product cd = new Product("Guns & Roses", 900);
Product printer = new Product("UltraTech Printer 2000", 12000);

Two new Product objects are created, cd and printer. We use the new keyword followed by the name of the class to say that we’re creating a new instance of that class.

We use the constructor of a class when newing up an object. Product’s constructor asks for a name and a price. So, we provide them both in the constructor. The price is in pence, which is why the numbers are so high - e.g. 900 is £9.00 and so on.

Product[] productsArray = new Product[2];

This is a simple variable declaration - we create an array of Products called productsArray, of size 2.

productsArray[0] = cd;
productsArray[1] = printer;

We assign the 0th and 1st indexes of the array to the Product objects we just created.

InventoryPrinter inventoryPrinter = new InventoryPrinter(productsArray);

I new up an InventoryPrinter object, this time initializing it with productsArray.

inventoryPrinter.PrintInventory();

I call PrintInventory on the inventoryPrinter object to print the inventory to the screen.

In the next Kata 8 you’ll see how to use classes and objects to improve the quiz game even more.

Copyright Mikiel Agutu 2019