Contructor In C#

Constructor is a method of class that is executed when its object is created. constructor is responsible for object initialization and memory allocation of its class and new keyword is used to create an object.

Most Important Points of Constructor
  1. Constructor name same as class name.
  2. Constructor should not contain return type even void also.
  3. Constructor can't contain modifiers.
  4. Constructor logic block can't contain return statement with its value, we can place return; in constructor.
  5. Constructor have parameter.
  6. We can throw exception from constructor.
  7. We can't define method with the same class name, it will generate compile time error.
  8. We can create multiple constructor but must have different parameter type and its order


Syntax of Constructor in C#

Public Class User
{
      // Constructor
      Public User()
     {
             // Constructor Logic Block
      }
}

Types of Constructor in C#
  1. Default Constructor : Constructor without parameter. 2 Types of default constructor system define constructor and user define constructor.
  2. Parameterized Constructor : When we want to assign dynamic value to object we are using parameterized constructor. The advantage of parameterized constructor is we can assign each instance of the class with different value.
  3. Copy Constructor : Constructor which create an object by copying variable from another objects its called copy constructor.
  4. Static Constructor : It is used to perform particular action only once throughout the application. It will be called automatically before the first instance is created. Static constructor is a parameterless. Only one static constructor is allowed to create.
  5. Private Constructor : When we create a constructor with private specifier its become a private constructor.
March 12, 2020 / by / 0 Comments

No comments:

Post a Comment

Thanks for your comments

Post Top Ad