C# Constructor
Constructor is a special method of the class that is automatically invoked when an instance of the class is created is called a constructor. the main use of the constructor is to initialize private fields of the class when you have not created a constructor in the class the compiler will automatically create a default constructor of the class.
- The default constructor initializes all numeric fields in the class to zero and all string and objects fields to null.
- A class can have any no. of constructors.
- A constructor doesn't have any return type not even void.
- A static constructor can't be parametrized.
- Within a class you can create only one static constructor.
Types of constructors -
- The drawback of the default constructor is that every instance of the class will be initialized to the same values, and it is not possible to initialize each instance of the class with different values.
- All numeric fields in the class initialized to zero.
- All string fields initialized to null.
2. Parametrized Constructor - A constructor with at least one parameter is called a parametrized constructor, the advantage of a parametrized constructor is that you can initialize each instance of the class with a different value.
3. Copy Constructor - The constructor which creates an object by copying variables from another object is called a copy constructor. the purpose of a copy constructor is to initialize a new instance to the values of an existing instance.
4. Static Constructor - When a constructor is created using a static keyword, it will be invoked only once for all of the instances of the class, and it is invoked during the creation of the first instance of the class or the first reference t a static member in the class. a static constructor is used to initialized static fields of the class to write the code that needs to be executed only once.
- A static constructor doesn't take access modifier or have parameters.
- A static constructor called automatically to initialize the class before the first instance is created.
5. Private Constructor - When a constructor is created with a private specifier it is not possible for other classes to drive form this class. neither is it possible to create an instance of the class that contains static members only.
- On use of a private constructor is when we have only static members
- It is provided an implementation of a singleton class pattern
- Once we provide a constructor that is either private or public or any, the compiler will not add the parameter less public constructor to the class.
Comments
Post a Comment