Object-Oriented Programming For Absolute Beginners in C#!

Object-Oriented Programming For Absolute Beginners in C#!

Learn OOP in C# from scratch

Hello ! Are you interested in software development and programming with C#? This article is for you!

In this blog post, I will try to introduce you to the most important concepts of object-oriented programming in the C# language. If you are new to C#, you can read my article : Learn C# from scratch for absolute beginners. (hashnode.dev) which is an in-depth introduction to programming with C#.

Introduction to OOP

OOP stands for object-oriented programming, this is a comprehensive tutorial for C# beginners on object-oriented programming, the objective of this tutorial is to give you an insight into object-oriented programming and help you understand its basics through practical examples.
In this tutorial, we will cover the following concepts :

  • What is OOP?

  • Class vs Object.

  • Attributes vs Methods.

  • Inheritance

If you like this article, don't forget to follow me to receive more programming articles! If you have any questions, feel free to post them in the comments or you can contact me personally.

Requirements

  • Basic understanding of C# language

  • Visual studio installed with C# and .NET

What Is Object-Oriented Programming

Object-oriented programming is an approach to modelling real-world elements, such as players in a game or employees in a company. A simple example of an object is a car with properties such as colour, speed, brand and weight, and methods such as increase or decrease speed, stop, turn right or left, reverse...
An object has two characteristics:

  • attributes

  • behaviour

Class and Object

We can define a class as a blueprint for the object. We can think of it as a sketch of a car containing all the details about the car. When the class is defined, only the description for the object is defined. Therefore, no memory or storage is allocated. Meanwhile, an object (instance) is an instantiation of a class, an object is a car with red colour for example and 300km/h as the maximum speed.
Here I have created a simple visualization of the difference between a class and an object:

If the concept of OOP is not yet clear in your mind, don't worry! The following practical example will make it easier for you.

OOP In C#

Attributes

The attributes are a characteristic of an object.
Let's take the previous example and define a class in C# called Car, to define a class in C# we use the class keyword as follows:

using System;
namespace Demo
{
    class Car
    {

    }

    internal class Program
    {
        static void Main(string[] args)
        {


            Console.ReadLine();
        }
    }
}

Now let's define our class with some attributes :

using System;
namespace Demo
{
    class Car
    {
        public string color;  
        public string brand;
        // public = we can access this outside of the class
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Console.ReadLine();
        }
    }
}

Now, to create an instance of the class car, we write the following line in the main function :

Car car = new Car();
car.brand = "audi";
car.color = "black";

Methods

Methods are functions defined inside the body of a class. They are used to define the behaviors of an object.
Now, let's define a method called changeMaxSpeed() that thakes one parameter pMaxSpeed and assign it the the maxSpeed attribute :

using System;


namespace Demo
{

    class Car
    {
        public string color;
        public string brand;
        public int maxSpeed;

        /// <summary>
        /// A method to change the max speed of the car
        /// </summary>
        /// <param name="pMaxSpeed"></param>
        public void changeMaxSpeed(int pMaxSpeed)
        {
            maxSpeed = pMaxSpeed;
        }

        /// <summary>
        /// A method to show the details of the car 
        /// </summary>
        public void ShowDetails()
        {
            Console.WriteLine($"Brand : {brand} 
                                Color : {color} 
                                Max speed : {maxSpeed}");
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {

            Car car = new Car();
            car.brand = "audi";
            car.color = "black";
            car.maxSpeed = 200;

            car.changeMaxSpeed(250);

            car.ShowDetails();
            Console.ReadLine();
        }
    }
}

The output of this code is :

Brand : audi Color : black Max speed : 250

Constructor

Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read. Constructors - C# programming guide | Microsoft Learn

The constructor the initializer method and it is called when an object is instantiated, for example if we want to create two cars, each with specific properties, we will create two objects of the previous class, one called car1 and the other car2 for example :

using System;
namespace Demo
{
    class Car
    {
        public string color;
        public string brand;
        public int maxSpeed;

        /// <summary>
        /// The class constructor
        /// </summary>
        /// <param name="color"></param>
        /// <param name="brand"></param>
        /// <param name="maxSpeed"></param>
        public Car(string color, string brand, int maxSpeed)
        {
            this.color = color;
            this.brand = brand;
            this.maxSpeed = maxSpeed;
        }

        /// <summary>
        /// A method to change the max speed of the car
        /// </summary>
        /// <param name="pMaxSpeed"></param>
        public void changeMaxSpeed(int pMaxSpeed)
        {
            maxSpeed = pMaxSpeed;
        }

        /// <summary>
        /// A method to show the details of the car 
        /// </summary>
        public void ShowDetails()
        {
            Console.WriteLine($"Brand : {brand} 
                                Color : {color} 
                                Max speed : {maxSpeed}");
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Car car1 = new Car("black", "audi", 200);
            Car car2 = new Car("Blue", "BMW", 300);

            car1.ShowDetails();
            car2.ShowDetails();
            Console.ReadLine();
        }
    }
}

Note that we can have multiple constructors inside the same class, for example, we may want to initialize a class from a text file or a database.

Data encapsulation & access modifiers

Access modifiers specify the level of accessibility of a given method or attribute, the public modifier specifies that the member is accessible outside the class, for example, if a class has a color attribute, when we instantiate the class and create an object called car1, we can access the color attribute by the following syntax: car1.color, however, for the private access modifier, we cannot access a member outside the class.

The main two access modifiers that you need to know as a beginner are public and private, however if you are interested in the others, here are some more details taken from Access Modifiers - C# Programming Guide | Microsoft Learn

  • public: The type or member can be accessed by any other code in the same assembly or another assembly that references it. The accessibility level of public members of a type is controlled by the accessibility level of the type itself.

  • private: The type or member can be accessed only by code in the same class or struct.

  • protected: The type or member can be accessed only by code in the same class, or in a class that is derived from that class.

  • internal: The type or member can be accessed by any code in the same assembly, but not from another assembly. In other words, internal types or members can be accessed from code that is part of the same compilation.

  • protected internal: The type or member can be accessed by any code in the assembly in which it's declared, or from within a derived class in another assembly.

  • private protected: The type or member can be accessed by types derived from the class that are declared within its containing assembly.

  • Summary table

    | Caller's location | public | protected internal | protected | internal | private protected | private | | --- | --- | --- | --- | --- | --- | --- | | Within the class | ✔️️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | | Derived class (same assembly) | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ❌ | | Non-derived class (same assembly) | ✔️ | ✔️ | ❌ | ✔️ | ❌ | ❌ | | Derived class (different assembly) | ✔️ | ✔️ | ✔️ | ❌ | ❌ | ❌ | | Non-derived class (different assembly) | ✔️ | ❌ | ❌ | ❌ | ❌ | ❌ |

Inheritance

To understand the concept of inheritance, we will take a simple example, Imagine we have a class called vehicle and our previous class called car, when we first created the class vehicle as follows :

using System;


namespace Demo
{

    class Vehicle
    {   
        public string color;
        public string brand;
        public int maxSpeed;

        public void changeMaxSpeed(int pMaxSpeed)
        {
            maxSpeed = pMaxSpeed;
        }

        public Vehicle(string color, string brand, int maxSpeed)
        {
            this.color = color;
            this.brand = brand;
            this.maxSpeed = maxSpeed;
        }

        public void ShowDetails()
        {
            Console.WriteLine($"Brand : {brand} Color: { color} Max speed : { maxSpeed}");
        }
    }


    class Car : Vehicle
    {
        public Car(string color, string brand, int maxSpeed) : base(color, brand, maxSpeed)
        {
        }
    }

    class Truck : Vehicle
    {
        public Truck(string color, string brand, int maxSpeed) : base(color, brand, maxSpeed)
        {
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {

            Car car1 = new Car("black", "audi", 200);
            Car car2 = new Car("Blue", "BMW", 300);

            Truck truck1 = new Truck("black", "audi", 200);


            truck1.ShowDetails();
            car2.ShowDetails();
            Console.ReadLine();
        }
    }
}

Now when we will create the class Car, we want our class to inherit from the previous class, meaning that we don't want to define the previous attributes and methods again. then, we can access the variables and methods of the parent class
So basically, Inheritance is the capability of one class to derive or inherit the properties from another class. The class that derives properties is called the child class and the class from which the properties are being derived is called the parent class.

Finally ...

This is a very simple tutorial for absolute beginners and is intended to give you some basics about OOP, in the next tutorials we will try to cover more advanced topics. Like, leave a Comment and follow for more! Thank you very much!

Related Articles :

Here are some of my articles that cover the basics of C# and other OOP concepts in python and c# :

Did you find this article valuable?

Support Interrupt101 by becoming a sponsor. Any amount is appreciated!