Home »
.Net
Constructors in C#
C#.Net Constructors: Learn, what is the constructor, how they declared, defined and their properties with an example in C#.Net?
Constructors are special type of methods in C#, which is automatically invoked when an object is being created. It is basically used to:
- To initialize data member of class.
- To allocate memory for data member.
There are following properties of constructor in C#:
- Constructor has the same name as the class name. It is case sensitive.
- Constructor does not have return type.
- We can overload constructor, it means we can create more than one constructor of class.
- We can use default argument in constructor.
- It must be public type.
Consider the program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class EMP
{
private string name ;
private int age ;
private int salary ;
//constructor
public EMP()
{
name = "Herry";
age = 20 ;
salary = 23000 ;
}
public void setEmp(string name, int a = 18, int salary = 20000)
{
this.name = name ;
this.age = a ;
this.salary = salary ;
}
public void printEmp()
{
Console.WriteLine("\nEmployee Record: ");
Console.WriteLine("\tName : " + name );
Console.WriteLine("\tAge : " + age );
Console.WriteLine("\tSalary: " + salary );
}
}
class Program
{
static void Main()
{
EMP E0 = new EMP();
E0.printEmp();
EMP E1 = new EMP();
E1.setEmp("Sandy", salary: 48500);
E1.printEmp();
EMP E2 = new EMP();
E2.setEmp("Mark", a:33);
E2.printEmp();
}
}
}
Output
Employee Record:
Name : Herry
Age : 20
Salary: 23000
Employee Record:
Name : Sandy
Age : 18
Salary: 48500
Employee Record:
Name : Mark
Age : 33
Salary: 20000
In above example EMP () method is constructor, it initializes object, when object creates.
Normally Constructors are following type:
- Default Constructor or Zero argument constructor
- Parameterized constructor
- Copy constructor