Showing posts with label Oops Concept. Show all posts
Showing posts with label Oops Concept. Show all posts

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 ...