Basics of Classes in C#

Pin

Welcome to yet another exciting tutorial on C#. We have covered most of the basic concepts. Now it’s the time to move towards more advanced concepts. This article provides a brief introduction to classes in C#. However, before diving into to classes, we first need to understand what object oriented programming is.

Object Oriented Programming (OOP)

OOP is a programming paradigm which models real world objects into software entities. It might sound confusing, but it is extremely straight forward. In the real world, anything that has some properties and can perform some functions is considered an object. Take an example of a race car game. Here a car is itself an object since it has a name, price, etc. and it has functionalities like start, stop, accelerate, etc. Similarly, a person driving a car is also an object. He has a name, age, nationality, etc. Similarly, he can perform functions like sit in the car, get out of the car, change car gears, etc. In a software program, objects are implemented via classes and objects.

Classes in C#

Classes are basically custom types for creating objects. You have already seen primitive data types such as int, string, char, double float etc. Classes are custom types. Classes have member variables, properties, and methods. It is important to note here that a class itself is nothing. It is only a blueprint and has no existence in physical memory. Consider a class as a map of some house. It contains blueprints of what the house will have and how will it look. However, a blueprint has no physical existence on the ground.

To create a class in C#, the keyword “class” is used followed by opening and closing curly brackets. Inside the brackets, you specify the member variables and methods of a class. Take a look at the following example.

class Player
{
    public string playerName;
    public int playerAge;

    public void StartGame()
    {
        Console.WriteLine("Game has been started.");
    }

    public void EndGame()
    {
        Console.WriteLine("Game has been ended");
    }
}

In the above code snippet, a class named Player is created. The class contains two member variables: PlayerName of type string and PlayerAge of type int. Similarly, a couple of methods, StartGame and EndGame are also defined inside the class.

At this point, this class has no existence in computer’s memory. Objects are used to create a physical memory for class’s member variables and method.

Objects in C#

An object in C# is an in-memory representation of a class. In the blueprint to house relationship, an object is a house. It has a physical existence in memory, and it can be used to call methods defined inside a class. One class can have multiple objects just like one blueprint can be used to build multiple houses. Take a look at the following example to see how objects are created in C#.

Player player1 = new Player(); // Creating object of player class
player1.playerName = "John"; // Accessing member variables
player1.playerAge = 22;
player1.StartGame(); // Accessing member methods

Take a careful look at the above code. To create an object of any class you have to use “new” keyword followed by the class name. This returns the reference to the object. The reference can be stored in a class type variable which is player1 in the above code.

Using this reference, you can access all the public members and methods of a class. To access a member variable or a method, write the object name followed by dot operator and the name of the variable or method. For instance, if you want to access StartGame() method via the player1 object, you will write ‘player1.StartGame()”.

Constructor in C#

A constructor is a special method which is used to initialize member variables at the time of initialization of an object of a class. The constructor method has the same name as the name of the class and it has no return type (not even void). Take a look at the following example to see how the constructor works.

class Player
{
    public string playerName;
    public int playerAge;

    public Player()
    {
        playerName = "John";
        playerAge = 10;
    }

    public void DisplayVariables()
    {
        Console.WriteLine(PlayerName + " | " + PlayerAge);
    }
}

Take a look at the code in above snippet. Here we have defined a constructor for the Player class. Notice, this constructor doesn’t have any return type. Inside the constructor, we assign some values to the PlayerName and PlayerAge variables. The class also contains a method which displays these values on the console. Now, if you create the object of the Player class and call DisplayVariable method on that object, you will see that “John” and 10 is displayed on the console. These were the values that were assigned to PlayerName and PlayerAge variables via the constructor.

It is important to note here that when you create an object of the class you are calling the constructor of the class. If you do not define any customized constructor, the default constructor is called.

You can also pass parameters to constructors. This way you can initialize class variables with the values you pass to the constructor at the time of initialization of the object. Take a look at the following example.

class Player
{
    public string PlayerName;
    public int PlayerAge;

    public Player(string name, int age)
    {
        PlayerName = name;
        PlayerAge = age;
    }

    public void DisplayVariables()
    {
        Console.WriteLine(PlayerName + " | " + PlayerAge);
    }
}

In the above code, the constructor accepts two parameters. These parameters are used to initialize the PlayerName and PlayerAge variables. Now, when you want to create an object of the Player class you have to pass a string and an integer type variable to the constructor. Take a look at the following code to see how parameterized constructors are called.

Player player1 = new Player("James", 20); // Passing arguments to constructor
player1.DisplayVariables();

Player player2 = new Player("Mike", 25);
player2.DisplayVariables();

In the above code, two objects i.e. player1 and player2 of class Player is initialized. If you look at the player1 object here “James” and 20 are being passed to the parameterized constructor. Similarly, for object player2, “Mike” and 25 are being passed to the parameterized constructor. Now if you call DisplayVariables method on player1 and player2 objects you shall see the values you passed via the constructor, on the console.

Finally, you can overload your constructors. This means that you can have multiple constructors within a class. The constructor that will be called when you create an object will be the one whose parameters match with the parameters in the call to the constructor. Take a look at the following example to see how constructors are overloaded.

class Player
{
    public string PlayerName;
    public int PlayerAge;

    public Player(string name)
    {
        PlayerName = name;
    }
    public Player(string name, int age)
    {
        PlayerName = name;
        PlayerAge = age;
    }

    public void DisplayVariables()
    {
        Console.WriteLine(PlayerName + " | " + PlayerAge);
    }
}

In the above code, you can see that there are two constructors: one with one two parameters and the other with one parameter. The following code snippet shows how player1 and player2 objects can be initialized by calling two different constructors.

Player player1 = new Player("James", 20); // Calling constructor with 2 parameters
player1.DisplayVariables();

Player player2 = new Player("Mike"); // Calling constuctor with 1 parameter
player2.DisplayVariables();

In the above code, player1 calls the constructor with two parameters and player2 calls the constructor with one parameter.

In this article, I explained what object oriented programming is and what are classes and objects. We also studied different types of constructors. I hope you found this article helpful in learning about classes in C#, if so, be sure to check out my C# Roadmap.