C# Keywords Tutorial Part 16: class

C# Keywords Tutorial Part 16: class

Programming languages like C# are flexible and support many different paradigms, including object-oriented programming. Classes are the cornerstone of object-oriented programming in C#, allowing programmers to write modular, reusable code. In this article, we’ll examine some code examples and go deeper into C#’s “class” keyword.

What is a class in C#?

In C#, a class is a blueprint for creating objects. A class defines the properties and behaviors of an object, including its data members (variables) and member functions (methods). A class can be thought of as a user-defined data type that encapsulates related data and functionality.

Using the “class” keyword in C#

To create a class in C#, we use the “class” keyword, followed by the name of the class. Here’s an example:

public class Car
{
    public string Make;
    public string Model;
    public int Year;
 
    public void Drive()
    {
        Console.WriteLine("The car is driving.");
    }
}

In this example, we’ve defined a class called “Car.” The “public” keyword before the class name specifies the access modifier, which determines how the class can be accessed from other parts of the program. In this case, the “public” modifier means that the class can be accessed from anywhere in the program.

Inside the class, we’ve defined three data members: “Make,” “Model,” and “Year.” These are properties of a car object that we want to define. We’ve also defined a method called “Drive,” which simulates the car driving.

Creating an object from a class

To use a class, we must first create an object from it. Here’s an example:

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

In this example, we’ve created an object called “myCar” from the “Car” class using the “new” keyword. We’ve then assigned values to the “Make,” “Model,” and “Year” properties of the object. Finally, we’ve called the “Drive” method on the object, which prints out “The car is driving.” to the console.

Inheritance in C# classes

In C#, classes can inherit properties and methods from other classes, using the “inheritance” feature. Here’s an example:

public class SportsCar : Car
{
    public bool IsTurbocharged;
 
    public void Accelerate()
    {
        Console.WriteLine("The car is accelerating.");
    }
}

In this example, we’ve defined a new class called “SportsCar” that inherits from the “Car” class using the “:” symbol. The “SportsCar” class has a new data member called “IsTurbocharged,” and a new method called “Accelerate.” Since it inherits from the “Car” class, it also has access to the “Make,” “Model,” “Year,” and “Drive” properties and methods.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *