Sunday, June 6, 2010

call constructor from another constructor (VB.Net and C#)

If you are using C#, you have to call one constructor from another by using inbuilt syntax (similar to one used during inheritance) for e.g.


class TestConstructor
    {
        public TestConstructor()
        {
            //Default Constructor
        }

        public TestConstructor(string s):this()
        {
            //overloaded constructor
        }

        public TestConstructor(int n):this("test")
        {
            //overloaded constructor
        }
    }

Now If I call it from main function as below

 static void Main(string[] args)
        {
            TestConstructor tc = new TestConstructor(4);
        }

the constructor which takes integer as parameter would be called which will then call the constructor taking string as parameter and that will call default constructor. So my default constructor would be executed first followed by the one which takes string as parameter and  the last one to be executed will be the one which takes integer as parameter.
Please note that the constructors would always be called in a manner they are related to each other. so while writing the code you need to write the most common initialization in your default constructor and then keep on doing inheritance of constructor until your most uncommon initialization is required to be wrapped in a constructor.


If you are using VB.NET then you have to write code as following


Class TestConstructor
        Public Sub New()
            'Default Constructor
        End Sub

        Public Sub New(ByVal s As String)
            'overloaded Constructor
            Me.New()
        End Sub
        Public Sub New(ByVal n As Integer)
            'overloaded Constructor
            Me.New("this")
        End Sub
 
    End Class

Now you can call it from Main


Sub Main()
        Dim tc As New TestConstructor(4)
    End Sub

and it will be executed similar to the example I mentioned for C#.

Here you will find subtle difference in the language, VB.NET does not differentiate much between constructor and function so you can explicitly call a constructor from another assuming it to be a function. Therefore here order of calling constructors is completely upto you, you can call constructors with all liberty (same as when you call function).

No comments:

Post a Comment