Home > database >  VB.NET Create a dictionary of Sub
VB.NET Create a dictionary of Sub

Time:05-04

I'm currently trying to create a dictionnary that looks like this :

Dim dict As New Dictionary(Of Integer, Action)
dict.Add(1, MySubFunction1)
dict.Add(2, MySubFunction2)


 Public Sub MySubFunction1()
    'do something, return nothing'
End Sub

Public Sub MySubFunction2()
    'do something, return nothing'
End Sub

Problem is, I cannot use Action with sub function like i saw in c#. Shoud i replace "Sub" by "Function" and always return something, like this :

Public Function MySubFunction1()
    'do something'
    Return True
End Function

Public Function MySubFunction2()
    'do something'
    Return True
End Function

Or is there any better way ?

CodePudding user response:

Action and Sub is the right combination.
But unlike in c# you cannot use just the method name as a delegate, you need to use AddressOf:

Dim dict As New Dictionary(Of Integer, Action)
dict.Add(1, AddressOf MySubFunction1)
dict.Add(2, AddressOf MySubFunction2)
dict(1).Invoke

Public Sub MySubFunction1()
    Console.WriteLine("Test")
End Sub

Public Sub MySubFunction2()
    
End Sub
  • Related