Reputation: 4179
My question is best described with a small code sample;
public class ClassA {
public delegate void MyDelegate(EventArgs e);
public event MyDelegate MyEvent;
public void OnEvent(EventArgs e) {
if (MyEvent != null)
MyEvent(e);
// print "WhatIsMyName" here
}
}
public class ClassB {
public ClassB() {
ClassA a = new ClassA();
a.MyEvent += WhatIsMyName;
}
public static void WhatIsMyName(EventArgs e) {
}
}
I'm guessing I need to use reflection but I'm not sure how to go about it (or even if it's possible). I'd also like to be able to get the class name of the method.
Upvotes: 0
Views: 82
Reputation: 8450
Actually there is a new feature in .NET 4.5, which is called "Caller Information".
You can get some information about caller like that:
public void Foo([CallerMemberName]string sourceMemberName = "",
[CallerFilePath]string sourceFilePath = "",
[CallerLineNumber]int sourceLineNo = 0)
{
Debug.WriteLine("Member Name : " + sourceMemberName);
Debug.WriteLine("File Name : " + sourceFilePath);
Debug.WriteLine("Line No. : " + sourceLineNo);
}
More information:
Caller Info - codeguru.com
Upvotes: 1
Reputation: 36300
You can use the StackTrace class to look at the entire stack trace for your application. This will be quite slow, but should work.
Check out the GetFrame and GetFrames methods for some examples.
Edit: If you are on .Net 4.5 you might also use the CallerMemberName attribute. This will be a faster and more elegant solution if it fits your requirements.
Upvotes: 0