Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine who is the creator of an object

Tags:

c#

.net

I have a class that is called regularly by several objects. I would like to include information in any exceptions as who the creater of the object is. What are my options?

"Who" refers to an object or class

like image 287
Brad Avatar asked Dec 22 '22 09:12

Brad


2 Answers

Store a stacktrace when the constructor is called. This is similar to what SlimDX does in debug builds.

like image 95
Cecil Has a Name Avatar answered Jan 07 '23 17:01

Cecil Has a Name


I might be missing something, but I am pretty sure that the only way you can do it, is by manually passing this information, fe. in constructor of your object.
Edit : If this is what you were looking for? :


class Creator
{
    public string Name { get; private set; }

    public Creator(string name)
    {
        Name = name;
    }
}

class Foo
{
    readonly Creator creator;
    public Foo(Creator creator)
    {
        this.creator = creator;
    }

    public void DoSth()
    {
        throw new Exception("Unhandled exception. My creator is " + creator.Name);
    }
}

public static void Main()
{
    Foo f = new Foo(new Creator("c1"));
    f.DoSth();
}
like image 23
Marcin Deptuła Avatar answered Jan 07 '23 16:01

Marcin Deptuła