Constructors:

  • A constructor is a special method that is called when an object is created.
  • It is used to initialize the object’s fields or perform any necessary setup.
  • Constructors have the same name as the class and do not have a return type.

Example:

class Person

{

    public string name;

    public int age;

    // Constructor

    public Person(string n, int a)

    {

        name = n;

        age = a;

    }

    public void SayHello()

    {

        Console.WriteLine(“Hello, my name is ” + name + ” and I am ” + age + ” years old.”);

    }

}

Person person2 = new Person(“Alice”, 30);

person2.SayHello();  // Output: Hello, my name is Alice and I am 30 years old.

Access Modifiers:

  • Access modifiers define the visibility and accessibility of class members (fields, methods, constructors) from outside the class.
  • The main access modifiers in C# are public, private, protected, and internal.

Example:

class Person

{

    public string name;        // Accessible from anywhere

    private int age;           // Accessible only within the class

    protected string address;  // Accessible within the class and derived classes

    internal string phone;     // Accessible within the same assembly

    // …

}

Inheritance:

  • Inheritance is a mechanism that allows a class (derived class) to inherit the properties and methods of another class (base class).
  • The derived class extends the base class and can add new members or override existing ones.
  • It promotes code reuse and facilitates the creation of class hierarchies.

Example:

class Student : Person

{

    public string studentId;

    public Student(string n, int a, string id)

        : base(n, a)

    {

        studentId = id;

    }

    // Additional methods and fields specific to the Student class

}

Classes and objects form the building blocks of object-oriented programming in C