Is there any way to get a reference to the calling object in c#?

No, there isn’t – at least not without using a profiling/debugging API of some description. You can walk the stack to find the calling method, with the caveat that it’s really slow and may be inaccurate due to JIT optimisations. That won’t tell you what the calling object is though (if indeed there is one).

If you want to get the type you can try this:

new StackFrame(1).GetMethod().DeclaringType

As Jon pointed out there might be issues if you run into JIT optimizations.

As for getting data from the object, I don’t think it’s possible.

Edit

Just to elaborate on the optimization issue, take the following code:

class stackTest
{
    public void Test()
    {
        StackFrame sFrame = new StackFrame(1);
        if (sFrame == null)
        {
            Console.WriteLine("sFrame is null");
            return;
        }

        var method = sFrame.GetMethod();

        if (method == null)
        {
            Console.WriteLine("method is null");
            return;
        }
        Type declaringType = method.DeclaringType;
        Console.WriteLine(declaringType.Name);
    }

    public void Test2()
    {
        Console.WriteLine(new StackFrame(1).GetMethod().DeclaringType.Name);
    }
}

class Program
{
    static void Main(string[] args)
    {

        stackTest s = new stackTest();
        s.Test();
        Console.WriteLine("Doing Test2");
        s.Test2();
        Console.ReadLine();

    }
}

We should get Program to the console twice, and when you run within the debugger you do. When you run without the debugger in release mode, you get the output from the first Test function. Which is probably because it is to complex to be inlined, however, the second method causes a null reference exception.

Another danger with this code is that at MS improves the JIT compiler what might have worked in 2.0 could crash and burn in future versions.

Leave a Comment