We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Saturday, May 16, 2015

Constructor in C#


A constructor is a special method available under every class which is responsible for initializing the variables of the class. 
Constructor is a special method of a class which will invoke automatically whenever instance or object of class is created. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class.

Note:
->Constructors don’t have any return type, not even void and within a class we can create only one static constructor.
->constructor name should be same as class name.

Example

class Test
{
public Test()
{
Console.WriteLine(" Test Method");
}
}


Types of Constructors

Basically constructors are 5 types those are

      1.    Default Constructor
      2.    Parameterized Constructor
      3.    Copy Constructor
      4.    Static Constructor
      5.    Private Constructor

Default Constructor

A constructor without having any parameters called default constructor. In this constructor every instance of the class will be initialized without any parameter values like as shown below.


using System;
namespace ConsoleApplication1
{
class Sample
{
public string param1, param2;
public Sample()     // Default Constructor
{
param1 = "Welcome";
param2 = "Hi friends";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample();   // Once object of class created automatically constructor will be called
Console.WriteLine(obj.param1);
Console.WriteLine(obj.param2);
Console.ReadLine();
}
}
}

Output:
Welcome
Hi friends


Parameterized Constructors

A constructor with at least one parameter is called as parameterized constructor. In parameterized constructor we can initialize each instance of the class to different values like as shown below


using System;
namespace ConsoleApplication1
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample("Welcome","dotNet Solution");   // Parameterized Constructor Called
Console.WriteLine(obj.param1 +" to "+ obj.param2);
Console.ReadLine();
}
}
}
Output:
Welcome to DotNet Solution


Constructor Overloading

In c# we can overload constructor by creating another constructor with same method name and different parameters like as shown below

using System;
namespace ConsoleApplication1
{
class Sample
{
public string param1, param2;

public Sample()     // Default Constructor
{
param1 = "Hi";
param2 = "I am Default Constructor";
}
public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample();   // Default Constructor will Called
Sample obj1=new Sample("Welcome","DotNet Solution");   // Parameterized Constructor will Called
Console.WriteLine(obj.param1 + ", "+obj.param2);
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
Output:
I am Default Constructor
Welcome to DotNet Solution


Copy Constructor

A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance.


using System;
namespace ConsoleApplication1
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)
{
param1 = x;
param2 = y;
}
public Sample(Sample obj)     // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome""DotNet Solution");  // Create instance to class Sample
Sample obj1=new Sample(obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}
Output:
welcome to Dotnet Solution


Static Constructor

When we declared constructor as static it will be invoked only once for any number of instances of the class and it’s during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.
-What is the role of the "new" operator in the creation of an object ?
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
static Sample()
{
Console.WriteLine("Static Constructor");
}
public Sample()
{
param1 = "Sample";
param2 = "Instance Constructor";
}
}
class Program
{
static void Main(string[] args)
{
// Here Both Static and instance constructors are invoked for first instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " + obj1.param2);
Console.ReadLine();
}
}
}
Output:

Static Constructor
Sample Instance Constructor
Sample Instance Constructor


Note:
- Static constructor will not accept any parameters because it is automatically called by CLR.
- Static constructor will not have any access modifiers.
- Static constructor will execute automatically whenever we create first instance of class
- Only one static constructor will allowed.

Private Constructor

Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.
using System;
namespace ConsoleApplication1
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
private Sample()  // Private Constructor Declaration
{
Console.WriteLine("Private Constructor with no parameters");
}
}
class Program
{
static void Main(string[] args)
{
// Here we don't have chance to create instace for private constructor
Sample obj = new Sample("Welcome","to DotNet Solution");
Console.WriteLine(obj.param1 +" " + obj.param2);
Console.ReadLine();
}
}
}
Output:
Wrlcome to Dotnet Solution

Note

  • One use of private construct is when we have only static member.
  • Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.
  • If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor
Ans: When you use the "new" operator for creating the object of the class it will internally perform the following:
   -Reads the Classes
   -Calls the Constructors
   -Allocates the memory required for the object
-What is meant by reading the class ?
Ans: Reading the class in the sense it will recongnize each and every member which was defined under the class.
-What is a Constructor ?
Ans: a constructor is a special method available under every class which is responsible for initializing the variables of the class.
-The Name of the constructor method is always same as the class name.
-A constructor is a non value returning method.
-Every class should contain a constructor in it if it has to execute.
-What happens if a constructor is not defined in a class ?
Ans: as a constructor is mandatory for the execution of a class if it was not defined under the class by the programmer while getting compiled the compiler takes the responsibility to define the constructor under that class, so that the class can execute.
-Can we define a constructor explicitly under the class ?
Ans: we can also define a constructor under the class as following:
[<modifiers>] <Name> ( [<param list>] )
{
 <Stmts>;
}  

No comments: