Matt Mitchell
Matt Mitchell

Reputation: 41823

How do you dynamically get a particular method's name in a strongly typed way?

I'm a little unsure how to word the title to this question but I'm looking for a the shortest/aseist way in VB.NET (or C# but using VB.NET at the moment) to get the string value of a method's name dynamically given the method call.

For instance, I have a class like this:

Public Class Blah
    Public Sub Foo()
    End Sub
End Class

Now Foo is a strongly-typed cover for a dynamic setting and I have an event handler that will fire when the setting changes and return the string name of the setting that changed.

I'd like to be able to switch/select on this string and have a case based on the Foo() method. To do this I need to able to get the string name of the Foo method from the method call itself (i.e. somehow GetMethodName(blahInstance.Foo())).

Upvotes: 3

Views: 623

Answers (1)

BlueMonkMN
BlueMonkMN

Reputation: 25601

I don't have VB.NET handy at the moment, but in C#, I'm thinking this is the answer. Does this look approximately like what you're looking for? If so, the VB.NET syntax should be relatively simple to work out:

     Blah blahInstance = new Blah();
     System.Action fooFunc = blahInstance.Foo;
     Console.WriteLine(fooFunc.Method.Name);

Upvotes: 7

Related Questions