Generic Factory over Object Initializers

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.


Related posts

Comments

October 3. 2008 01:36 PM

Chris Sutton

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. Smile

Chris

Chris Sutton

October 3. 2008 02:31 PM

Robert Standefer

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.

Robert Standefer

October 20. 2008 07:40 AM

Tommy Carlier

What's wrong with this instead:

var aRunningCar = Builder.Create<Car>();
aRunningCar.Engine = new Engine("v8"); // 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?

Tommy Carlier

October 20. 2008 11:32 AM

Nick Parker

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.

Nick Parker

October 21. 2008 03:22 PM

Javier Lozano

Like the syntax and it flows pretty smoothly.

Javier Lozano

October 23. 2008 05:05 AM

free ebooks download

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

free ebooks download

November 24. 2008 01:39 AM

Busby SEO Test

thanks it really helps me !!

Busby SEO Test

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

December 5. 2008 04:04 AM

Twitter

    Search

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2008