October 2008 Entries

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();
            return item;
Which allows us to do something like this:

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