Concept of Constructor and Destructor:
we came to know that the people who are new to Programming face difficulty in understanding the concept of Constructor and Destructor in OOP in C#, C++ or any other Programming Language. Let us help you in this part of education by posting a very simple tutorial to learn Constructor and Destructor in OOP.
Constructor:
Constructors are the special methods in the class having same name as the class, when the class has been called or the object of the class has been made the constructor automatically runs itself. It means constructor have the run time support. There are three difference between method given below:
- Constructors execute automatically on making of class object, but method have to be called separately.
- Constructors have no return type.
- Constructor have same name as class name
Example:
class Student
{
public Student() // no
return type, a constructor, we make it public as we will call its class in another class
{
Console.WriteLine("Constructor");
}
public void abc()
{
Console.WriteLine("Method");
// have return type, method
}
}
class Program
{
static void Main(string[] args)
{
Student s = new Student(); //
constructor will execute automatically here
s.abc(); // method has to be called
}
}
Arguments in Constructors:
Arguments or Parameters in Constructors are same as methods in C#. The main difference is in Calling and the arguments will be passed when object is created.
Example:
class argmen
{
public argmen(string
a)
{
// first constructor
}
public argmen(int a, string b)
{
// second constructor
}
public argmen()
{
// third constructor
}
}
class Program
{
static void Main(string[] args)
{
argmen ar = new argmen("Faisal"); // this will call
the first constructor as we passed string
argmen ar2 = new argmen(8,"Jabbar"); // this will call
the second constructor as we passed first in and then string
argmen ar3 = new argmen(); // this will call the thirf constructor as have no
arguments
}
}
Destructor:
Example:
class Student
{
~Student() // this is a destructor, ~(Tilda) to make destructor
{
Console.WriteLine("Destructor");
}
Thank you For Reading this, Like this if you understood, It helps a lot to make us motivated
Good Description.
ReplyDeleteI am regular visitor, how are you everybody? This post posted at this web page is truly pleasant. outlook 365 sign in
ReplyDelete