0

Possible Duplicate:
Retrieving the calling method name from within a method (C#)

I have a class say A in which there is a Method called Func1; this function is static. Now there are some other classes say B, C that use A.Func1

How can I get the class name which contains the function that is calling ?

ie

public class A  
{  
    public static void Func1()  
    {  
    // who called me?  
    }  
}  

public class B  
{  
    public void CallFunc()  
    {  
        A.Func1();  
    }  
}

public class C
{  
    public void AlsoCallFunc()  
    {  
        A.Func1();  
    }  
}
Community
  • 1
  • 1
Abhishek
  • 957
  • 3
  • 20
  • 43
  • Clarify the question, Post some code, Help us to help you.. – abhilash Feb 29 '12 at 11:58
  • 2
    See: http://stackoverflow.com/questions/615940/retrieving-the-calling-method-name-from-within-a-method-c - however, I strongly suggest you remove the need for this; such techniques are brittle **at best**. Virtually any other design would be preferable. – Marc Gravell Feb 29 '12 at 11:59
  • Actually, my senario is, in my class there is an event, in this event there are some calculation based on the calling winform thats why i need of this. – Abhishek Feb 29 '12 at 12:03
  • Marc is right - this is one of the smelliest code-smells you'll ever find. Don't do it. – Ross Patterson Feb 29 '12 at 12:14
  • If you have an event handler its first parameter is the sender. Maybe you can use that sender to get the calling form. – brgerner Feb 29 '12 at 12:50
  • Rather than identifying the caller by stack trace, why not inject the additional informations required as a method parameter? If its a genuine event then you can use the sender or have custom event args with additional information – kaj Feb 29 '12 at 13:45

3 Answers3

2

Can use StackTrace class in order to acees that kind of information.

To get calling method name, I sometimes use this function. But you need to check if it works in your specific case:

private static string GetCallingMethodName()
{        
    const int iCallDeepness = 2; 
    System.Diagnostics.StackTrace stack = new System.Diagnostics.StackTrace(false);
    System.Diagnostics.StackFrame sframe = stack.GetFrame(iCallDeepness);
    return sframe.GetMethod().Name;
}
Tigran
  • 61,654
  • 8
  • 86
  • 123
0

maybe you work with the output of

Environment.StackTrace
mindandmedia
  • 6,800
  • 1
  • 24
  • 33
0

if you need to work with form and want to know which form is calling then use event and sender