Constructors:
Constructor is same as method inside class with the same
name as class without return type. A constructor is called when an object of
class first created. You can use constructor to initialize the object and set any
parameters. In addition you can accept arguments through constructor.
Let’s discuss code for creating constructor
using System;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Employee e = new Employee("John");
Console.Write(e.GetEmployee());
}
}
class Employee
{
string EmployeeName;
public Employee() //Default Constructor
{
}
public Employee(string
s) //Parameterized Constructor
{
EmployeeName = s;
}
public string
GetEmployee()
{
return EmployeeName;
}
}
}
In the above code class
Employee has 2 constructors defined. While creating the object if we pass
string as parameter it calls second constructor and assign s variable value to
EmployeeName variable.
And after that if we get
the value of variable EmployeeName, we get the string passed to that variable.
There is different type of constructors in c#
1.
Default Constructor: This constructor has no any
argument. If we create object without passing any parameter it goes to default
constructor. If we not declared this constructor in a class, iit takes by
default it. In the above example there is one Default Constructor.
2.
Parameterized constructor: This type of
constructor has much argument. We can define multiple constructors with
different signature in the parameter (This Concept is called as Method
Overloading).
3.
Copy constructor: A copy constructor is used to
create copy of existing object as new object. This constructor takes reference
of the object to be copied as an argument.
Destructor:
It is also one of the methods with the same name as class
but before class name there is “~” sign there. It is used for destroy the
objects that are no longer in use. In below example I have implemented
destructor.
using System;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Employee e = new Employee("John\n");
Console.Write(e.GetEmployee());
}
}
class Employee
{
string EmployeeName;
public Employee()
{
}
~Employee()
{
Console.Write("Distructor
called");
Console.ReadLine();
}
public Employee(string
s)
{
EmployeeName = s;
}
public string
GetEmployee()
{
return EmployeeName;
}
}
}
Output:
John
Destructor called
Key Points:
Desctructor does not accept any access modifier.
0 Comments