DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

Constructors in .NET

By Ashok Nalam on 01 Jan 2013 | Category: VB.NET | Tagged: oops constructor C# 
In this article we will see about constructors in .net. and types of constructors with sample example.
  Discuss Add Comment   |  
Add rating Rate this resource  [Rated 5.00/5 by 1 people] 

Introduction

“A constructor is class method which will be executed automatically as soon as the object is created”

  • Always name of the constructor is same as the class name. In C# it has same name and for VB.NET, constructor will be named with “New” keyword.
  • Constructors doesn't specify any return type (not even void) to the method. So it doesn't return any value. 
  • If class does not have any form of constructor then language compiler will create a public default constructor.

Types of constructors

  1. Default constructor: A constructor without parameters is called default constructor. It is referred as instance constructor also.
  2. Parameterized constructor: A constructor in which the parameters are defined. Constructor can have different set of parameters which is called “constructor overloading”.
  3. Copy constructor: A constructor with object reference of the same class as the parameter is called copy constructor.
  4. Static/Shared Constructor: Static/shared constructor will be invoked by class loader of CLR only once for any number of instances of the class.
    • Static/shared constructor will be called only once before any object of class is created.
    • It is used to initialize values to static/shared members.
    • It cannot have any access specifies like public or private. If we try to provide access specifier then we will get  compile error as “access modifiers are not allowed on static constructors
    • A class will have only one static/shared constructor means we do not have any parameterized static/shared constructors in the class. If we try to overload static/shared constructor then the compiler error is “a static/shared constructor must be parameterless”.

VB.NET Constructors Syntax

Sub New()
 'default constructor
End sub
Sub New(Byval param1 as <data type>, Byval param2 as <data type>,…..)
'Parameterized constructor
End sub
Sub New(Byval <param_name> as >(<Class_Name>)
'Copy constructor
End sub
Shared Sub New()
'Shared constructor
End sub

C# Constructors Syntax

<Class_Name>()
{
--default constructor
}
<Class_Name> (<data type> param1, >(<data type> param2,……)
{
--Parameterized constructor
}
<Class_Name>(<Class_Name> <param_name>)
{
--Copy constructor
}
static Class_Name ()
{
--Static constructor
}
Now we will see a example which will cover all the constructor types. Here we are providing C# example, same you can convert to VB.NET version also to understand.

Example:

class Student
{
    private int id, marks;
    private string name;
    public Student()
    {
        //default constructor
        Console.WriteLine("default constructor is invoked.");
    }
    static Student() //No params and No access modifiers
    {
        //static constructor and set values for static members
        Console.WriteLine("static constructor is invoked.");
    }
    public Student(int studentId, string studentName)
    {
        //Parameterized constructor with 2 params
        this.id = studentId;
        this.name = studentName;
        Console.WriteLine("Call from Parameterized Constructor with 2 params. studentId={0} and studentName={1}.", this.id, this.name);
    }
    public Student(int studentId, string studentName, int totalMarks)
    {
        //Parameterized constructor with 3 params
        this.id = studentId;
        this.name = studentName;
        this.marks = totalMarks;
        Console.WriteLine("Call from Parameterized Constructor with 3 params. studentId={0} , studentName={1} and totalMarks={2}.", this.id, this.name, this.marks);
    }
    // all above constructors can be called as constructor overloaded methods.

    public Student(Student varStudent)
    {
        // Copy constructor.
        this.id = varStudent.id;
        this.name = varStudent.name;
        Console.WriteLine("Call from Copy Constructor. studentId={0} and studentName={1}.", this.id, this.name);
    }
}
class ConstructoreUsage
{
    public static void Main()
    {

        Student objStudent = new Student(); //static and default constructors are invoked for the first instance
        Student objStudent1 = new Student(1, "Ram"); //Parameterized constructor with 2 params is invoked
        Student objStudent2 = new Student(2, "Laxman", 100); //Parameterized constructor with 3 params is invoked
        Student objStudent3 = new Student(objStudent1); //Copy constructor is invoked
        Console.Read();
    }
}

Output:

Can Constructor be Private/Protected:

Constructors are usually public because they are provided to create the objects for the class. But it can be private or protected also. In such case object cannot be created for that class and also the class cannot be used as base class for inheritance.

private/protected Student()
{
//default constructor
}
 Student objStudent = new Student(); //Compile Error is ‘Student.Student()’ is inaccessible due to protection level.

Sequence of event which will be executed when the first object is created:

  1. Class will be loaded
  2. Static/shared members are loaded and allocated memory
  3. Static/Shared constructor will be executed. ( initialization of Static/shared members will be done here)
  4. Class/instance members are loaded and allocated and initialized.
  5. Default/instance constructor will be executed.

Note: static/shared constructor cannot have access to instance members of the class so allocation of memory to instance members will be done after static/shared constructor execution.

  Discuss Add Comment    
Add rating Rate this resource  [Rated 5.00/5 by 1 people] 
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 8666  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.