Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 788
Notradam Narciso Avatar asked Jan 09 '11 09:01

Notradam Narciso


People also ask

What is an example of a nested function?

Users typically create nested functions as part of a conditional formula. For example, IF(AVERAGE(B2:B10)>100,SUM(C2:G10),0). The AVERAGE and SUM functions are nested within the IF function.

Can you nest functions in VBA?

no there are no nested functions in VBA, but if you want to make it more streamlined then declare the function private then only that module can see it.

How does nested function work?

A nested function can access other local functions, variables, constants, types, classes, etc. that are in the same scope, or in any enclosing scope, without explicit parameter passing, which greatly simplifies passing data into and out of the nested function. This is typically allowed for both reading and writing.

Can we Nest Fucntions within functions?

We can declare a function inside a function, but it's not a nested function. Because nested functions definitions can not access local variables of the surrounding blocks, they can access only global variables of the containing module.


2 Answers

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.
like image 87
Oded Avatar answered Sep 23 '22 10:09

Oded


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

like image 39
Cody Gray Avatar answered Sep 20 '22 10:09

Cody Gray