Junior — Middle
What is the role of a constructor when creating an object and why is it needed?
sobes.tech AI
Answer from AI
A constructor in C# is a special method of a class that is called when a new object is created. Its main role is to initialize the object, that is, to set the initial values of fields and perform necessary setup.
A constructor is needed to ensure that the object will be created in a correct state. If a constructor is not explicitly defined, the compiler will create a default parameterless constructor.
Example of a constructor:
public class Person
{
public string Name { get; }
public int Age { get; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
// Creating an object
var person = new Person("Ivan", 30);