![]() |
VOOZH | about |
A constructor in C# is a special method of a class that is automatically called when an object of the class is created. It has the same name as the class, does not have a return type and is mainly used to initialize the object's data members.
Example:
class Geeks{
// constructor of Geeks class
public Geeks( ) { }
}
// Using this constructor
Geeks obj = new Geeks();
Common constructor types are:
A default constructor in C# is a constructor with no parameters. It is automatically provided by the compiler if no constructor is defined in the class. It initializes numeric fields to 0, Boolean to false and reference types like strings or objects to null. Example:
Note: The compiler may show warnings since the fields are never explicitly assigned. These warnings are safe to ignore here because they illustrate the default values assigned automatically by C#.
A constructor having at least one parameter is called a parameterized constructor. It can initialize each instance of the class to different values. Example:
Name = GFG Id = 1
A copy constructor is used to create a new object by copying values from an existing object of the same class. In C#, copy constructors are not built-in and must be explicitly defined by the user. Example:
Month: June Year: 2018
Note: C# does not have a predefined copy constructor, we manually create one if needed.
If a constructor is created with a private specifier is known as Private Constructor. It is not possible for other classes to derive from this class and also it’s not possible to create an instance of this class. Some important points regarding the topic is mentioned below:
Note: Access modifiers can be used in constructor declaration to control its access i.e. which other class can call the constructor. Private Constructor is one of it's example.
Example
100 101
Static Constructor has to be invoked only once in the class and it has been invoked during the creation of the first reference to a static member in the class. A static constructor is used to initialize static fields or data of a class and is executed only once.
Example:
Static Constructor Instance Constructor 1 Name: GFG id: 1 Instance Constructor 2 Name: GeeksforGeeks id: 2