In this article I will explain what is constructor in class, use of constructor and types of constructor.
The constructor basically special method of class that is automatically invoked when instance of class is created is called the constructor. The use of the constructor are initialize the private filed of the class while creating the instance of the class. when you have not created the constructor of the class, the compiler automatically create the default constructor. The default constructor initialize the all numeric filed to zero and all string filed to null.
using System;
public class Program
{
public static void Main()
{
Lab1 l=new Lab1();
Console.WriteLine("Value of a {0}",l.a);
Console.WriteLine("Value of name {0}",l.name);
}
}
public class Lab1{
public int a;
public string name;
}
Output :
Value of a 0
Value of name null
In the above example when we have create the instance of the class then automatically constructor are created and initialize the value of a is 0 and name is null.
Some important information about the constructor :
- A class can have any number of constructors.
- A constructor does not have any return type like int, float and string even void.
- A static constructor can not be parameterized constructor.
- within a class, you can create only on static constructor.
Types of constructor :
No comments:
Post a Comment