Constructor

Constructor

A constructor is a special method that is used to initialize the object of a class. It is called automatically when an object of the class is created using the “new” keyword. Constructors have the same name as the class and can have parameters or be parameter less.

Here’s an example of a parameter less constructor for a class called “Person”:

				
					class Person {
    public string Name { get; set; }
    public int Age { get; set; }
    public Person() {
        Name = "Unknown";
        Age = 0;
    }
}

				
			

In this example, we have defined a class called “Person” with two properties, “Name” and “Age”. We have also defined a parameter less constructor for the class that sets the initial values of the properties to “Unknown” and 0, respectively.

Here’s an example of a constructor with parameters for the same class:

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

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

				
			

In this example, we have defined a constructor with two parameters, “name” and “age”, that sets the initial values of the properties to the values of the parameters.

Constructors can be used to perform initialization tasks that are required when an object is created. They can also be used to validate input parameters or perform other tasks that are required before the object is used. By providing constructors in your classes, you can ensure that objects are created with the correct initial state and behavior.

 

Join To Get Our Newsletter
Spread the love