Classes & Objects

Lesson 25
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

In C#, a class is a blueprint for creating objects, while an object is an instance of a class. Classes define the attributes and behaviors of an object.

Here is an example of a simple class:

public class Car
{
    public string Make;
    public string Model;
    public int Year;

    public void Start()
    {
        Console.WriteLine("The car has started.");
    }

    public void Stop()
    {
        Console.WriteLine("The car has stopped.");
    }
}

In this example, we have created a class called Car. The Car class has three public attributes - Make, Model, and Year - which can be accessed and modified by code outside of the class. The Car class also has two methods - Start and Stop - which are public and can be called by code outside of the class.

We can create objects of the Car class by instantiating them with the new keyword:

Car myCar = new Car();
myCar.Make = "Honda";
myCar.Model = "Civic";
myCar.Year = 2022;

myCar.Start();
myCar.Stop();

In this example, we’ve created an object of the Car class called myCar. We’ve set the Make, Model, and Year attributes of myCar to “Honda”, “Civic”, and 2022, respectively. We’ve then called the Start and Stop methods of myCar.

We can also create multiple objects of the same class:

Car car1 = new Car();
car1.Make = "Ford";
car1.Model = "Mustang";
car1.Year = 2021;

Car car2 = new Car();
car2.Make = "Chevrolet";
car2.Model = "Corvette";
car2.Year = 2023;

In this example, we’ve created two objects of the Car class called car1 and car2. We’ve set the attributes of each object to different values.

Classes and objects are a fundamental part of object-oriented programming and are used extensively in C# applications. They allow for encapsulation of data and behavior, which can help simplify code and improve maintainability.