Älskar
Älskar

Reputation: 2577

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?

Upvotes: 7

Views: 2082

Answers (2)

Sebastian Hofmann
Sebastian Hofmann

Reputation: 1438

If you like to stick to something like your original approach, I suggest the following, which simplifies it:

public static T With<T>(this T obj, Action<T> action)
{
     action(obj);
     return obj;
}

This extension method lets you initialize the properties of your object in a cleaner way:

var car = new Car().With(c =>
{
    c.VehicleType = "Sedan";
    c.Model = "fancyModelName";
    //and so on
});

Upvotes: 7

Ousmane D.
Ousmane D.

Reputation: 56453

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", 
     ... 
};

Upvotes: 5

Related Questions