Sunday, February 6, 2011

How to get the calling method name

This is continuation to my last post on finding the name of the method inside the same method. As I told in that post,my original requirement was to find out who is calling one method and handle the call appropriately.After spending some more time ,I was able to find a way.Its nothing but getting the call stack programmatically.Here is the code.

Console.WriteLine(new StackFrame(1).GetMethod().Name);
Console.WriteLine(new StackFrame(1).GetMethod().DeclaringType.FullName);

Now its possible to check the caller method and do operations based on the block callers ,return different results etc…

Is there any sense in doing like this where anybody can create an assembly with required name and bypass this

Normally speaking there is no sense.But of course YES based on some scenarios especially in our project.We have a class present for years used to keep the context which we would like to make SingleTon now, to avoid memory leaks and improve performance. There is no chance that we can put a private constructor or rewrite the entire code due to serialization of the context and practicability.If we start rewriting the code we cannot deliver on time.So the last option is to find out the classes which really needs to instantiate the context class and give permission to them only.For other classes expose a static property which returns the current context object.

But if we think from performance aspects, its time consuming as each and every call needs a comparison.

Really speaking I am compromising performance for the practicability.

No comments: