C# Classes and Objects

In this tutorial, you will learn about the concept of C# classes and objects with the help of examples.

C# Classes and Objects

In Previous article we learned about C# Program structure and data types and now in this article we will learn about C# classes and objects using various examples. Similar to most of the object-oriented programming languages C# also has inbuilt support for C# classes and objects.

C# Classes and Objects

In C#, a class is a blueprint or a template for creating objects. An object is an instance of a class. C# is associated with classes and objects, along with its attributes and methods.

To work with objects, we need to perform the following activities:

  • create a class
  • create objects from the class

C# Class:

Before we learn about objects, we need to understand the working of classes. Class is the blueprint for the object.

Here’s an example of a simple class in C#:

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

    public void Drive()
    {
        Console.WriteLine("Driving the {0} {1}...", Make, Model);
    }
}

In this example, we have defined a class called “Car“. It has three public properties: “Make“, “Model“, and “Year“, which can be accessed from outside the class. It also has a public method called “Drive” that writes a message to the console.

C# Objects:

An object is an instance of a class. Suppose, to create an object of this class, we can use the “new” keyword:

Classname obj= new Classname();

This creates a new instance of the “Car” class and assigns it to the variable “myCar“. We can then set the properties of the object like this:

Car myCar= new Car();
myCar.Make = "Toyota";
myCar.Model = "Corolla";
myCar.Year = 2018;

And we can call the “Drive” method like this:

myCar.Drive();

This will output the message “Driving the Toyota Corolla…” to the console.

Classes can have constructors, which are special methods that are called when an object is created. Constructors can be used to initialize the object’s properties or perform other setup tasks. Here’s an example of a class with a constructor:

public class Person
{
    public string Name;
    public int Age;

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void SayHello()
    {
        Console.WriteLine("Hello, my name is {0} and I'm {1} years old.", Name, Age);
    }
}

In this example, we have a class called “Person” that has two properties: “Name” and “Age”. We also have a constructor that takes two parameters: “name” and “age”. This constructor sets the “Name” and “Age” properties of the object.

We can create an instance of the “Person” class like this:

Person john = new Person("John", 30);

This creates a new instance of the “Person” class with the “Name” property set to “John” and the “Age” property set to 30. We can then call the “SayHello” method like this:

john.SayHello();

This will output the message “Hello, my name is John and I’m 30 years old.” to the console.

Constructor :

In C#, a constructor is a special method that is used to initialize objects when they are created. It has the same name as the class and does not have a return type, not even void.

Here is an example of a constructor in C#:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    // Constructor with parameters
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    // Default constructor
    public Person()
    {
        Name = "John Doe";
        Age = 18;
    }
}

// Creating an object of the Person class using the constructor with parameters
Person person1 = new Person("Alice", 25);

// Creating an object of the Person class using the default constructor
Person person2 = new Person();

In this example, we have defined a class ‘Person‘ with two properties, Name and Age. We have also defined two constructors for this class – one that takes two parameters (nameand 'age') and one that doesn’t take any parameters.

When we create an object of the Person' class using the constructor with parameters, we pass in values for the ‘nameand age parameters. These values are then used to initialize the ‘Nameand ‘Age‘ properties of the object.

When we create an object of the Person class using the default constructor, the ‘Name‘ property is set to “John Doe” and the Ageproperty is set to 18 by default.

Methods:

Methods are functions that are defined within a class. They are used to perform specific tasks or operations. C# is a popular programming language used to build a variety of applications ranging from desktop applications to web services.

Here’s an example of a method in C#:

// Define a method to calculate the sum of two integers
public int CalculateSum(int a, int b)
{
    return a + b;
}

In the example above, we defined a method called ‘CalculateSumthat takes two integers as arguments (a' and b') and returns their sum. Here are the key parts of this method:

  • public‘: This keyword indicates that the method is accessible from outside the class in which it’s defined.
  • int‘: This is the return type of the method. In this case, the method returns an integer value.
  • CalculateSum: This is the name of the method.
  • (int a, int b): These are the parameters that the method accepts. In this case, the method accepts two integers called a and b.
  • return a + b';: This is the body of the method. It adds the values of a and b and returns the result.

To call this method, you would use code like this:

int result = CalculateSum(2, 3);
Console.WriteLine(result); // Output: 5

In this example, we’re calling the ‘CalculateSum‘ method and passing in the values 2 and 3 as arguments. The method calculates the sum of these values and returns the result, which we store in the result variable. We then output the value of result to the console, which displays the result 5.

Inheritance:

Inheritance is a powerful feature in C# that allows you to create new classes based on existing classes. Inheritance enables you to reuse the code in a base class and extend it by adding new functionality or modifying existing behavior.

Here’s an example of how to use inheritance in C#:

// Define a base class called Animal
public class Animal
{
    // Declare a protected string field
    protected string name;

    // Define a constructor to set the name field
    public Animal(string name)
    {
        this.name = name;
    }

    // Define a virtual method called MakeSound
    public virtual void MakeSound()
    {
        Console.WriteLine("The animal makes a sound.");
    }
}

// Define a derived class called Cat that inherits from Animal
public class Cat : Animal
{
    // Define a constructor that calls the base class constructor
    public Cat(string name) : base(name)
    {
    }

    // Override the MakeSound method to make a cat-specific sound
    public override void MakeSound()
    {
        Console.WriteLine("Meow!");
    }
}

In the example above, we defined a base class called ‘Animalwith a protected field ‘name‘, a constructor to set the ‘namefield, and a virtual method called ‘MakeSound‘. We also defined a derived class called Cat that inherits from ‘Animal' and overrides the ‘MakeSound‘ method.

Here are the key parts of this example:

  • public class Animal: This is the base class.
  • protected string name‘: This is a protected field that stores the name of the animal.
  • public Animal(string name): This is a constructor that sets the ‘name' field.
  • public virtual void MakeSound(): This is a virtual method that outputs a generic sound.
  • public class Cat: Animal‘: This is the derived class that inherits from ‘Animal'.
  • public Cat(string name) : base(name): This is a constructor that calls the base class constructor to set the ‘namefield.
  • public override void MakeSound(): This is a method that overrides the ‘MakeSoundmethod of the base class to output a cat-specific sound.

To use this inheritance hierarchy, you would create an instance of the ‘Catclass and call its ‘MakeSound' method:

Cat cat = new Cat("Fluffy");
cat.MakeSound(); // Output: Meow!

In this example, we create a new ‘Cat' object called ‘cat' and pass in the name “Fluffy” to the constructor. We then call the ‘MakeSound' method on the cat object, which outputs the cat-specific sound “Meow!”. Because ‘Catinherits from ‘Animal', it also has access to the ‘namefield and the ‘MakeSoundmethod of the ‘Animal' class.

Polymorphism:

Polymorphism is a fundamental concept in object-oriented programming that allows you to write code that can work with objects of multiple types. In C#, polymorphism is achieved through method overriding and method overloading.

Method Overriding: Method overriding occurs when a derived class provides a different implementation of a method that is already defined in its base class. Here’s an example of how to use method overriding to implement polymorphism in C#:

// Define a base class called Shape
public class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine("Drawing a shape.");
    }
}

// Define a derived class called Circle that overrides the Draw method
public class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a circle.");
    }
}

// Define a derived class called Rectangle that overrides the Draw method
public class Rectangle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a rectangle.");
    }
}

In the example above, we defined a base class called ‘Shapewith a virtual ‘Drawmethod, and two derived classes called ‘Circleand ‘Rectanglethat override the ‘Draw' method.

Here are the key parts of this example:

  • public class Shape‘: This is the base class.
  • public virtual void Draw()‘: This is a virtual method that outputs a generic message.
  • public class Circle : Shape: This is the derived class that overrides the Draw method to output a circle-specific message.
  • public override void Draw()‘: This is a method that overrides the Draw method of the base class to output a circle-specific message.
  • public class Rectangle' : Shape: This is the derived class that overrides the Draw method to output a rectangle-specific message.
  • public override void Draw()‘: This is a method that overrides the Draw method of the base class to output a rectangle-specific message.

To use polymorphism with these classes, you would create instances of the Circle and ‘Rectangle' classes and call their ‘Draw' methods:

Shape circle = new Circle();
Shape rectangle = new Rectangle();

circle.Draw(); // Output: Drawing a circle.
rectangle.Draw(); // Output: Drawing a rectangle.

In this example, we create two objects, ‘circleand ‘rectangle‘, of the base class type ‘Shape'. We then instantiate ‘circle' as an instance of the derived ‘Circleclass, and ‘rectangle' as an instance of the derived ‘Rectangle' class. We call the ‘Draw' method on both objects, which outputs the circle-specific and rectangle-specific messages, respectively.

Method Overloading: Method overloading occurs when multiple methods have the same name, but different parameter types or numbers. Here’s an example of how to use method overloading to implement polymorphism in C#:

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

    public double Add(double a, double b)
    {
        return a + b;
    }
}

In the example above, we defined a class called ‘Calculator‘ with two methods called ‘Add', one that takes two integers and another that takes two doubles. These two methods have the same name but different parameter types.

To use polymorphism with these methods, you would call them with different parameter types:

Calculator calculator = new Calculator();

int result1 = calculator.Add(2, 3); // Returns 5
double result2 = calculator.Add(2.5, 3.5); // Returns 6.0

In this example, we create a new ‘Calculator‘ object called ‘calculator‘. We then call the ‘Add‘.

Encapsulation :

Encapsulation is one of the fundamental concepts of object-oriented programming (OOP) in C#. It refers to the practice of bundling related data (fields) and behavior (methods) into a single unit, usually a class, and controlling access to that unit through a well-defined interface.

In C#, encapsulation is achieved by using access modifiers such as public, private, protected, internal, and protected internal to control the visibility and accessibility of class members, such as fields, methods, and properties.

By making certain members private, you can ensure that they are not accessed or modified by code outside the class, thus preventing unauthorized access or modification of internal state. Instead, access to those members is provided through public or protected methods, properties, or events.

Encapsulation provides several benefits, including:

  • Improved code maintainability and modularity: Encapsulation allows you to hide the implementation details of a class from other parts of the program, making it easier to modify or update the class without affecting the rest of the program.
  • Improved code readability and understanding: Encapsulation provides a clear and concise interface for interacting with a class, making it easier to read and understand the purpose and behavior of the class.
  • Improved code reusability: Encapsulation allows you to reuse code by creating objects from classes that have well-defined interfaces and encapsulated state.

Here is an example of encapsulation in C#:

public class Employee
{
    private string name;
    private int age;

    public Employee(string name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public string GetName()
    {
        return name;
    }

    public int GetAge()
    {
        return age;
    }

    public void SetName(string name)
    {
        this.name = name;
    }

    public void SetAge(int age)
    {
        this.age = age;
    }
}

In this example, we have defined a class ‘Employeewith private fields ‘nameand ‘age'. We have provided public getter and setter methods for these fields using the 'GetName', ‘GetAge', ‘SetName', and ‘SetAge' methods. By making the fields private and providing public access to them through the getter and setter methods, we have encapsulated the internal state of the ‘Employeeclass and provided a well-defined interface for interacting with it.

A class serves as a blueprint for defining user-defined data types in programming. It allows for grouping of similar objects and encapsulating their data and functionality. Objects, on the other hand, are runtime entities created from a class to access its members.

To create a new class, the “class” keyword is used, followed by the name of the class. Optional modifiers or attributes can be specified for the class. The members of the class, including data and functionality, are declared within curly braces “{}”. This declaration establishes the structure and behaviour of objects that will be created based on the class. So, a class declaration in programming typically starts with the “class” keyword, followed by the class name and curly braces to enclose its members. This allows for defining custom data types and their associated behaviours. Then, objects can be instantiated from the class to represent specific instances of the defined data type, with access to the members (data and functionality) defined in the class. In this way, C# classes and objects provide a way to model real-world entities and their behaviours in software development.

Leave a Comment

RSS
Follow by Email
YouTube
YouTube
LinkedIn
Share