Constructor is used to initializing the Class and Private members within the class.
It is like a method but with no return type like void or int or any. Constructors are the first being called.
For example,
Class Car
{
private string color; //Private field member
public Car(string _color) //Constructor initialization
{
color = _color;
}
}
//Initializing Class
Car myCar = new Car("Red"); // This will call the constructor
Basic things to remember,
- It must match the class name
- No return type is allowed
- No separate method call required, as above example at class initialization it is called directly
- All classes have their own default constructors if it is not declared.
- Constructors can have multiple parameters and such is called Parameterized Constructors
- Constructors can be overloaded by using different parameters (Will see more on Overloading and Overriding in upcoming posts)
Types of Constructors
- Parameterless Constructor / Default Constructor
- If no constructor is defined C# create for itself
- Parameterized Constructor
- Constructor with parameters one or many is called parameterized constructor
- Used to initialize the members of the class
- Static Constructor
- Static constructor used to initialize the static members
- You can have Public and Static constructor
- Private Constructor
- If a class has a Private Constructor only, other classes will not be able to create an instance of that class
No comments:
Post a Comment