Generic Factory over Object Initializers

posted @ Thursday, October 02, 2008 11:43 PM

 

Consider the following generic factory method:

    public class Builder
    {
        public static TType Create<TType>(Action<TType> actionOnTType) where TType : new()
        {
            var item = new TType();
            actionOnTType(item);
            return item;
        }
    }

 which allows us to do something like this:

            var aRunningCar = Builder.Create<Car>(car => 
            {
                car.Engine = new Engine("v8");
                car.Start();
            });

What are your thoughts on the above over the standard object initializers found in C# 3.0?  Initially the difference is that this allows us to invoke methods on the instance as the instance is passed into our lambda expression whereas object initializers only allow us to set property values to be assigned to the instance.  It's a subtle difference but something I think could be helpful.  Just a random thought that passed through my head after I finished watching the debate tonight.

Comments
Chris Sutton - 10/4/2008 6:36 AM
# re: Generic Factory over Object Initializers
Looks like a cool idea. I'm going to try it in a project today to see how it works.

So did the debates inspire you to write this? I can't wait for the next debate. :)

Chris
Robert Standefer - 10/4/2008 7:31 AM
# re: Generic Factory over Object Initializers
Hi Nick,

Can you point me to a good resource to learn more about the concepts used in the generic factory method? I mean, I can look at MSDN and such, but if you know of some good articles, I'd love to see them.
Tommy Carlier - 10/21/2008 12:40 AM
# re: Generic Factory over Object Initializers
What's wrong with this instead:

var aRunningCar = Builder.Create&lt;Car&gt;();
aRunningCar.Engine = new Engine(&quot;v8&quot;); // why not use a factory for Engine?
aRunningCar.Start();

I know it's just a simple example, but what would be the advantage of using a delegate for initialization instead of just using the object after creating it?
Nick Parker - 10/21/2008 4:32 AM
# re: Generic Factory over Object Initializers
Tommy,

It's partially stylistic, obviously we don't want the lambda to be excessively long in and of itself. Nothing is inherently wrong with your example either.
Javier Lozano - 10/22/2008 8:22 AM
# re: Generic Factory over Object Initializers
Like the syntax and it flows pretty smoothly.
free ebooks download - 10/23/2008 10:05 PM
# re: Generic Factory over Object Initializers
I have searched the net and I should say I have not come across an article like this which is so easy to understand and learn the concepts.
cheers
Comments have been closed on this topic.