Amitloaf
Amitloaf

Reputation: 165

How do I get information about an instance of a delegate function (like name or containing class) in C#?

I have a delegate function

class FuncActivator {
  public delegate void DelFunc(string arg, string val);
}

I keep instances of that function to start at the same time later within the program (Also in FuncActivator:

List<DelFunc> funcList = new List<DelFunc>();

public void KeepFunc(DelFunc delFunc) {
  funcList.Add(delFunc);
}

Now I want to get information about the actual delegate name, or it least which class passed it here. For example, in a different class

public class FunnyClass {
  public void FunnyFunc(string arg, string val) {
    //..Do stuff
  }

  public FunnyClass () {
    FuncActivatorInstance.KeepFunc(FunnyFunc);
  }
}

I'd like from a method within FuncActivator to list the names or callers of all the delegates in my list (like "FunnyFunc" or at least "FunnyClass"). Is that possible?

Upvotes: 3

Views: 962

Answers (1)

Tim S.
Tim S.

Reputation: 56536

This code:

public void PrintFuncs()
{
    foreach (var func in funcList)
    {
        Console.WriteLine(func.Method.Name);
        Console.WriteLine(func.Method.DeclaringType.Name);
    }
}

Prints:

FunnyFunc
FunnyClass

The instance of FunnyClass that added itself to the list is at func.Target, if you'd like to use that, too.

Lambdas that are attached, since they are anonymous, will have an auto-generated method name. If a class was generated for it as well, it will have an auto-generated name as well. So just FYI, you won't always be able to have very readable strings from this.

Upvotes: 5

Related Questions