Search code examples
c#classcallbackattributesinitialization

C# callback for when a class with attribute got instantiated


Is there something like a callback for when when a class Foo with a specific attribute got instantiated? A little like this pseudo code:

void OnObjectWithAttributeInstantiated(Type attributeType, object o) {
    // o is the object with the attribute
}

So i was trying to create an attribute AutoStore. Imagine the following:

Given a class Foo with that tag:

[AutoStore]
public class Foo { ... }

Then (somewhere else in the code, no matter where) you instantiate that class

Foo f = new Foo()

I now want, that this object f will be automatically added to a list of objects (e.g. in a static class or something)

If there is no such way, do you have some ideas how to do a work-around?

Edit I dont want to use a superclass which does that for purposes of clean code

Best regards Briskled


Solution

  • I don't think you can do that. Because attributes are there for you to discover at runtime. But a possible solution might be to create a factory to wrap the whole thing, like -

    public class Factory
    {
        public static T Instantiate<T>() where T : class
        {
            // instantiate your type
            T instant = Activator.CreateInstance<T>();
    
            // check if the attribute is present
            if (typeof(T).GetCustomAttribute(typeof(AutoStore), false) != null)
            {
                Container.List.Add(instant);
            }
            return instant;
        }
    }
    
    public static class Container
    {
        public static List<object> List { get; set; } = new List<object>();
    }
    

    and then you can use it like -

    Foo foo = Factory.Instantiate<Foo>();
    foo.Bar = "Some Bar";