I’m not quite sure how best ask this question, so please feel free to edit…
I have a “Utilities” class that contains common functionality used throughout my application. One of my methods logs exeptions like this:
internal static void logExeption(Type typeOfClass, string methodName, Exception exeption )
{
//Do some logging here
}
Then I’d like to call it throughout my application whenever I catch an exception like so:
try{
//perform some action
}
catch(Exception ex)
{
Utils.logExeption(this.GetType(), System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
}
I would like to know if there’s a way I can avoid passing in the first two parameters and just figure out the context of the Class/Method where the exception originated right in the logException method. This will make things cleaner for me in the long run.
So you want to determine the calling object and the function. Though it is not recommended it can be achieved. Use System.Diagnostics.StackTrace to walk the stack; then get the appropriate StackFrame one level up. Then determine which method was the caller by using GetMethod() on that StackFrame. Note that building a stack trace is a potentially expensive operation, and it’s possible for callers of your method to obscure where things are really coming from.