Powerslave
Powerslave

Reputation: 331

Using attribute to create an instance of class

I have 2 fields like

private IFruit fruit;
private Banana banana;

An instance of Banana is created like this:

var banana = new Banana(fruit);

I want to create an attribute for Banana fields to do the job of creating Banana instance for me!

Upvotes: 1

Views: 696

Answers (2)

Boas Enkler
Boas Enkler

Reputation: 12557

Also some container like unity offer this functionality

Upvotes: 0

C.Evenhuis
C.Evenhuis

Reputation: 26446

Attributes don't cause any code to be executed - you'll have to use reflection to access them. If you want you could implement a base class that has this behavior, and add the reflection code to the constructor:

abstract class AutoCreateBase
{
    public MyBase()
    {
        // Reflection to go through the fields, find the attributes, and use Activator.CreateInstance() on each
    }
}

class MyClass : AutoCreateBase
{
    [AutoCreate]
    private Banana banana;
}

Upvotes: 1

Related Questions