Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out who is (implicitly) calling my ToString?

Tags:

c#

.net

tostring

My class requires additional information to properly output its status, so I've added a custom PrintSelf method taking the appropriate parameters.

However, I'm afraid there are still calls to ToString in my large project, which were not replaced by the new method. How can I find those improper calls to ToString?

I'm using VS 2015, but it does not seem to have this ability.

Throwing an exception in ToString would be an obvious way, but I don't want to do that for two reasons:

  1. ToString can still perform a different job and output something not depending on the added parameter.

  2. There is no way to get full code coverage, meaning it would only find a few instances of implicit calls, but not (reliably) all of them.

like image 486
mafu Avatar asked Sep 28 '16 12:09

mafu


1 Answers

To override ToString and log the caller you can do like this

    public override string ToString()
    {
        StackTrace stackTrace = new StackTrace();           
        StackFrame[] stackFrames = stackTrace.GetFrames();  

        StackFrame callingFrame = stackFrames[1];
        MethodInfo method = callingFrame.GetMethod();
        YourLogingMethod(method.DeclaringType.Name + "." + method.Name);

        return base.ToString();
    }
like image 198
Thorarins Avatar answered Oct 13 '22 00:10

Thorarins