C: Classes¶
Concepts in Action¶
Using classes allows you to organize their code logically and modularly. Each class represents a distinct game entity or concept, making the code easier to understand, maintain, and debug. It promotes code reusability and extensibility, as you can create new instances of classes with different parameters to add variety to their game.
Introduction¶
In the realm of object-oriented programming, classes are like blueprints that define how to create an object. If we take the example of a cat, a class would define common characteristics and behaviors that all cats share.
Imagine if every time you wanted to create a cat in your code, you had to define what a cat is from scratch. You’d have to specify the color, the number of legs, and the sound it makes every single time you create a new cat. This would quickly become repetitive and inefficient.
In object-oriented programming, we avoid this inefficiency by defining a blueprint for what a cat is – this is what we call a class. A class groups behavior and data that belongs together and defines and characterize any possible ‘Cat’ we may want to create in our program.
For instance, all cats have a color and a number of legs, and all cats can meow, but they might have a different name, number of legs and a different color. This in turn defines how the cat might behave.
Prior C# knowledge required¶
Understanding of C# Types and C# Functions is recommended before delving into this topic.
Definition¶
In C#, a class is a user-defined blueprint or prototype from which objects are created. It represents a set of properties (variables) and methods (functions) that an object of this class will have.
Here is a simple class in C#:
public class Cat
{
public string color;
public int numberOfLegs;
public void Meow()
{
Debug.Log("Meow!");
}
}
In C#, initialization is the process of assigning a value to a variable when you create it. For a Cat object, this might involve specifying its color and numberOfLegs properties. Let’s put this into practice. How do you actually create a new Cat object from this class?
public class Cat
{
public string color;
public int numberOfLegs;
public Cat(string color, int numberOfLegs)
{
this.color = color;
this.numberOfLegs = numberOfLegs;
}
public void Meow()
{
Console.WriteLine("Meow!");
}
}
Cat tuxedoCat = new Cat("black and white", 4);
Cat threeLeggedCat = new Cat("orange", 3);
In this Cat class, we’ve added a constructor method (it has the same name as the class). The constructor is a special method that gets called when you create a new object from the class. It’s where you can set up your object with any initial state or behavior it needs. Here, the constructor takes color and numberOfLegs as parameters, and assigns them to the corresponding properties of the Cat object.
Using constructors
to initialize objects simplifies our code and makes it more robust:
Simplicity: Constructors allow us to set up an object with all the required initial values in one place. This makes it easier to understand how an object is created and what its initial state is.
Robustness: By enforcing that initial values must be provided when an object is created, we can help prevent bugs caused by uninitialized properties.
Differences to JavaScript¶
In JavaScript, classes are primarily added for readability on top of JavaScript’s existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript. In contrast, C# is a class-based object-oriented language, and classes are at the heart of most everything you do in C#. Javascript uses the constructor keyword to define a method that is automatically called when an instance of a class is created, in C# this is a special function that is the name of the class, without any return type.
class Cat {
constructor(color, numberOfLegs) {
this.color = color;
this.numberOfLegs = numberOfLegs;
}
meow() {
console.log('Meow!');
}
}
let tabbyCat = new Cat('Brown', 4);
let threeLeggedCat = new Cat('Black', 3);
Similarities to JavaScript¶
The basic syntax for creating classes, creating methods, and instantiating objects is somewhat similar in both JavaScript and C#. Both use the class keyword to define a class, and the new keyword to create an instance of a class.
In both languages, methods can be added to a class to define the behaviors that an object created from that class can do.
Examples¶
public class Vehicle
{
public string color;
public int numberOfWheels;
public Vehicle(string color, int numberOfWheels)
{
this.color = color;
this.numberOfWheels = numberOfWheels;
}
public void Drive()
{
Debug.Log("The" + color + " vehicle with " + numberofWheels + " wheels is driving.");
}
}
// Usage:
Vehicle car = new Vehicle("red", 4);
car.Drive(); // Output: The red vehicle with 4 wheels is driving.
Vehicle motorbike = new Vehicle("blue", 2);
motorbike.Drive(); // Output: The blue vehicle with 2 wheels is driving.
Key Takeaways¶
-
A class in C# is a blueprint for creating objects. It defines a set of properties and function that are common to all objects of that class.
-
Each instance of a class can have different values for its properties. For instance, in the Vehicle class, every vehicle has a color and a number of wheels, but the specific color and number of wheels can differ from vehicle to vehicle.
-
You can define functions in a class to make the objects of that class “do” things. In the Vehicle class, we defined a Drive function which makes a vehicle “drive”.
-
When calling a function, the behavior may vary based on the object’s properties. When we call Drive on different instances of the Vehicle class, the output changes based on the color and number of wheels of each vehicle.
-
Classes in C# provide a way to create more complex data types, encapsulating related data and behavior into one package. This makes your code more organized and easier to understand.
-
Constructors in C# allow for the initialization of an object’s properties when the object is created. This can provide more control over how an object is set up and can ensure that an object is in a valid state from the moment it’s created. For instance, in the Vehicle class, we defined a constructor that takes a color and a number of wheels, which are then used to set the Color and NumberOfWheels properties of a new Vehicle object. This ensures that every Vehicle object has a color and a number of wheels as soon as it’s created.
Further Reading¶
- The official Microsoft documentation on classes
- W3schools on Object Oriented Programming
- C# classes - Tutorialsteacher