Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to determine which instance of a class the current instance of a class is instantiated from?

Tags:

c#

As the title suggests, it is possible to determine which instance of a class a particular instance of another class is instantiated from?

Update: Example Code below

class FooBar: Foo
{
    private Context context;
    public FooBar(Context _context): base(_context)
    {
        this.context = _context;
    }
}

class Foo
{
    public Baz baz;
    private Context context; 
    public Foo(Context _context)
    {
        baz = new Baz();
        this.context = _context;
    }
}

class Baz
{
    public Baz()
    {
        GetNameOfCaller()
    }

    private void GetNameOfCaller()
    {
       ....
       ....
       _className = ....;
    }
    private string _className;
}
like image 877
CJC Avatar asked Dec 11 '22 19:12

CJC


1 Answers

Yes, you can do that for constructors the same way as for regular methods. Just use the CallerMemberName to pass in the name of the calling method. You won't have the class name with it, then you need to walk the StackTrace which is much more complicated.

public class X
{
    public X([CallerMemberName] string caller = null)
    {
        this.Caller = caller;
    }

    public string Caller { get; private set; }
}

Then just call this. The compiler will fill in the caller parameter for you:

static void Main(string[] args)
{
    X x = new X();
    Console.WriteLine($"Caller = {x.Caller}"); // prints Main
}
like image 129
Patrick Hofman Avatar answered Dec 13 '22 08:12

Patrick Hofman