Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get run time type of stack frames

I was wondering if it were possible to obtain the run time type of method callers in the stack trace.

Consider the following example:

class Parent
{
    public void Foo()
    {
        var stack = new StackTrace();

        foreach (var frame in stack.GetFrames())
        {
            var methodInfo = frame.GetMethod();
            Console.WriteLine("{0} (ReflectedType: {1})", methodInfo.ToString(), methodInfo.DeclaringType);
        }
    }
}

class Child : Parent
{
}

If I create an instance of Child and call Foo

var child = new Child();
child.Foo();

Foo will print: Void Foo() (ReflectedType: Parent)

Is there any way to get the actual run time types (Child in this case) of method callers in the stack trace?

like image 255
Patrick M Avatar asked May 08 '26 04:05

Patrick M


1 Answers

No. The reason is described by Raymond Chen here.

The relevant quote is:

An object in a block of code can become eligible for collection during execution of a function it called.

It's not intuitive, read the part about JIT and GC working together.

Getting the actual Type requires the instance, but the optimization effort is geared toward making that Garbage, so you can't rely on it still being there.

like image 177
Henk Holterman Avatar answered May 10 '26 21:05

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!