1

I have the same intention as in this question:

Automatically call all functions matching a certain pattern in python

But I needed the solution (if technically possible) in VB.NET. Is that possible in VB.NET ?

1 Answer 1

4

Sure you can do that, that's what reflection is for:

Imports System.Reflection

Module Module1

    Sub Main()
        Dim methods = GetType(Module1).GetMethods() _
            .Where(Function(m) m.Name.StartsWith("Setup"))
        For Each method As MethodInfo In methods
            method.Invoke(Nothing, Nothing)
        Next
    End Sub

    Sub Setup1()
        Console.WriteLine(1)
    End Sub

    Sub Setup2()
        Console.WriteLine(2)
    End Sub

    Sub Setup3()
        Console.WriteLine(3)
    End Sub

End Module
Sign up to request clarification or add additional context in comments.

6 Comments

@svick, sorry I'm a newbie and I just tested your code and visual studio 2008 showed following error: Leading '.' or '!' can only appear inside a 'With' statement.
@david, sorry, I forgot you can't continue line in VB just like in C#, see updated answer.
VB.NET 10 (introduced with VS 2010) supports implicit line continuation without using the _ character.
@Cody Gray, many thanks ! That is new info for me. VB.NET is getting smarter.
@david: You're welcome. I suppose it's good to know... I still use the line continuation characters out of habit. VB.NET may be getting smarter, but I'm clearly not. :-) Also do keep in mind that while Reflection will certainly work for this, there is a performance penalty involved in invoking functions this way. It's not nearly as fast as a direct call to the function. That may be perfectly OK for your purposes, but it's certainly worth knowing about regardless.
|

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.