using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Reflection; namespace Yaulw.Other { /// /// Use the StackWalker to Find out what Method/Type Called you. /// This is useful for logging functions to know what method/type called the Logging Method. /// public static class StackWalker { /// /// Hard-Coded in Stack Frame count depending on how this Class is getting called, /// and how many frames we have to go up / down (use nPlusMinus) /// public const int DEFAULT_STACK_FRAME_COUNT = 3; /// /// Use this to get the MethodName from the CallStack. /// This allows the calling method to know which method called it /// /// Use this to add/substract from the base stack level you want to retrieve /// Returns the MethodName as specified by the CallStack public static string GetMethodNameFromStack(int nPlusMinus = 0) { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame; MethodBase stackFrameMethod; stackFrame = stackTrace.GetFrame(DEFAULT_STACK_FRAME_COUNT + nPlusMinus); stackFrameMethod = stackFrame.GetMethod(); return stackFrameMethod.Name; } /// /// Use this to get the Type from the CallStack. /// This allows the calling method to know which type called it. /// /// Use this to add/substract from the base stack level you want to retrieve /// Returns the Type as specified by the CallStack public static Type GetTypeFromStack(int nPlusMinus = 0) { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame; MethodBase stackFrameMethod; stackFrame = stackTrace.GetFrame(DEFAULT_STACK_FRAME_COUNT + nPlusMinus); stackFrameMethod = stackFrame.GetMethod(); return stackFrameMethod.ReflectedType; } } }