1

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!

3
  • 1
    Google for dependency injection. It does what you are looking for. Commented Jul 12, 2011 at 9:17
  • 1
    not really clear what you want, sorry. Can you, please, redifine yuor question ? Commented Jul 12, 2011 at 9:18
  • You could also look into the Factory pattern. But still your question is not clear enough to give a good answer. Commented Jul 12, 2011 at 9:20

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Also some container like unity offer this functionality

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.