calling New with arguments - Syntax question

C

Colin McGuire

Hi, I have a class with lots of constructors - one is shown below

Public Sub New(ByVal rows As Integer, ByVal columns As Integer)
InitializeComponent()
'And code in here that sets instance variables,
'and does calculations based on rows and columns passed
'in in the constructor, and lots more.
End Sub

Another of my constructors has no parameters, and there are various
other
constructors that receive, for example, Point etc. But what I want to
do is
call one constructor New from another constructor New so I don't have
to reproduce the same code many times, or put it in a separate
procedure and call it from each New(..)

Here is what I am wanting to do, but the compiler is having none of it
!

Public Class test
Inherits System.Windows.Forms.Form
Public Sub New(ByVal rows As Integer, ByVal columns As Integer)
InitializeComponent()
'And code in here that sets instance variables,
'and does calculations based on rows and columns passed
'in in the constructor, and lots more.
End Sub

Public Sub New()
Dim defaultRows As Integer=2
Dim defaultColumns As Integer=10
Call New(defaultRows,defaultColumns)
End Sub

'More methods/code etc
End Class

Can someone cast their eye over this and help me along with the
correct syntax (the line "Call New(defaultRows,defaultColumns" is the
line the compiler balks at).

Thank you
Colin
 
M

Mattias Sjögren

Colin,
Can someone cast their eye over this and help me along with the
correct syntax (the line "Call New(defaultRows,defaultColumns" is the
line the compiler balks at).

Public Sub New()
MyClass.New(2, 10)
End Sub



Mattias
 
J

Jay B. Harlow [MVP - Outlook]

Colin,
In addition to Mattias example.

The call to MyClass.New or MyBase.New needs to be the first statement in the
constructor, before any other statements, or variable or constant
declarations.

Also you need to include the MyClass or MyBase so the compiler knows that
you are chaining to another constructor and that constructor is either in
the base class (MyBase) or the current class (MyClass).

And as Mattias showed, Call is optional hence I tend to omit it.

Hope this helps
Jay
 
M

Mike Caputo

You can also call Me.New(etc, etc)

--


Michael Caputo
Programmer/Database Administrator
Simon Economic Systems Ltd.
 
J

Jay B. Harlow [MVP - Outlook]

Mike,
That's right! I was thinking there was a third syntax. Thanks for the
additional info.

I normally use either MyBase or MyClass in the constructor so I "forgot"
that Me was supported.

Thanks
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top