Sobes.tech
Junior — Middle

Explain the purpose and operation of a constructor when creating a new object in object-oriented programming

sobes.tech AI

Answer from AI

A constructor in object-oriented programming is a special method of a class that is automatically called when a new object of that class is created. Its main task is to initialize the object, that is, to set the initial values of its fields and perform necessary preparations.

In C#, a constructor has the same name as the class and does not return a value.

Example of a constructor in C#:

class Person
{
    public string Name;
    public int Age;

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

// Creating an object
Person p = new Person("Ivan", 30);

Here, when creating a Person object, the constructor sets the name and age, ensuring the correct state of the object from the very beginning.