Search code examples
c#lambdabuilder

C# Lambda Builder Pattern


I have a class and it has 11 properties (most are inherited). I don't quite like passing in 11 parameters. I know I could create a ModelBuilder class and do the following:

new ModelBuilder().WithProp1(prop1).WithProp2(prop2).Build();

But I was thinking of only one method generic enough to accept a Func which you can then specify the prop to assign:

public Car With<TOut>(Func<Car, TOut> lambda)
{
    lambda.Invoke(this);
    return this;
}

Usage:

var car = new Car()
        .With(x => x.VehicleType = "Sedan")
        .With(x => x.Wheels = 4)
        .With(x => x.Colour = "Pink")
        .With(x => x.Model = "fancyModelName")
        .With(x => x.Year = "2007")
        .With(x => x.Engine = "Large")
        .With(x => x.WeightKg = 2105)
        .With(x => x.InvoiceNumber = "1234564")
        .With(x => x.ServicePlanActive = true)
        .With(x => x.PassedQA = false)
        .With(x => x.Vin = "blabla");

This seems to work. My question: is there anything I'm missing here in terms of implementation (barring the obvious - dragging this method to an interface or helper class)? Are there any gotchas that may surface with this implementation that I am overlooking?


Solution

  • You're over complicating things, instead, you should leverage the object initializer syntax which is much simpler and more readable.

    var car = new Car { 
         VehicleType = "Sedan", 
         Wheels = 4,
         Colour = "Pink", 
         ... 
    };