3

Is there a way for me to make a function call on a new instance of a variable without first declaring it?

So for example in Java you could do:

new foo().bar(parameters);

I've tried something similar in Visual Basic, but it's a syntax error. For the moment I'm creating a variable and then running the function.

dim instance as new foo()
instance.bar(parameters)

Is there something I can do similarly to the Java code above?

1
  • Looks like you need to look into Shared methods in instead. Commented Apr 23, 2013 at 21:18

3 Answers 3

6

Not exactly. You can do so in a larger expression by surrounding the instantiation in parenthesis, for instance:

MessageBox.Show((New String("y"c, 1)).ToUpper())

Or, in fact, while I find it more confusing, you don't actually even need the parenthesis around the instantiation:

MessageBox.Show(New String("y"c, 1).ToUpper())

However, if you want to just call a method like that, the only way I know of is to wrap in in a CType operator. For instance, if you had a class like this:

Private Class Test
    Public Sub Show()
        MessageBox.Show("Hello")
    End Sub
End Class

You could call the Show method like this:

CType(New Test(), Test).Show()

But, it is a bit clumsy.

Actually, SSS provided an even better answer since I posted this yesterday. Instead of wrapping it in a CType operator, you can use the Call keyword. For instance:

Call New Test().Show()
Sign up to request clarification or add additional context in comments.

Comments

1

Yes you can, I use the following pattern often. The alternative is to add parameters to Sub New(). I use this pattern when initialisation can fail, and you want to return a null reference (Nothing) instead of throwing an exception.

Public Class Foo
  Property Prop1 As String
  Property Prop2 As String

  Public Shared Function Bar(p1 As String, p2 As String) As Foo
    Dim f As Foo
    If p1 = "" Or p2 = "" Then
      'validation check - if either parameter is an empty string, initialisation fails and we return a null reference
      f = Nothing
    Else
      'parameters are valid
      f = New Foo
      f.Prop1 = p1
      f.Prop2 = p2
    End If
    Return f
  End Function

  ''' <summary>
  ''' Optional - marking the Sub New as "Private" forces the caller to use the Bar() function to instantiate
  ''' </summary>
  ''' <remarks></remarks>
  Private Sub New()

  End Sub
End Class

Comments

0

Like SSS has provided the way which is best for Classes, another way around could be of using Modules if it is not a compulsion for you to use Classes only.

Modules provide easy access for function without even creating objects for them.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.