Constructor Introduction
- The Constructor is used to initialize the object of the class.
- The Constructor name is the same as the class Name.
- The Constructor should be public, private and protected etc.
- A Constructor can be overloaded.
Types of Constructors
- Default Constructor
- Parameterized Constructor
- Private Constructor
- Copy Constructor
- Static Constructor
1. Default Constructor
Example
namespace ConstructorExample
{
class DefaultConstructor
{
int a, b;
public DefaultConstructor()
{
a = 23;
b = 56;
}
public void display()
{
Console.WriteLine("sum="+(a+b));
}
}
class Program
{
public static void Main()
{
DefaultConstructor dc = new DefaultConstructor();
dc.display();
Console.ReadLine();
}
}
}
2. Parameterized Constructor
Example
namespace ConstructorExample
{
class ParameterizeConstructor
{
int a, b;
public ParameterizeConstructor(int a, int b)
{
this.a =a;
this.b =b;
}
public void display()
{
Console.WriteLine("sum="+(a+b));
}
}
class Program
{
public static void Main()
{
ParameterizeConstructor pc = new ParameterizeConstructor(12, 32);
pc.display();
Console.ReadLine();
}
}
}
3. Private Constructor
Example
namespace ConstructorExample
{
class PrivateConstructor
{
static int a, b;
public PrivateConstructor(int x, int y)
{
a =x;
b =y;
}
//create this function because private constructor is not nilitilize in another class
public static PrivateConstructor InitilizeConstructor()
{
return new PrivateConstructor(12, 30);

Join the conversation! Your thoughts help the community grow.