How to implement class constructor in Visual Basic?

vb.net

vb.net Problem Overview


I just would like to know how to implement class constructor in this language.

vb.net Solutions


Solution 1 - vb.net

Not sure what you mean with "class constructor" but I'd assume you mean one of the ones below.

Instance constructor:

Public Sub New()

End Sub

Shared constructor:

Shared Sub New()

End Sub

Solution 2 - vb.net

Suppose your class is called MyStudent. Here's how you define your class constructor:

Public Class MyStudent
    Public StudentId As Integer
    
    'Here's the class constructor:
    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

Here's how you call it:

Dim student As New MyStudent(studentId)

Of course, your class constructor can contain as many or as few arguments as you need--even none, in which case you leave the parentheses empty. You can also have several constructors for the same class, all with different combinations of arguments. These are known as different "signatures" for your class constructor.

Solution 3 - vb.net

If you mean VB 6, that would be Private Sub Class_Initialize().

http://msdn.microsoft.com/en-us/library/55yzhfb2(VS.80).aspx

If you mean VB.NET it is Public Sub New() or Shared Sub New().

Solution 4 - vb.net

A class with a field:

Public Class MyStudent
   Public StudentId As Integer

The constructor:

    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionyonan2236View Question on Stackoverflow
Solution 1 - vb.netHans OlssonView Answer on Stackoverflow
Solution 2 - vb.netShieldOfSalvationView Answer on Stackoverflow
Solution 3 - vb.netJonathan AllenView Answer on Stackoverflow
Solution 4 - vb.netAnkit SinghView Answer on Stackoverflow