real time example in constructor and destructor [Resolved]

Posted by Rahmankhan under ASP.NET on 8/27/2013 | Points: 10 | Views : 10584 | Status : [Member] | Replies : 8
i need more example and clear explanation




Responses

Posted by: Bandi on: 8/27/2013 [Member] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
Constructors
Constructors are special methods, used when instantiating a class. A constructor can never return anything, which is why you don't have to define a return type for it. A normal method is defined like this: public string Describe()
A constructor can be defined like this: public Car()
In our example for this chapter, we have a Car class, with a constructor which takes a string as argument. Of course, a constructor can be overloaded as well, meaning we can have several constructors, with the same name, but different parameters.
Here is an example:
public Car()

{

}


-- Constructor with single parameter
public Car(string color)

{
this.color = color;
}


A constructor can call another constructor, which can come in handy in several situations. Here is an example:
public Car()

{
Console.WriteLine("Constructor with no parameters called!");
}

public Car(string color) : this()
{
this.color = color;
Console.WriteLine("Constructor with color parameter called!");
}

If you run this code, you will see that the constructor with no parameters is called first. This can be used for instantiating various objects for the class in the default constructor, which can be called from other constructors from the class. If the constructor you wish to call takes parameters, you can do that as well. Here is a simple example:
public Car(string color) : this()

{
this.color = color;
Console.WriteLine("Constructor with color parameter called!");
}

public Car(string param1, string param2) : this(param1)
{

}

If you call the constructor which takes 2 parameters, the first parameter will be used to invoke the constructor that takes 1 parameter.

Destructors
Since C# is garbage collected, meaning that the framework will free the objects that you no longer use, there may be times where you need to do some manual cleanup. A destructor, a method called once an object is disposed, can be used to cleanup resources used by the object. Destructors doesn't look very much like other methods in C#.
Here is an example of a destructor for our Car

class: ~Car()
{
Console.WriteLine("Out..");
}

Once the object is collected by the garbage collector, this method is called.

Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Rahmankhan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Satyapriyanayak on: 8/27/2013 [Member] [MVP] Silver | Points: 50

Up
0
Down

Resolved
Constructor in C#

A special method of the class that will be automatically invoked when an instance of the class is created is called as constructor.

Constructors are mainly used to initialize private fields of the class while creating an instance for the class.

When you are not creating a constructor in the class, then compiler will automatically create a default constructor in the class that initializes all numeric fields in the class to zero and all string and object fields to null.

To create a constructor, create a method in the class with same name as class and has the following syntax.

[Access Modifier] ClassName([Parameters])

{

}


Constructors in C#.NET Example


using System;



//Example Class to return Area of a Square

class Square

{

private int Side;



//Default Constructor

public Square()

{

this.Side = 1;

}





//Paramerized Constructor

public Square(int side)

{

//A Constructor is used to initilize private fields of a class

this.Side = side;

}





public int Area()

{

return this.Side * this.Side;

}



}





//Using Class in the program

class MainClass

{



public static void Main()

{

//Calling Default Constructor

Square squreobject = new Square();

int Area = squreobject.Area();

Console.WriteLine(Area);



//Calling Parametrized Constructor

Square MySquare = new Square(10);

int myarea = MySquare.Area();

Console.WriteLine(myarea);



Console.Read();

}

}


Output
1
100

If this post helps you mark it as answer
Thanks

Rahmankhan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Satyapriyanayak on: 8/27/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
Destructor in C#.NET


A destructor is a special method of the class that is automatically invoked while an instance of the class is destroyed. Destructor is used to write the code that needs to be executed while an instance is destroyed. To create a destructor, create a method in the class with same name as class preceded with ~ symbol.

Syntax :

~ClassName()
{

}


Example : The following example creates a class with one constructor and one destructor. An instance is created for the class within a function and that function is called from main. As the instance is created within the function, it will be local to the function and its life time will be expired immediately after execution of the function was completed.


using System;

namespace ProgramCall
{
class myclass
{

public myclass()
{

Console.WriteLine("An Instance Created");
}

//destructor
~myclass()
{
Console.WriteLine("An Instance Destroyed");
}
}


class Destructor
{
public static void Create()
{
myclass T = new myclass();
}


static void Main()
{

Create();
GC.Collect();

Console.Read();
}
}
}



Output

An Instance Created
An Instance Destroyed


If this post helps you mark it as answer
Thanks

Rahmankhan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 8/27/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
These are the more examples on constructors & destructors
http://www.programcall.com/21/csnet/constructor-and-destructor-invoking-sequence-with-inheritance.aspx
http://www.c-sharpcorner.com/uploadfile/82b15a/constructors-and-destructors-in-C-Sharp-net/
http://msdn.microsoft.com/en-us/library/vstudio/ms173115.aspx
http://www.youtube.com/watch?v=hRr0yavL7o0


Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Rahmankhan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 8/27/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Constructor and Destructor In C#
We know that all objects that are created must be given initial values.we have used two approach to initialize the value of all the variables without constructors.

The first approach uses the dot operator to access instance variables and then assigns values to them individually. It can be a tedious approach to initialize all the variables of all the objects.
The second approach takes the help of a function like 'GetData' to initialize each object individually using statement like;
rect1.GetData(30,20);
Constructor:-
Constructor is like a method which may contain some certain set of statement, But constructor does not have any Return Type and it will have the same name as the Class Name.
A Constructor is called automatically when object of class created.Basically constructor is used to Initialize the data member of class.We can use constructor overloading also in the program.
In case of parent child relationship ,when we make the object of child class, then child class constructor is called and base class default constructor is executed.
EXAMPLE:-
using System; 

namespace CONSTRUCTOR
{
class Program
{
static void Main(string[] args)
{
employee emp = new employee("noida");//parameterised constructor of employee class is called which takes one aguments and default constructor of cls class is called.
Console.WriteLine(emp.sname); // default constructor of cls class is called which takes no aguments
Console.WriteLine(emp.address); //default constructor of employee class is called which takes no aguments
Console.ReadLine();
}
}
public class cls
{
public string sname;

public cls()
{
sname = "abc";
Console.WriteLine("Default constructor of cls");
}
public cls(string ram)
{
sname = ram;
Console.WriteLine("paramerterise constructor of cls");
}
}
public class employee : cls
{
public string address;
public employee()
{
address = "mohannagar";
Console.WriteLine("default constuctor of employee");
}
public employee(string shayam)
{
address = shayam;
Console.WriteLine("paramerised constructor of employee");
}
}
}

RUN above program: Open console application in your visual studio-> copy the above the code and paste in Program.cs file->Run the application.

If we want to call a specific constructor of the base class through child class, the we can specify the "base" keyword with child class constructor.
using System; 

namespace BASE_KEYWORD_CONSTRUCTOR
{
class Program
{
static void Main(string[] args)
{
employee emp = new employee("DELHI");
Console.WriteLine(emp.sname);
Console.WriteLine(emp.address);
Console.ReadLine();
}
}
public class cls
{
public string sname;

public cls()
{
sname = "abc";
Console.WriteLine("define constructor of cls");
}
public cls(string ram)
{
sname = ram;
Console.WriteLine("paramerterise constructor of cls");
}
}
public class employee : cls
{
public string address;
public employee()
{
address = "mohannagar";
Console.WriteLine("define constuctor of emp");
}
public employee(string shayam): base(shayam)
{
address = shayam;
Console.WriteLine("paramerised constructor of employee");
}
}

}


Constructor are usually Public ,because they are provided to create objects. we can use Private or Protected constructors also when we are using inheritance

Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Rahmankhan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Bandi on: 8/27/2013 [Member] [MVP] Platinum | Points: 25

Up
0
Down
Type of Constructors:- There are some type of constructor which are use in our program.

Static Constructor:- Static member are those which is not changeable over whole program. Static Constructor is called automatically by CLR when class is loaded in first time in memory,before any object of class is created.
Non Static Constructor:- Non static member are those member which is dynamically changes over the program. Non Static constructor(Instinct Constructor) is called whenever object of the class is created.
using System; 

using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text;
using System.Windows.Forms;
namespace STATIC_AND_NONSTATIC_CONSTRUCTOR
{
class Program
{
static void Main(string[] args)
{
student obj1 = new student();
student obj2 = new student("s");
student.pname="pname is Rajesh";
MessageBox.Show(student.pname);
}
}

public class student
{
public static string pname;
public string saddress;
static student()
{
pname = "Microsoft";
MessageBox.Show("STATIC CONSTRUCTOR IS CALLED");

}
public student()
{
MessageBox.Show("NON STATIC CONSTRUCTOR IS CALLED");
}
public student(string sadd)
{
string saddress = sadd;
MessageBox.Show("NON STATIC PARAMETERISED CONSTRUCTOR IS CALLED");
}
}
}

3. Private Constructor:- In many situation, we may wish to define some utility classes that contain only static member such classes are never required to instantiate objects.Creating objects using such classes may be prevented by adding private constructor to the class.
4. Copy Constructor:- A copy constructor creates an object by copying variables from another object. Since C# does not provided a copy constructor ,we must provide it ourselves if we wish to add this feature to the class.
Public value(value value) 

{
code= value.code;
price=value.price;
}
// creating objects in main class
value value2= new value(value1);


Note:- Here value2 is a copy of value1.
Important Points:
Constructor Overloading:- Constructor overloading is like method overloading , In this we have used same name but different signature of the Constructor. we have already discussed about signature in our previous post. This is called constructor overloading. Constructor overloading is used when object are required to perform similar task but using different input parameters. In Constructor overloading we use same name Constructor but there signature is different to perform similar functionality in programs.
This Keyword in C#:- When we refer to current member of the class then we can use "This" Keyword to refer that member.
If we want to call a specific constructor of class through another constructor of the same class then we can specify "This" keyword with that constructor.


Destructor:-
It is also like a method. It has not any return type and will have the same name as the class name but but prefix is used '~'(tilde).
It is called automatically when the object is no more than use,so to deallocate the memory used by resources within the class.
Destructor takes no arguments, so we can use only one destructor within the class and there will not use any access specifier with destructor.
Class student 

{
~student() // No arguments
{
-------------------------------------
}
}


Mark This Response as Answer
--
Chandu
http://www.dotnetfunda.com/images/dnfmvp.gif

Rahmankhan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rahmankhan on: 8/30/2013 [Member] Starter | Points: 25

Up
0
Down
thnks bandi

Rahmankhan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rahmankhan on: 8/30/2013 [Member] Starter | Points: 25

Up
0
Down
thnks Satyapriyanayak

Rahmankhan, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response