C# Part 8: Object-Oriented Programming In C# (Classes and Objects)

C# Part 8: Object-Oriented Programming In C# (Classes and Objects)


Please Subscribe Youtube| Like Facebook | Follow Twitter

Object-Oriented Programming In C#

In this article, we will provide a detailed overview of Object-Oriented Programming In C# (Classes and Objects) and provide examples of how they are used in C# programming.

Object-Oriented Programming (OOP) is a fundamental paradigm in software development, allowing developers to create modular, reusable, and efficient code. C# is a powerful programming language that fully supports OOP principles. In this article, we will explore the key concepts of object-oriented programming in C#, providing detailed explanations and real-world examples to help you grasp the concepts more effectively.

The Pillars of Object-Oriented Programming

OOP is built upon four key pillars: encapsulation, inheritance, polymorphism, and abstraction.

Encapsulation

Encapsulation is the process of bundling data and methods together within a class, hiding internal details and providing controlled access to the object’s state. It promotes data integrity and prevents direct manipulation of internal variables. In C#, you can achieve encapsulation using access modifiers like private, public, and protected.

Inheritance

Inheritance allows the creation of new classes (derived classes) based on existing classes (base classes). The derived classes inherit the properties and behaviors of the base class, promoting code reuse and creating an “is-a” relationship between classes. C# supports single inheritance, meaning a class can inherit from only one base class.

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables code to be written that can work with objects of multiple types, providing flexibility and extensibility. Polymorphism is achieved through method overriding and method overloading.

Abstraction

Abstraction is the process of simplifying complex systems by focusing on essential features and hiding unnecessary details. It allows programmers to create abstract representations of real-world entities or concepts in the form of classes and interfaces. Abstraction provides a high-level view of an object’s behavior and characteristics, without specifying the implementation details. By abstracting away specific implementation details, abstraction promotes modularity, code reusability, and code organization.

We will explain them further in detail in next article. In this article we will explain Classes and Objects.

Classes and Objects

In C#, classes are blueprints or templates that define the structure and behavior of objects. An object is an instance of a class, representing a real-world entity. Let’s explore how to define a class and create objects.

Defining a Class

In C#, a class declaration consists of the class keyword, followed by the class name and a pair of curly braces. You can define fields (variables) and methods (functions) inside the class to specify the object’s behavior.

Example:

public class Car
{
    // Fields, methods, and constructors can be defined here
}

Creating Objects

To create objects in C#, you use the new keyword followed by a call to the class constructor. The constructor initializes the object and sets its initial state. Here’s an example of creating objects of the Car class:

Car myCar = new Car();
Car friendCar = new Car();

In the above code, we created two Car objects named myCar and friendCar using the new keyword. Each object will have its own set of instance variables and methods.

Methods, Fields, and Constructors

Methods in C# are functions defined within a class that perform specific tasks or actions. Fields, also known as instance variables, hold the state or data associated with objects.

You can access methods and fields using the dot notation. The dot notation allows you to access members (methods and fields) of a class or object.

To access a method, you use the following syntax:

objectName.MethodName(arguments);

To access a field, you use the following syntax:

objectName.FieldName;

Constructors in C# are special methods used to initialize objects. They have the same name as the class and do not have a return type. Constructors can take parameters to set initial values for the object’s fields. Constructors can be categorized into two main types: parameterless constructors and parameterized constructors.

Parameterless Constructors

A parameterless constructor, also known as a default constructor, doesn’t take any parameters. It initializes the object with default values or performs basic initialization tasks. If no constructor is explicitly defined in a class, C# automatically provides a default parameterless constructor.

public class Car
{
    public Car()
    {
        // Initialization code or default values
    }
}

Parameterized Constructors

Parameterized constructors in C# accept one or more parameters. They allow you to initialize the object with specific values provided during object creation. These values are passed as arguments to the constructor and used to set the initial state of the object.

public class Car
{
    public Car(string make, string model, int year)
    {
        // Initialization code using provided values
    }
}

You can create objects using the parameterized constructor by passing the required arguments:

Car myCar = new Car("Toyota", "Camry", 2022);

This creates a Car object named myCar with the provided values for the make, model, and year parameters.

Let’s add some methods, fields and constructor to the Car class

Example

public class Car
{
    // Fields
    private string make;
    private string model;
    private int year;

    // Constructor
    public Car(string make, string model, int year)
    {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    // Getter properties
    public string Make
    {
        get { return make; }
    }

    public string Model
    {
        get { return model; }
    }

    public int Year
    {
        get { return year; }
    }

    // Setter properties
    public void SetMake(string make)
    {
        this.make = make;
    }

    public void SetModel(string model)
    {
        this.model = model;
    }

    public void SetYear(int year)
    {
        this.year = year;
    }

    // Other methods
    public void StartEngine()
    {
        Console.WriteLine("Engine started!");
    }

    public void StopEngine()
    {
        Console.WriteLine("Engine stopped!");
    }

    public void CarDetails()
    {
        Console.WriteLine("make: " + make + " model: " + model + " year: " + year);
    }
}

Explanation

The public class Car defines a class named Car. It represents a car object and contains information about the car’s make, model, and year of manufacture. The class has private fields (make, model, and year) that store these details.

The constructor public Car(string make, string model, int year) is used to create an instance of the Car class. It takes the make, model, and year as parameters and initializes the corresponding fields of the object.

The class provides getter properties (Make, Model, and Year) to retrieve the values of the private fields. These properties allow controlled access to the field values.

Additionally, there are setter methods (SetMake, SetModel, and SetYear) that allow updating the values of the private fields.

The class also includes other methods such as StartEngine, StopEngine, and CarDetails, which perform specific actions related to the car object.

Overall, the Car class encapsulates the properties and behavior of a car, allowing you to create car objects, retrieve their details, modify their information, and perform operations specific to cars.

this keyword

In C#, the this keyword is a reference to the current instance of a class. It is primarily used to differentiate between instance variables and parameters or local variables that have the same name.

i.e

this.make = make;

This line assigns the value of the make parameter to the make attribute of the current object. The use of this is necessary when there is a naming conflict between the parameter and the attribute. It explicitly refers to the instance variable make of the current object, distinguishing it from the method parameter.

Now, we can create an instance of the Car class and call its methods. Here’s an example:

using System;
class Program
{
    public static void Main(string[] args)
    {
        Car myCar = new Car("Toyota", "Camry", 2022);

        myCar.StartEngine();
        myCar.CarDetails();
        myCar.StopEngine();
    }
}

To run Code

Step 1: Create a new file named Car.cs and open it in a text editor or an integrated development environment (IDE).

Step 2: Copy and paste the Car class code into the Car.cs file

public class Car
{
    // Fields
    private string make;
    private string model;
    private int year;

    // Constructor
    public Car(string make, string model, int year)
    {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    // Getter properties
    public string Make
    {
        get { return make; }
    }

    public string Model
    {
        get { return model; }
    }

    public int Year
    {
        get { return year; }
    }

    // Setter properties
    public void SetMake(string make)
    {
        this.make = make;
    }

    public void SetModel(string model)
    {
        this.model = model;
    }

    public void SetYear(int year)
    {
        this.year = year;
    }

    // Other methods
    public void StartEngine()
    {
        Console.WriteLine("Engine started!");
    }

    public void StopEngine()
    {
        Console.WriteLine("Engine stopped!");
    }

    public void CarDetails()
    {
        Console.WriteLine("make: " + make + " model: " + model + " year: " + year);
    }
}

Step 3: Save the Car.cs file.

Step 4: Create a new file named Program.cs and open it in a text editor or an IDE.

Step 5: Copy and paste the Main method code into the Program.cs file

Example

using System;
class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car("Toyota", "Camry", 2022);

        myCar.StartEngine();
        myCar.CarDetails();
        myCar.StopEngine();
    }
}

Step 6: Save the Program.cs file.

Step 7: Compile the Car.cs and Program.cs files using the C# compiler. If you are using an IDE, it will handle the compilation for you.

Step 8: Run the Program class. The output will be displayed in the console.

You should see the following output

Output

Engine started!
make: Toyota model: Camry year: 2022
Engine stopped!

In this example, we have a Car class that represents a car object. It has private fields (make, model, and year) to store information about the car’s make, model, and manufacturing year. The class also has a constructor that takes these values as parameters and initializes the fields accordingly.

The Car class provides getter and setter properties (Make, Model, and Year) to access and modify the values of the private fields. These properties allow controlled access to the field values and enable encapsulation.

Additionally, the Car class defines several methods. The StartEngine method prints a message indicating that the car’s engine has started. The StopEngine method prints a message indicating that the car’s engine has stopped. The CarDetails method prints the car’s make, model, and year.

In the Main method of the Program class, we create an instance of the Car class called myCar by using the constructor with the values “Toyota”, “Camry”, and 2022. Then, we call the StartEngine method, CarDetails method, and StopEngine method on the myCar object, which will execute the corresponding actions and display messages.

Overall, this example demonstrates the usage of a Car class with its fields, constructor, properties, and methods to create and interact with car objects.

Static Method And Non-Static Method In C#

Static Method

A static method belongs to the class itself rather than an instance of the class. It can be accessed using the class name directly, without creating an object of the class. Static methods are commonly used for utility functions or operations that do not require access to instance-specific data.

Here’s an example of a static method

public class MathUtils
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

In the above code, we have a class called MathUtils that contains a static method Add. This method takes two integers as parameters and returns their sum. To use the Add method, you can directly call it using the class name without creating an object:

int result = MathUtils.Add(5, 3);
Console.WriteLine(result); // Output: 8

Non-Static Methods

A non-static method, also known as an instance method, belongs to an instance of a class. It can access and modify the instance-specific data or fields of the class. Non-static methods require an object of the class to be created before they can be invoked.

Here’s an example of a non-static method:

Example

public class Car
{
    private string make;

    public void SetMake(string make)
    {
        this.make = make;
    }

    public string GetMake()
    {
        return make;
    }
}

In the above code, we have a class called Car that contains two non-static methods: SetMake and GetMake. The SetMake method sets the value of the make field, while the GetMake method retrieves its value. To use these methods, you need to create an instance of the Car class:

Car myCar = new Car();
myCar.SetMake("Toyota");
string carMake = myCar.GetMake();
Console.WriteLine(carMake); // Output: Toyota

Here, we create a Car object myCar, invoke the SetMake method to set the make of the car to “Toyota”, and then call the GetMake method to retrieve the make and display it using Console.WriteLine().

Differences between static and non-static methods in C#

TermStatic MethodNon-Static Method
DefinitionBelongs to the class itselfBelongs to an instance of the class
InvocationAccessed using the class name directlyInvoked on an object instance of the class
AccessCannot access non-static members (fields, methods) directlyCan access both static and non-static members directly
MemoryMemory is allocated once for the methodMemory is allocated separately for each object instance
UsageUseful for utility functions, operations independent of objectsUsed for operations that require access to instance-specific data
Object DependencyDoes not depend on object instancesRequires an object instance to be created
AccessibilityCan be called without creating an object of the classRequires an object of the class to be created to call the method

Conclusion

In conclusion, classes and objects are the fundamental building blocks of object-oriented programming (OOP). They enable us to organize and structure our code in a way that closely mirrors real-world entities and their interactions. By encapsulating data and behavior within classes, we can create objects that represent specific instances of those classes.

Classes act as blueprints or templates, defining the attributes (data) and methods (behavior) that objects of that class will possess. Objects, on the other hand, are instances of classes that have their own state and behavior.

C# Beginner Tutorial Series

Please Subscribe Youtube| Like Facebook | Follow Twitter


Leave a Reply

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