Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the calling method name and type using reflection? [duplicate]

Tags:

c#

reflection

Possible Duplicate:
How can I find the method that called the current method?

I'd like to write a method which obtains the name of the calling method, and the name of the class containing the calling method.

Is it possible with C# reflection?

like image 973
Billy ONeal Avatar asked Jun 22 '10 17:06

Billy ONeal


Video Answer


1 Answers

public class SomeClass {     public void SomeMethod()     {         StackFrame frame = new StackFrame(1);         var method = frame.GetMethod();         var type = method.DeclaringType;         var name = method.Name;     } } 

Now let's say you have another class like this:

public class Caller {    public void Call()    {       SomeClass s = new SomeClass();       s.SomeMethod();    } } 

name will be "Call" and type will be "Caller".

UPDATE: Two years later since I'm still getting upvotes on this

In .NET 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute.

Going with the previous example:

public class SomeClass {     public void SomeMethod([CallerMemberName]string memberName = "")     {         Console.WriteLine(memberName); // Output will be the name of the calling method     } } 
like image 50
BFree Avatar answered Sep 29 '22 18:09

BFree