82

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

1
  • 1
    Its important to remember that you can only call methods from an instance of the class when it is public. If the method is private, the only the methods inside of the same class can call it. Nov 12, 2013 at 9:08

4 Answers 4

97

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
5
  • Class constructor is a VB 6 term for an instance constructor. Alas it is also a OOP term for what you called a shared constructor. Jul 19, 2010 at 7:27
  • @Jonathan: Thanks, I knew it was an ambigious term, but wasn't sure what it meant where. Btw, your answer is slightly wrong in that a Shared constructor can't be Public. Jul 19, 2010 at 7:31
  • Ugh, that's what I get for typing too fast. Jul 19, 2010 at 7:43
  • 1
    By the way, I just saw a cheat sheet listing public Foo() as a "class constructor" in C#. At this point I'm thinking the term is essentially useless. Jul 19, 2010 at 7:46
  • If I say "object constructor" or "static constructor" you know exactly what I mean. If I say "class constructor" you have to ask. That makes it useless to me. Jul 19, 2010 at 22:36
27

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.

12

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().

3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.