Reputation: 4266
is it possible?
i want to get the name of class (like foo) which is invoking my method (like myMethod)
(and the method is in another class(like i))
like:
class foo
{
i mc=new i;
mc.mymethod();
}
class i
{
myMethod()
{........
Console.WriteLine(InvokerClassName);// it should writes foo
}
}
thanks in advance
Upvotes: 4
Views: 2349
Reputation: 4266
I found the fallowing : http://msdn.microsoft.com/en-us/library/hh534540.aspx
// using System.Runtime.CompilerServices
// using System.Diagnostics;
public void DoProcessing()
{
TraceMessage("Something happened.");
}
public void TraceMessage(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Trace.WriteLine("message: " + message);
Trace.WriteLine("member name: " + memberName);
Trace.WriteLine("source file path: " + sourceFilePath);
Trace.WriteLine("source line number: " + sourceLineNumber);
}
// Sample Output:
// message: Something happened.
// member name: DoProcessing
// source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs
// source line number: 31
Upvotes: 0
Reputation: 1500595
You can use StackTrace
to work out the caller - but that's assuming there's no inlining going on. Stack traces aren't always 100% accurate. Something like:
StackTrace trace = new StackTrace();
StackFrame frame = trace.GetFrame(1); // 0 will be the inner-most method
MethodBase method = frame.GetMethod();
Console.WriteLine(method.DeclaringType);
Upvotes: 10