Vesuvian
Vesuvian

Reputation: 717

How to get the name of a method at runtime?

I'm using an event system that takes a string for the callback method name. I'd like to avoid hardcoding strings. Is there any way I can get the method names of given class in runtime?

Something similar to:

typeof(MyClass).Name;

but for methods would be perfect.

Edit:

I've been googling the problem and all results seem to be people looking to get the name of the current executing method. This isn't what I'm looking for - instead I'd like to get the name of other methods within the same class.

Upvotes: 2

Views: 771

Answers (3)

Bhushan Firake
Bhushan Firake

Reputation: 9458

For same method:

MethodBase.GetCurrentMethod().Name;

For method in another class:

var type = typeof(MyClass);
MethodInfo[] methodInfos = type.GetMethods(BindingFlags.Public | BindingFlags.Instance);

Then, you can use, for example, methodInfos[0].Name to get the name of the method.

If the method to be called is in the same class, you can do it as below:

If it is method with no return type/void

 Action action = () => { MethodToBePassed(); };

  public static void MethodToBePassed()
  {
  }

   public static void Test(string a, Action action)
   {
      action();
   }

Call it as below:

 Test("a", action);

If method has return param

 Func<string, int> action = (str) => { return MethodToBePassed(str); };

 public int MethodToBePassed(string sample)
 {
    return 1;
 }

 public static void Test(string a, Func<string, int> action)
 {
    int value = action("a");
 }

Upvotes: 0

BambooleanLogic
BambooleanLogic

Reputation: 8171

It sounds like you're talking about the nameof operator, added in C# 6.0.

MSDN Documentation

Excerpt:

Used to obtain the simple (unqualified) string name of a variable, type, or member. When reporting errors in code, hooking up model-view-controller (MVC) links, firing property changed events, etc., you often want to capture the string name of a method. Using nameof helps keep your code valid when renaming definitions. Before you had to use string literals to refer to definitions, which is brittle when renaming code elements because tools do not know to check these string literals.

A nameof expression has this form:

if (x == null) throw new ArgumentNullException(nameof(x));
WriteLine(nameof(person.Address.ZipCode)); // prints "ZipCode”

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

You are looking for

System.Reflection.MethodBase.GetCurrentMethod().Name;

Refer MethodBase.GetCurrentMethod Method

Returns a MethodBase object representing the currently executing method.

EDIT:

var str = typeof(MyClass);
MethodInfo[] info = str.GetMethods(BindingFlags.Public | BindingFlags.Instance);

Upvotes: 1

Related Questions