vb.netconstructor-chaining

How to do constructor chaining in VB.NET?


In C# you can chain constructors in the following way:

    public class Foo
    {
        public Foo(string name)
        {
            // Do something.
        }
    
        public Foo(string name, int bar) : this(name)
        {
            // Do something.
        }
    }

Is there perhaps a VB.NET equivalent to chain constructors?


Solution

  • It looks similar to Java in this respect:

    Public Class Foo
        Public Sub New(name As String)
            ' Do something '
        End Sub
    
        Public Sub New(name As String, bar As Integer)
            Me.New(name)
            ' Do something '
        End Sub
    End Class
    

    Note that you have to use MyBase.New(...) in case you want to call a constructor of a base class. See also VB.NET OOP Part2 – Understanding Constructors.