mobile ads

Friday 29 November 2013

Constructors

A constructor is a method in the class which gets executed when its object is created. Whenever a class or struct is created, its constructor is called. Even if we don't write the constructor code, default constructor will be created and called first when object is instantiated and sets the default values to members of claas. A class or struct may have multiple constructors that take different arguments.
 Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.Constructors have the same name as Class
Default constructor will no take parameters and will be invoked when instance is created.
We can prevent the class instantiation by declaring the constructor as private
class sample
{
      private sample()
     {
      }
}
Classes can define the constructors with parameter also and must be called by "new" keyword.
class sample
{
   public int y;
   public sample (int i)
   {
        y=i;
    }
}
constructor with parameters.
sample s= new sample(10);
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only, and does not take access modifiers or have parameters.It is called automatically before the first instance is created or any static members are referenced.
It is called automatically to initialize the class before the first instance is created or any static members are referenced. The user has no control on when the static constructor is executed.
class SimpleClass
{
    // Static variable that must be initialized at run time.
    static readonly long baseline;
    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}
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.
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.
It is mandatory to have the constructor in the class and that too should be accessible for the object i.e., it should have a proper access modifier. Say, for example, we have only private constructor(s) in the class and if we are interested in instantiating the class, i.e., want to create an object of
 the class, then having only private constructor will not be sufficient and in fact it will raise an error. So, proper access modifies should be provided to the constructors.

0 comments:

Post a Comment