■ Constructor
• A constructor is a special method that is used to initialize objects.
• it is called when an object of a class is created.
• It is used to set initial values for fields(variables)
• without constructor we can't create instance of a class (if we don't create a constructor explicity then compiler create the default constructor implicitly )
• the constructor name must match the class name, and it cannot have a return type (like void or int).
• All classes have constructors by default if you do not create a class constructor yourself, C# creates one for you.
• A static constructor cannot be a parameterized constructor because it get called automatically by the runtime.
➤ Types of Constructor
1) Default Constructor
2) Parameterized Constructor
3) Copy Constructor
4) Static Constructor
1) Default Constructor or parameter-less constructor
• A constructor with no parameters is called a default constructor.
• The default constructor initializes all numeric fields to zero and all string and object fields to null, unless explicitly initialized to different values in the constructor.
2) parameterised constructor
• A constructor having at least one parameter is called as parameterized constructor.
It can initialize each instance of the class to different values.
3) Copy constructor
• This constructor creates an object by copying variables from another object.
• Its main use is to initialize a new instance to the values of an existing instance.
• It takes class name as parameter.
4) Static Constructor
• if we use static keyword before the name of constructor then it is called static constructor.
• If there are static fields in our class then compiler will provide implicit static constructor until we create explicit constructor.
• It is called automatically by the runtime before any static members are accessed or any static methods are called, and it runs only once for the class.
• A static constructor is used to initialize static fields of the class and to be executed only once.
• static constructors cannot have parameters and cannot be called directly.
• static constructors cannot be overloaded.
• We can't use any modifier with static constructor
Example :-
public class MyClass
{
public static int Count;
// Static constructor
static MyClass()
{
// Initialize static members
Count = 0;
Console.WriteLine("Static constructor called.");
}
public static void IncrementCount()
{
Count++;
}
}
// Usage
MyClass.IncrementCount();
Console.WriteLine(MyClass.Count); // Output: 1
Comments
Post a Comment