Classes and Objects in C#

Mannan Ul Haq
0

C# is an object-oriented programming language that provides support for classes and objects. A class in C# is a blueprint for creating objects that encapsulate data and behavior. Let's dive into the fundamentals of classes, objects, and access modifiers in C#.


Defining a Class in C#:

In C#, a class is defined using the class keyword, followed by the class name. Inside the class, we can declare data members (fields) and member functions (methods) that operate on these data members.

using System;

class Person
{
    // Data members
    public string name;
    public int age;

    // Member function to introduce the person
    public void Introduce()
    {
        Console.WriteLine($"Hi, my name is {name} and I am {age} years old.");
    }
}


In the above example, we define a class called "Person" using the class keyword. Inside the class, we have two data members: name (of type string) and age (of type int). We also have a member function called introduce() which prints out the person's name and age.

Creating Objects and Accessing Members:

To create an object of a class, we use the new keyword followed by the class name and store it in a variable. Once an object is created, we can access its data members and member methods using the dot operator (.).

class Program
{
    static void Main()
    {
        // Creating objects of the Person class
        Person person1 = new Person();
        Person person2 = new Person();

        // Setting the data members of person1
        person1.name = "Alice";
        person1.age = 25;

        // Setting the data members of person2
        person2.name = "Bob";
        person2.age = 30;

        // Using member methods to introduce the persons
        person1.Introduce();
        person2.Introduce();
    }
}

In the Main() function, we create two objects of the Person class: person1 and person2. We then set the name and age for each person using the dot operator (.). Finally, we call the introduce() function on each object, which displays the person's information.

Access Specifiers:

C# provides access modifiers to control the visibility or accessibility of class members. There are four access modifiers:

1. `public`:

Public members are accessible from any part of the program. They have the widest scope.

2. `private`:

Private members are accessible only within the class where they are declared. They are hidden from other classes.

3. `protected`:

Protected members are accessible within the class where they are declared and its derived classes.

3. `internal`:

Internal members are accessible only within the same assembly (i.e., the project or library). They are not accessible outside the assembly.

Here's an example that demonstrates the use of access specifiers:

class MyClass
{
    public int publicVar;       // Public data member

    private int privateVar;     // Private data member

    protected int protectedVar; // Protected data member

    internal int internalVar;   // Internal data member

    // Member methods can have any access modifier
    public void PublicFunction()
    {
        Console.WriteLine("PublicFunction: I can access all data members.");
        Console.WriteLine($"PublicVar: {publicVar}, PrivateVar: {privateVar}, ProtectedVar: {protectedVar}, InternalVar: {internalVar}");
    }

    private void PrivateFunction()
    {
        Console.WriteLine("PrivateFunction: I can only access the privateVar.");
        Console.WriteLine($"PrivateVar: {privateVar}");
    }

    protected void ProtectedFunction()
    {
        Console.WriteLine("ProtectedFunction: I can access privateVar and protectedVar.");
        Console.WriteLine($"PrivateVar: {privateVar}, ProtectedVar: {protectedVar}");
    }

    internal void InternalFunction()
    {
        Console.WriteLine("InternalFunction: I can access all data members within the same assembly.");
        Console.WriteLine($"PublicVar: {publicVar}, PrivateVar: {privateVar}, ProtectedVar: {protectedVar}, InternalVar: {internalVar}");
    }
}

class Program
{
    static void Main()
    {
        MyClass obj = new MyClass();

        // Accessing public data member and calling public function
        obj.publicVar = 10;
        obj.PublicFunction();

        // Private members cannot be accessed outside the class
        // obj.privateVar = 20; // Error: privateVar is inaccessible due to its protection level
        // obj.PrivateFunction(); // Error: PrivateFunction() is inaccessible due to its protection level

        // Protected members cannot be accessed outside the class, but can be accessed in derived classes
        // obj.protectedVar = 30; // Error: protectedVar is inaccessible due to its protection level
        // obj.ProtectedFunction(); // Error: ProtectedFunction() is inaccessible due to its protection level

        // Accessing internal data member and calling internal function within the same assembly
        obj.internalVar = 40;
        obj.InternalFunction();

        // Output:
        // PublicFunction: I can access all data members.
        // PublicVar: 10, PrivateVar: 0, ProtectedVar: 0, InternalVar: 0

        // InternalFunction: I can access all data members within the same assembly.
        // PublicVar: 10, PrivateVar: 0, ProtectedVar: 0, InternalVar: 40
    }
}

NOTE: In a class, the default access specifier for its members is "private". This means that if you don't specify an access specifier for a member, it will be considered private by default. (alert-success)


Class Methods:

Class methods, also known as member functions, are functions defined within a class that operate on the class's data members.


Classification of Member Methods:

In C#, member methods can be classified based on their purpose and behavior. Three common types of member methods are accessor methods (or getter methods), mutator methods (or setter methods), and utility methods.


1. Accessor or Getter Methods:

  • Accessor methods are used to retrieve the values of private data members of a class.
  • Accessor methods provide read-only access to the private data members, allowing other parts of the program to obtain the values.
  • Typically, accessor methods have a return type that matches the data member they retrieve.
In C#, accessor methods are typically defined as properties. Properties provide a simple and elegant way to access private fields while controlling their visibility and behavior.


Example:


class Rectangle
{
    private double length;
    private double width;

    public double Length
    {
        get { return length; }
    }

    public double Width
    {
        get { return width; }
    }
}

class Program
{
    static void Main()
    {
        Rectangle rectangle = new Rectangle();

        // Using the getter properties to retrieve the values
        double length = rectangle.Length;
        double width = rectangle.Width;
    }
}


In the above example, `Length()` and `Width()` are accessor methods that allow retrieving the values of the private data members `length` and `width`, respectively.


In C#, the get keyword is used in a property declaration to define the accessor method (getter) for the property. It specifies the code that will be executed when the property is read or accessed. (alert-success)


2. Mutator or Setter Methods:

  • Mutator methods are used to modify the values of private data members of a class.
  • They provide a way to update the internal state of an object by setting new values for the private data members.
  • Mutator methods do not return a value (or return `void`), but they typically take parameters to update the data members.
In C#, setter methods can also be defined as properties using 'set', providing controlled access to private fields while enforcing any required validation or constraints.


Example:


using System;

class Rectangle
{
    private double length;
    private double width;

    public double Length
    {
        get { return length; }
        set
        {
            if (value > 0)
                length = value;
        }
    }

    public double Width
    {
        get { return width; }
        set
        {
            if (value > 0)
                width = value;
        }
    }
}

class Program
{
    static void Main()
    {
        Rectangle rectangle = new Rectangle();

        // Using the setter properties to set the values
        rectangle.Length = 5.0;
        rectangle.Width = 3.0;

        // Using the getter properties to retrieve the values
        double length = rectangle.Length;
        double width = rectangle.Width;

        Console.WriteLine($"Length: {length}, Width: {width}");
    }
}


In the above example, `Length()` and `Width()` are mutator methods that allow setting new values for the private data members `length` and `width`, respectively.


3. Utility Methods:

  • Utility methods perform specific operations related to the class but may not directly manipulate the class's data members.
  • They can be used for calculations, conversions, or any other functionality associated with the class.


Example:


class MathOperations
{
    public int Square(int number)
    {
        return number * number;
    }
}


In the above example, `Square()` is a utility method defined as a static member method. It calculates the square of a given number, but it does not require any access to the object's data members.


Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !