Friday, May 12, 2023

Constructor in C#

 What is the constructor in c #?


In C#, a constructor is a special method that gets called automatically when you create an instance (object) of a class. The purpose of a constructor is to initialize the object's data members or properties to default or specific values, and to perform any necessary setup operations.


A constructor is declared with the same name as the class and has no return type, not even void. In addition, a constructor may have zero or more parameters to accept input values from the caller.


For example, the following code defines a simple class named "clsPerson" with a constructor that accepts two parameters to set the object's name and age:

class clsPerson

{

    public string Name { get; set; }

    public int Age { get; set; }


    // Constructor

    public clsPerson(string name, int age)

    {

        Name = name;

        Age = age;

    }

}

To create a new instance of the "clsPerson" class, you would call the constructor like this:

ClsPerson p = new clsPerson("Dheeraj Kumar", 25);


This creates a new "clsPerson" object with the name "Dheeraj Kumar" and age 25, and assigns it to the variable "p". The constructor is automatically called during the object creation process, and sets the object's "Name" and "Age" properties to the values passed in.


No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...