Thursday, December 8, 2011

Jquery Load DropDownList form server Side DataTable Using Json

Server side code


[System.Web.Script.Services.ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[System.Web.Services.WebMethod]


public static string GetValue()
{


System.Data.DataTable dt = new System.Data.DataTable();


dt.Columns.Add("EmpId", typeof(string));


dt.Columns.Add("EmpName", typeof(string));




dt.Rows.Add("001", "Mohan");
dt.Rows.Add("002", "Raja");
dt.Rows.Add("001", "Mohan1");
dt.Rows.Add("002", "Raja32");
dt.Rows.Add("001", "Mohan4");
dt.Rows.Add("002", "Raja6");
dt.Rows.Add("001", "Mohan7");
dt.Rows.Add("002", "Raja8");




string sJSON = JSON_DataTable(dt);


return sJSON;


}




Buliding Json Format


public static string JSON_DataTable(DataTable dt)
{


StringBuilder JsonString = new StringBuilder();


//Exception Handling
if (dt != null && dt.Rows.Count > 0)
{
JsonString.Append("{ ");
JsonString.Append("\"Head\":[ ");


for (int i = 0; i < dt.Rows.Count; i++)
{
    JsonString.Append("{ ");
    for (int j = 0; j < dt.Columns.Count; j++)
    {
      if (j < dt.Columns.Count - 1)
       {
         JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() +"\":" + "\"" +
         dt.Rows[i][j].ToString() + "\",");
       }
   else if (j == dt.Columns.Count - 1)
   {
      JsonString.Append("\"" +
     dt.Columns[j].ColumnName.ToString() + "\":" +
      "\"" + dt.Rows[i][j].ToString() + "\"");
  }
}


/*end Of String*/
if (i == dt.Rows.Count - 1)
{
   JsonString.Append("} ");
}
else
{
   JsonString.Append("}, ");
}
}


   JsonString.Append("]}");
   return JsonString.ToString();
}
else
{
  return null;
}


}


Client Side Code


$(document).ready(function () {
$('#'').mouseover(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetValue",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {


$("#DropDownList1").get(0).options.length = 0;
$("#DropDownList1").get(0).options[0] = new Option("Select", "-1");


var Result = $.parseJSON(msg.d);


$.each(Result.Head, function () {
//alert(this.EmpId + " " + this.EmpName);


$("#DropDownList1").get(0).options[$("#DropDownList1").get(0).options.length] = new Option(this.EmpName, this.EmpId);
});


},
error: function () {
alert("Failed to load");
}
})
return false;


});


});




HTML Code

Above Code:




 
Below Code:


 







Dynamically Pass controlId to method

function MyConfirmMethod(ControlName) {


var control1 = ControlName.id;


$.ajax({
type: "POST",
url: "Default.aspx/GetValue",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {


document.getElementById(control1).options.length = 0;


document.getElementById(control1).options.length = 0;
document.getElementById(control1).options[0] = new Option("Select", "-1");


var Result = $.parseJSON(msg.d);


$.each(Result.Head, function () {
//alert(this.EmpId + " " + this.EmpName);


document.getElementById(control1).options[document.getElementById(control1).options.length] = new Option(this.EmpName, this.EmpId);
});


},
error: function () {
alert("Failed to load");
}
})
return false;
}

Thursday, November 10, 2011

Convert Var variable LINQ Query to DataTable - 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Reflection;

namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)
{

DataTable dtTest = new DataTable();
dtTest.Columns.Add("Title", typeof(string));

DataRow dr = dtTest.NewRow();
dr["Title"] = "AAA";
dtTest.Rows.Add(dr);

DataRow dr1 = dtTest.NewRow();
dr1["Title"] = "BBB";
dtTest.Rows.Add(dr1);

DataRow dr2 = dtTest.NewRow();
dr2["Title"] = "CCC";
dtTest.Rows.Add(dr2);

var query = from m in dtTest.AsEnumerable()
group m by m["Title"] into g
select new { Title = g.Key, Count = g.Count() };

DataTable dt = LinqtoDataTablequery();

GridView1.DataSource = dt;
GridView1.DataBind();

}


public DataTable LinqtoDataTable(IEnumerable varlist)
{
  DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
   // Use reflection to get property names, to create table, Only first time, others will follow
   if (oProps == null)
    {
        oProps = ((Type)rec.GetType()).GetProperties();
        foreach (PropertyInfo pi in oProps)
        {
           Type colType = pi.PropertyType;

            if ((colType.IsGenericType)(colType.GetGenericTypeDefinition()== typeof(Nullable)))
               {
                 colType = colType.GetGenericArguments()[0];
               }

          dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
        }
   }

  DataRow dr = dtReturn.NewRow();
 foreach (PropertyInfo pi in oProps)
 {
     dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
 }
 dtReturn.Rows.Add(dr);
}
return dtReturn;
}
}
}

Friday, October 28, 2011

ASP.NET page life cycle Events

 When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal. In this article, I will discuss in detail the ASP.NET page life cycle Events.The page's life cycle in the order listed below:
1. PreInit
2. Init
3. InitComplete
4. PreLoad
            a. Loads ViewState
            b. Loads Postback data
5. Load
6. Control (PostBack) event(s)
7. LoadComplete
8. PreRender
9. SaveStateComplete
10. Render
11. UnLoad

PreInit:
The entry point of the page life cycle is the pre-initialization phase called “PreInit”. This is the only event where programmatic access to master pages and themes is allowed. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_PreInit(object sender, EventArgs e)
{

// Check the IsPostBack property to determine whether this is the first time the page is being processed.

// Create or re-create dynamic controls.

// Set a master page dynamically.

// Set the Theme property dynamically.

}

Init:
This event fires after each control has been initialized, each control's UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_Init(object sender, EventArgs e)
{

// Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.

}

InitComplete :
Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_InitComplete(object sender, EventArgs e)
{

// Raised by the Page object. Use this event for processing tasks that require all initialization be complete.

}

PreLoad : Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance

(1)Loads ViewState : ViewState data are loaded to controls

Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden control that is passed from page request to page request.

(2)Loads Postback data : postback data are now handed to the page controls

Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnPreLoad(EventArgs e)
{

// Use this event if you need to perform processing on your page or control before the Load event. // Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

}

Load: The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_Load(object sender, EventArgs e)
{

// The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.

// Use the OnLoad event method to set properties in controls and establish database connections.

}

Control (PostBack) event(s): ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown's selectedindexchange event, for example.These are the events, the code for which is written in your code-behind class(.cs file).

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Button1_Click(object sender, EventArgs e)

{

// This is just an example of control event.. Here it is button click event that caused the postback

}

LoadComplete : This event signals the end of Load.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_LoadComplete(object sender, EventArgs e)
{
           // Use this event for tasks that require that all other controls on the page be loaded.
}

PreRender : Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnPreRender(EventArgs e)
{

// Each data bound control whose DataSourceID property is set calls its DataBind method.

// The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

}

SaveStateComplete : Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnSaveStateComplete(EventArgs e)
{

// Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.

// Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

}

Render : This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

Note: Right click on the web page displayed at client's browser and view the Page's Source. You will not find any aspx server control in the code. Because all aspx controls are converted to their respective HTML representation. Browser is capable of displaying HTML and client side scripts.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

// Render stage goes here. This is not an event

UnLoad : This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on-

(a)Instances of classes i.e. objects

(b)Closing opened files

(c)Closing database connections.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_UnLoad(object sender, EventArgs e)
{

// This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

// During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream.

//If you attempt to call a method such as the Response.Write method, the page will throw an exception.

}

Thursday, October 6, 2011

Constructor Vs Static Constructor

A Constructor is usually used to initialize data. However Static Constructor is used to initialize only static members. Here I am just talking about the Constructors. How they get initialized and how they behave.

Things to know about Static Constructor
  1. It is used to initialize static data members.
  2. Can't access anything but static members.
  3. Can't have parameters
  4. Can't have access modifiers like Public, Private or Protected.
Now once you understand the above points, you can appreciate the difference between Static Class and Unstatic Class
  1. Static Class cannot be instantiated unlike the unstatic class. You should directly access its Method via the ClassName.MethodName
  2. A Program can't tell when it is going to load static class but its definitely loaded before the call.
  3. A Static class will always have the static constructor and its called only once since after that its in the memory for its lifetime.
  4. A Static class can contain only static members. So all the members and functions have to be static.
  5. A Static class is always sealed since it cannot be inherited further. Further they cannot inherit form any other class (except Object)
Let's look at a normal Constructor

class
Program
{
static void Main(string[] args)
{
/* Note two things
1.Here you get to instantiate the Constructor in the code wherever you like.
2.If you debug you get to goto the Constructor and see what is being done.
*/
MyExample myExample = new MyExample();
myExample.Print();
}
}

public class MyExample
{
private static int StaticVariable ;
public MyExample()
{

if (StaticVariable < 10)
{
StaticVariable = 20;
}
StaticVariable = 100;
}
}
public void Print()
{
Console.WriteLine(StaticVariable);
}
}
Now consider this second example for static class

class
Program
{
static void Main(string[] args)
{
/* Note the following
1.You dont get to instantiate for sure so you dont know when the constructor was called.
2.Secondly you can access your method directly.
*/
//MyExampleStatic myExampleStatic = new MyExampleStatic();
MyExampleStatic.Print();
}
}
static class MyExampleStatic
{
private static int StaticVariable;
static MyExampleStatic()
{
if (StaticVariable < 10)
{
StaticVariable = 20;
}
else
{
StaticVariable = 100;
}
}
public static void Print()
{
Console.WriteLine(StaticVariable);
}
}
The point is that static member could be used only by a static Constructor or static Function. Hope you have a Static Constructing life.

Static Class in C#

 A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example: UtilityClass.MethodA();
 A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.
The following list provides the main features of a static class:
  • Contains only static members.
  • Cannot be instantiated.
  • Is sealed.
  • Cannot contain Instance Constructors.
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can contain a static constructor. Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization.
Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.

public static class TemperatureConverter
{
    public static double CelsiusToFahrenheit(string temperatureCelsius)
    {
        // Convert argument to double for calculations.
        double celsius = Double.Parse(temperatureCelsius);

        // Convert Celsius to Fahrenheit.
        double fahrenheit = (celsius * 9 / 5) + 32;

        return fahrenheit;
    }

    public static double FahrenheitToCelsius(string temperatureFahrenheit)
    {
        // Convert argument to double for calculations.
        double fahrenheit = Double.Parse(temperatureFahrenheit);

        // Convert Fahrenheit to Celsius.
        double celsius = (fahrenheit - 32) * 5 / 9;

        return celsius;
    }
}

class TestTemperatureConverter
{
    static void Main()
    {
        Console.WriteLine("Please select the convertor direction");
        Console.WriteLine("1. From Celsius to Fahrenheit.");
        Console.WriteLine("2. From Fahrenheit to Celsius.");
        Console.Write(":");

        string selection = Console.ReadLine();
        double F, C = 0;

        switch (selection)
        {
            case "1":
                Console.Write("Please enter the Celsius temperature: ");
                F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
                Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
                break;

            case "2":
                Console.Write("Please enter the Fahrenheit temperature: ");
                C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());
                Console.WriteLine("Temperature in Celsius: {0:F2}", C);
                break;

            default:
                Console.WriteLine("Please select a convertor.");
                break;
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
} 
 Example Output:
    Please select the convertor direction
    1. From Celsius to Fahrenheit.
    2. From Fahrenheit to Celsius.  :2
    Please enter the Fahrenheit temperature: 20
    Temperature in Celsius: -6.67
    Press any key to exit.


Constructor and Destructor

A constructor can be used, where every time an object gets created and if we want some code to be executed automatically. The code that we want to execute must be put in the constructor. The general form of a C# constructor is as follows 

modifier constructor_name (parameters)
{
//constructor body
} 


The modifiers can be private,public, protected or internal.The name of a constructor must be the name of the class, where it is defined. A constructor can take zero or more arguments. A constructor with zero arguments (that is no-argument) is known as default constructor. Remember that there is not return type for a constructor. 

The following class contains a constructor, which takes two arguments

class Complex
{
private int x;
private int y;
public Complex (int i, int j)
{
x = i;
y = j;
}
public void ShowXY ()
{
Console.WriteLine(x + "i+" + y);
}
}

The following code segment will display 20+i25 on the command prompt. 


Complex c1 = new Complex (20,25);
c1.ShowXY (); // Displays 20+i25 


That is when we create the object of the class Complex, it automatically calls the constructor and initializes its data members x and y. We can say that constructor is mainly used for initializing an object. Even it is possible to do very complicated calculations inside a constructor. The statement inside a constructor can throw exceptions also. 

If we don't provide a constructor with a class, the C# provides a default constructor with an empty body to create the objects of the class. Remember that if we provide our own constructor, C# do not provide the default constructor.

The complete program is given below
// C# constructor example
using System;
class Complex
{
private int x;
private int y;
public Complex(int i, int j) // constructor with 2 arguments
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine(x +"i+" + y);
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(20,25);
c1.ShowXY();
}
}

Constructor Overloading

Just like member functions, constructors can also be overloaded in a class. The overloaded constructor must differ in their number of arguments and/or type of arguments and/or order of arguments.
The following program shows the overloaded constructors in action.
// C# constructor overloading
 

using System;
class Complex
{
public Complex(int i, int j)
{
Console.WriteLine("constructor with 2 integer arguemets");
}
public Complex(double i, double j)
{
Console.WriteLine("constructor with 2 double arguments");
}
public Complex()
{
Console.WriteLine("no argument constructor");
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(20,25);// displays 'constructor with 2 integer arguments'
Complex c2 = new Complex(2.5,5.9); // displays 'constructor with 2 double arguments'
Complex c3 = new Complex(); displays 'no argument constructor'
}
} 


Private Constructors
We already see that, in C#, constructors can be declared as public, private, protected or internal. When a class declares only private constructors, it is not possible other classes to derive from this class or create an instance of this class. Private constructors are commonly used in classes that contain only static members. However a class can contain both private and public constructor and objects of such classes can also be created, but not by using the private constructor.
The following is a valid program in C# 
// C# constructor both private & public

using System;
class Complex
{
private Complex(int i, int j)
{
Console.WriteLine("constructor with 2 integer arguments");
}
public Complex()
{
Console.WriteLine("no argument constructor");
}
}
class MyClient
{
public static void Main()
{
Complex c3 = new Complex();
}
}

However the following program do not compile since it contain only private constructors 


// C# constructor only private. Will show compilation error.

using System;
class Complex
{
private Complex()
{
Console.WriteLine("no argument constructor");
}
}
class MyClient
{
public static void Main()
{
Complex c3 = new Complex();
}
}
public void Method1()
{
Console.WriteLine("Method of a non-abstract class");
}
}

Constructor Chaining

The entire above program shows that C# supports constructor overloading. In C#, even one constructor can invoke another constructor in the same class or in the base class of this class. This is what is known as constructor chaining. A special type of syntax is used for constructor chaining as follows.
// C# constructor chaining

using System;
class Complex
{
private Complex()
{
Console.Write("1");
}
private Complex(int x):this()
{
Console.Write("2");
}
public Complex(int x, int y):this(10)
{
Console.Write("3");
}
}
class MyClient
{
public static void Main()
{
Complex c = new Complex(10,20); // Displays 123
}
}

In the above program the Complex(int x, int y) invokes the Complex(int x) constructor by using a special syntax ':' this(arguments), which in turn invokes the Complex() constructor.

Static Constructors
The normal constructors, which we explained till now, can be used for the initialization of both static and non-static members. But C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first. Remember that, just like any other static member functions, static constructors can't access non-static data members directly. 

The name of a static constructor must be the name of the class and even they don't have any return type. The keyword static is used to differentiate the static constructor from the normal constructors. The static constructor can't take any arguments. That means there is only one form of static constructor, without any arguments. In other way it is not possible to overload a static constructor.

We can't use any access modifiers along with a static constructor.
For example  C# static constructor

using System;
class Complex
{
static Complex()
{
Console.WriteLine("static constructor");
}
}
class MyClient
{
public static void Main()
{
Complex c;
Console.WriteLine("RAJESH");
c = new Complex();
}
}

The output of the above program is
RAJESH
static constructor

Note that static constructor is called when the class is loaded at the first time. However we can't predict the exact time and order of static constructor execution. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called. 

Like non-static constructors, static constructors can't be chained with each other or with other non-static constructors. The static constructor of a base class is not inherited to the derived class. 

Constructors with  Inheritance
Both static and non-static constructors are not inherited to a derived class from a base class. However, a derived class non-static constructor can call a base class non-static constructor by using a special function base(). It is possible to invoke both default and parametrized constructors of the base class from the derived class. If we don't call the base class constructor explicitly, the derived class constructor will call the default constructor of the base class implicitly when an object of the derived class is created. This is shown in the program given below.
// C# Implicit call of base class default constructor
 

using System;
class Base
{
   public Base()
   {
     Console.WriteLine("base constructor");
   }
}
class Derived : Base
{
}
class MyClient
{
  public static void Main()
  {
    Derived d1 = new Derived();//Displays 'base constructor'
  }
}

We can also call a base class constructor explicitly by using base() as shown below.

// C# Implicit call of base class default constructor
 
using System;
class Base
{
public Base()
{
Console.WriteLine("BASE 1");
}
public Base(int x)
{
Console.WriteLine("BASE 2");
}
}
class Derived : Base
{
public Derived():base(10)
{
Console.WriteLine("DERIVED CLASS");
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();//Displays 'base constructor'
}
}

This program outputs
BA SE2
DERIVED CLASS

The base() can be used for chaining constructors in a inheritance hierarchy.


Destructors
The .NET framework has an in built mechanism called Garbage Collection to de-allocate memory occupied by the un-used objects. The destructor implements the statements to be executed during the garbage collection process. A destructor is a function with the same name as the name of the class but starting with the character ~.

Example:

class Complex
{
public Complex()
{
// constructor
}
~Complex()
{
// Destructor
}
}

Remember that a destructor can't have any modifiers like private, public etc. If we declare a destructor with a modifier, the compiler will show an error.Also destructor will come in only one form, without any arguments. There is no parameterized destructor in C#.

Destructors are invoked automatically and can't be invoked explicitly. An object becomes eligible for garbage collection, when it is no longer used by the active part of the program. Execution of destructor may occur at any time after the instance or object becomes eligible for destruction.
In C# all classes are implicitly derived from the super base class object. The object class contains one special method, Finalize(), which every class can override. The Garbage Collection mechanism in .NET will call this method prior to the garbage collection of the objects this class. Remember when we provide a destructor in a class, during the compilation time, the compiler automatically generates the Finalize() method. That means that a destructor and overridden Finalize() method can't co-exist in a class. The following code will generate a compilation error because of the above program

class Complex
{
~Complex()
{
}
protected override void Finaliz()
{
}
} 





Constructor in C#

In this article I will explain the constructor concept in C# along with practical demonstration which will help you to understand it in a simple way.

What is constructor?
 
o    Constructor is used to initialize an object (instance) of a class.
o    Constructor is a like a method without any return type.
o    Constructor has same name as class name.
o    Constructor follows the access scope (Can be private, protected, public, Internal and external).
o    Constructor can be overloaded.

Constructors generally following types :
 
o    Default Constructor
o    Parameterized constructor
o    Private Constructor
o    Static Constructor
o    Copy Constructor.

The constructor goes out of scope after initializing objects.

Default Constructor

A constructor that takes no parameters is called a default constructor.
When a class is initiated default constructor is called which provides default values to different data members of the class.

You need not to define default constructor it is implicitly defined.

Practical: Default Constructor
Note: In the above practical example if you don't create a constructor still there will be a default constructor, which will initialize the data members of the class with some legal values.

Parameterized constructor


Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.

Practical: Parameterized Constructor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace parameterized_constructor
{
class Program
{
   class c1
     {
        int a, b;

        public c1(int x, int y)
        {
          this.a = x;
          this.b = y;
        }

public void  display()
{
   Console.WriteLine("Value of a: {0}", a);
   Console.WriteLine("Value of b: {0}", b);
}
       }

static void Main(string[] args)
{
// Here when you create instance
of the class parameterized constructor will be called.
c1 ob1 = new c1(10, 20);
ob1.display();
Console.ReadLine();
}
}
}

Private Constructor

Private constructors are used to restrict the instantiation of object using 'new' operator. A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. This type of constructors is mainly used for creating singleton object. If you don't want the class to be inherited we declare its constructor private. We can't initialize the class outside the class or the instance of class can't be created outside if its constructor is declared private. We have to take help of nested class (Inner Class) or static method to initialize a class having private constructor.


Practical: Private Constructor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace private_constructor
{
class Program
{

class c1
{
int a, b;

// Private constructor declared here
private c1(int x, int y)
{
this.a = x;
this.b = y;
}

public static c1 create_instance()
{
return new c1(12,20);
}

public void display()
{
int z = a + b;
Console.WriteLine(z);
}
}

static voidMain(string[] args)
{
// Here the class is initiated
using a static method of the class than only you can use private
constructor
c1 ob1 = c1.create_instance();
ob1.display();
Console.ReadLine();
}
}
}



Static Constructors

C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor).

Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. Non-static constructors are inline and are faster.
Static constructors are used to initializing class static data members.

Point to be remembered while creating static constructor:

1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.

Static members are preloaded in the memory. While instance members are post loaded into memory.
Static methods can only use static data members.

Practical: Static Constructor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace static_eg
{

class Program
{

public class test
{
static string name;
static int age;

static test()
{
Console.WriteLine("Using static constructor to initialize static
data members");
name = "John Sena";
age = 23;
}

public static void display()
{
Console.WriteLine("Using static function");
Console.WriteLine(name);
Console.WriteLine(age);
}

}

static void Main(string[] args)
{
test.display();
Console.ReadLine();
}
}
}

Copy Constructor
If you create a new object and want to copy the values from an existing object, you use copy constructor.
This constructor takes a single argument: a reference to the object to be copied.

Practical: Copy Constructor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace copy_constructor
{

class Program
{

class c1
{
int a, b;

public c1(int x, int y)
{
this.a = x;
this.b = y;
}

// Copy construtor
public c1(c1 a)
{
this.a = a.a;
this.b = a.b;
}

public void display()
{
int z = a + b;
Console.WriteLine(z);
}
}

static void Main(string[] args)
{
c1 ob1 = new c1(10,20);
ob1.display();
// Here we are using copy constructor. Copy constructor is using the
values already defined with ob1
c1 ob2 = new c1(ob1);
ob2.display();
Console.ReadLine();
}
}
}
Copy constructor sets behavior during runtime. It is shallow copying.
I would be glad to share my knowledge and waiting for your feedback to increase my knowledgebase.

Abstract Factory Vs Factory Method

Abstract Factory Provides an interface for creating families of related or dependent objects without specifying their concrete classes ...