Thursday, 2 January 2025

Understanding Classes in C#

Introduction

In C# class is a blueprint for creating objects. It contains data (properties) and behaviour (methods). We can build multiple objects with distinct properties and methods using classes without having to repeat the code.

Class Syntax: Creating a generic C# Class


public class Car    //car is the class name and Pascal case
{
    public string Model { get; set; }	//properties
    public string Color { get; set; }

    public void Start()					//method
    {
        Console.WriteLine("Car started.");
    }

    public void Stop()					//method
    {
        Console.WriteLine("Car stopped.");
    }
}

A generic class in C# is created using a class keyword followed by class name. Class name, property name, method name must always be Pascal case i.e. Starting letter must be capital case. Class can have different properties and methods. We cannot use the class directly without creating an object. In order to use class we must create an object which is an instance of class.

Creating an object

Once class is created. Object can be creating by instantiating a class with the new keyword. Attributes can be initialized using the dot operator followed by attribute name as shown below.


Car myCar = new Car();
myCar.Model = "Toyota Camry";
myCar.Color = "Red";
myCar.Start();

We can also create an object and initialize attributes directly using { }


Car myCar = new Car
{
    Model = "Toyota Camry",
    Color = "Red"
};

Creating object using constructor

We can also create an object and initialize attributes directly using constructor. Constructor name must be same as class name. Arguments are passed in to the constructor. this keyword is used to link arguments to attributes.


 public class Car
 {
     public string Model { get; set; }
     public string Color { get; set; }

     public Car(string model, string color) //Constructor
     {
         this.Model = model;
         this.Color = color;
     }

     public void Start()
     {
         Console.WriteLine("Car started.");
     }

     public void Stop()
     {
         Console.WriteLine("Car stopped.");
     }
}

Once the constructor is set in a class we can now create an object by directly passing in values to the constructor.


Car myCar = new Car("Mercedes", "blue");
Console.WriteLine(myCar.Model);   //outputs Mercedes
Console.WriteLine(myCar.Color);   //outputs blue

Types of classes

Regular Classes
Abstract Classes
Static Classes
Partial Classses

Regular Class: Needs to be instantiated to create objects. These are the most common type. Examples shown above so far are regular classes.

Abstract Class: Abstract classes are something that exists as generic idea but does not physically exist. For e.g. vehicle can be anything a bike, truck, car, lorry, boat etc. Abstract classes cannot be instantiated directly. They serve as a base class for other classes, providing a common interface. Abstract class can have its own properties and methods. All derived classes must provide their own implementation for these properties and methods. Abstract class is created using abstract keyword.


public abstract class Vehicle
    {
        //Abstract properties and methods (no implementation)
        public abstract string Model { get; set; }
        public abstract string Color { get; set; } 
        public abstract void Start();
        public abstract void Stop();
    }

Once public class is created. We can use this public class as a base class as follows. Each abstract properties and methods must be implemented during this phase.


public class Car : Vehicle
    {
        //implementing abstract properties
        public override string Model { get; set; }
        public override string Color { get; set; }

        //constructor
        public Car(string model, string color)
        {
            Model = model;  //can also write this.Model
            Color = color;  //can also write this.Color
        }
		
        //implementing abstract method
        public override void Start()
        {
            Console.WriteLine($"{Model} car started.");
        }

        public override void Stop()
        {
            Console.WriteLine($"{Model} car stopped.");
        }
    }

    public class Truck : Vehicle
    {
    	//implementing abstract properties
        public override string Model { get; set; }
        public override string Color { get; set; }

        //constructor
        public Truck(string model, string color)
        {
            Model = model;  //can also write this.Model
            Color = color;  //can also write this.Color
        }
		
        //implementing abstract method
        public override void Start()
        {
            Console.WriteLine($"{Model} truck started.");
        }

        public override void Stop()
        {
            Console.WriteLine($"{Model} truck stopped.");
        }
    }

Once the abstract class is created and implemented on its derived class then we can use it by creating objects from the derived class.


internal class Program
    {
        static void Main(string[] args)
        {
            Car myCar = new Car("BMW", "red"); //Car is the derived class
            myCar.Start();		//BMW car started.
            myCar.Stop();		//BMW car stopped.

            Truck myTruck = new Truck("Tesla", "silver");
            myTruck.Start();    // Tesla truck started.
            myTruck.Stop();		//Tesla truck stopped.
        }
    } 

Static Class: Static class cannot be instantiated and can be used directly. All members of a static class must be static. An example is shown below

public static class CarUtilities
{
    public static void displayInformation(Car car)
    {
        Console.WriteLine($"Model: {car.Model}");
        Console.WriteLine($"Color: {car.Color}");
    }
}

Partial Class:Partial class can be defined across multiple files. This is useful for splitting large class definitions into smaller, more manageable parts.



I have also created a youtube video about this topic please feel free to check it out. Happy coding.



No comments:

Post a Comment