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;
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With