CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Wednesday, October 11, 2006

Working with normal and static constructor in C# 2.0

Working with normal and static constructor in C# 2.0

This Code snippet explains when a normal constructor and static constructor gets initialized. After going through this code snippet, reader gets a clear cut understanding of the steps involved in object initialization (Both static and non-static)

 
 
 
 
 
 

In C#, constructor is defined as a method which gets called whenever an object is created. A constructor may or may not have arguments without any return type. In C#, we also have static constructors. Static constructors are used to initialize Static variables. Let us understand how and when these constructors get called.

The code below explains when an instance constructor gets called in class.

Listing 1

using System;
public class A
{
  //Constructor of Class A
  public A()
  {
    Console.WriteLine("Constructor of Class A");
  }
public class B: A
{
  //Constructor of Class B
  public B()
  {
    Console.WriteLine("Constructor of Class B");
  }
}
public class C: B
{
  //Constructor of Class C
  public C()
  {
    Console.WriteLine("Constructor of Class C");
  }
}
public class Client
{
  static void Main(string[]args)
  {
    // Initializing the class C's constructor.
    C c = new C();
    Console.Read();
  }
}
 

Post a Comment