C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !






Constructors and Destructors in C#


Posted Date: 09 Aug 2008    Resource Type: Articles    Category: .NET Framework
Author: Gaurav AroraMember Level: Gold    
Rating: Points: 10



A constructor is a method, which is called when an object of a class type
is constructed, and it usually used for initialization. A constructor method has
following characteristics:


  • It has the same name as class

  • It has no return type

  • It does not return any value

  • Constructors are always public and we use them to initialize variable.

  • There is default class constructor without parameter, provided by C# internally if we did not write any constructor.



Note : You can declare private constructors also, when you don't want to allow clients to directly handle your class.


/* This Example is a part of different
* examples shown in Book:
* C#2005 Beginners: A Step Ahead
* Written by: Gaurav Arora
* Reach at : gaurav.aroraose@yahoo.co.in*/

// File name : privateconstructor.cs

using System;

namespace CSharp.AStepAhead.privateconstructor
{

class privateconstructor
{
private privateconstructor()
{
//This constructor never handle from client
Console.WriteLine("This is a private constructure, can't access outside");
}
public privateconstructor(int x, int y)
{
Console.WriteLine("This is a Public ocnstructore");
Console.WriteLine("X:{0}, Y:{1} X * Y : {2}", x, y, x * y);
}

//static void Main()
//{
// //Create an object of class
// privateconstructor objClass;
// objClass = new privateconstructor();
// objClass = new privateconstructor(4, 5);
// Console.ReadLine();
//}

}

class class1
{
static void Main()
{
//Create an object of class
privateconstructor objClass;
//objClass = new privateconstructor();//Neevr access from here
objClass = new privateconstructor(4, 5);
Console.ReadLine();
}
}
}


Static Constructors
Static constructors are automatically initialize when class initializes, we can
directly use the class members without creating the instance of that class



/* This Example is a part of different
* examples shown in Book:
* C#2005 Beginners: A Step Ahead
* Written by: Gaurav Arora
* Reach at : gaurav.aroraose@yahoo.co.in*/

// File name : privateconstructor.cs

using System;

namespace CSharp.AStepAhead.privateconstructor
{

class privateconstructor
{
private privateconstructor()
{
//This constructor never handle from client
Console.WriteLine("This is a private constructure, can't access outside");
}
public privateconstructor(int x, int y)
{
Console.WriteLine("This is a Public ocnstructore");
Console.WriteLine("X:{0}, Y:{1} X * Y : {2}", x, y, x * y);
}

//static void Main()
//{
// //Create an object of class
// privateconstructor objClass;
// objClass = new privateconstructor();
// objClass = new privateconstructor(4, 5);
// Console.ReadLine();
//}

}

class class1
{
static void Main()
{
//Create an object of class
privateconstructor objClass;
//objClass = new privateconstructor();//Neevr access from here
objClass = new privateconstructor(4, 5);
Console.ReadLine();
}
}
}


In the other hand a Destructor is also called a finalizer. It is just opposite the constructor, it is a method called when the garbage collector reclaims an object.

Constructors have following characteristics:


  • The name of a destructor is same as name of class

  • The destructor declared with a tilde (~).

  • Destructors are always public and never other than public.

  • Destructors take no arguments. So, there is only one destructor per class.

  • Destructors have no return type.





Similarities in Class and Structure




  • Both can have constructor, methods, properties, fields, constants, enumerations, events and event handlers.

  • Structures and Classes can implement interface.

  • Both of them have constructors with or without parameters.

  • Both can have delegates and events.



Differences in Class and Structure


  • Structures are value type and classes are reference type

  • Structures are stored on Stack and Classes are on heap in memory.

  • Structure members can’t be declared as protected, but class member can be.

  • Structures cant allow inheritance

  • Structure do not require constructor while Classes require.

  • Objects created from classes are terminated using Garbage Collection. Structures are not collected by GC.

  • Structure variables each have their own copy of the data. In Class it is possible for two variables to reference the same object. Not possible for values of a struct type to be null. Class type value may be null.

  • A structure is not permitted to declare a destructor. But, you can declare a class destructor using (~) tilde.



For more details, visit http://www.msdotnetheaven.com/ChaptersCsharp/csharplanguageii.htm#




Responses

Author: InterviewsWorld    13 Aug 2008Member Level: Silver   Points : 2
Nice description but you have very less info about static constructor.

Static constructors have the following properties:

*

A static constructor does not take access modifiers or have parameters.
*

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
*

A static constructor cannot be called directly.
*

The user has no control on when the static constructor is executed in the program.
*

A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
*

Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

know more...go here

http://www.interviewsworld.com

http://msdn.microsoft.com/en-us/library/k9x6w0hc(vs.80).aspx





Author: Gaurav Arora    13 Aug 2008Member Level: Gold   Points : 1
Hi Interviewworlds,

Thanks for updation. The motive of above article is to describe imlementation of constructors.

Thanks & regards,
Gaurav Arora


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Interview  .  Discussion  .  Destructors in C#  .  Destructor  .  Contructors and Destructors in C#  .  Constructors in C#  .  Constructor  .  Class  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: String Operations in C#
Previous Resource: Abstract Classes and Abstract Method(s)
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design


Contact Us    Privacy Policy    Terms Of Use