Bernoulli Lizard
Bernoulli Lizard

Reputation: 579

Pass function as a parameter in vb.net?

I have class that performs many similar yet different read/write operations to an excel file. All of these operations are defined in separate functions. They all have to be contained within the same long block of code (code that checks and opens a file, saves, closes, etc). What is reasonable way to not have to duplicate this code each time? The problem is that I can't just one method containing all of the shared code before I execute the code that is different for each method because that code must be contained within many layers of if, try, and for statements of the shared code.

Is it possible to pass a function as a parameter, and then just run that function inside the shared code? Or is there a better way to handle this?

Upvotes: 22

Views: 42062

Answers (3)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Declare your parameter as Func(Of T) or Action(Of T).

Which one you should use depend on your methods signature. I could give you more precise answer if you gave us one.

Upvotes: 9

Steve
Steve

Reputation: 5545

You can also use a delegate so you can pass function/subs that have a certain signature.

Upvotes: 4

Konrad Rudolph
Konrad Rudolph

Reputation: 545508

Focusing on the actual question:

Is it possible to pass a function as a parameter

Yes. Use AddressOf TheMethod to pass the method into another method. The argument type must be a delegate whose signature matches that of the target method. Inside the method, you treat the parameter as if it were the actual method. Example:

Sub Foo()
    Console.WriteLine("Foo!")
End Sub

Sub Bar()
    Console.WriteLine("Bar!")
End Sub

Sub CallSomething(f As Action)
    f()
End Sub

' … somewhere:
CallSomething(AddressOf Foo)
CallSomething(AddressOf Bar)

As I said, the actual parameter type depends on the signature of the method you’d like to pass. Use either Action(Of T) or Func(Of T) or a custom delegate type.

However, in many cases it’s actually appropriate to use an interface instead of a delegate, have different classes implement your interface, and pass objects of those different classes into your method.

Upvotes: 41

Related Questions