Notradam Narciso
Notradam Narciso

Reputation: 131

How do I declare a nested function in VB.NET?

How would I declare a nested function in VB.NET? For example, I want to do something like this:

Function one()
    Function two()
    End Function
End Function

However, this statement is invalid in VB.NET because of unclosed function.

Upvotes: 13

Views: 15526

Answers (3)

Timothy C. Quinn
Timothy C. Quinn

Reputation: 4515

Lambda expressions were added in recent years to vb.net: https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/lambda-expressions

In Modern vb, you do the following:

    Function foo() as String
        Dim _bar = Function()
                       return "bar"
                   End Function

        return "foo " + _bar()
    End Function

Upvotes: 0

Cody Gray
Cody Gray

Reputation: 244951

Are you asking how to write a lambda expression?

A lambda expression is a function or subroutine without a name that can be used wherever a delegate is valid. Lambda expressions can be functions or subroutines and can be single-line or multi-line. You can pass values from the current scope to a lambda expression.

You create lambda expressions by using the Function or Sub keyword, just as you create a standard function or subroutine. However, lambda expressions are included in a statement.

For example, the following code will print "Hello World!":

Dim outputString As Action(Of String) = Sub(x As String)
                                            Console.WriteLine(x)
                                        End Sub
outputString("Hello World!")

For more examples, see here: VB.NET Lambda Expression

Upvotes: 21

Oded
Oded

Reputation: 499262

As you noted, this is not possible.

You have several options

  • have Function two be a private function within the same class, so you can call it from Function one.
  • Create a nested class or structure on the class, again private, and call methods on that.

Upvotes: 3

Related Questions