0

I'm using Fluent Builder with callbacks to configure a context on the fly.

Currently, I have a PlaneContext class with a list of passengers which I want to populate by using the method AddPassenger like:

var builder = new PlaneBuilder<PlaneContext>();

builder.AddPlane(plane => plane.Name = "Boeng") 
    .AddPassenger(passenger => passenger.Name = "Robert")
    .AddPassenger(passenger => passenger.Name = "Johnny");

As shown above, I've created a PlaneBuilder class to chain methods like these. The first method AddPlane works fine, but the chained methods AddPassenger does not work as expected. My lack of understanding in delegates as Action<T> and Func<T, TResult> is highly the issue.

This is what I have tried, but I get cannot implicitly convert string to Passenger:

public PlaneBuilder<T> AddPassenger(Func<Passenger, Passenger> callback)
{
    var passenger = callback(new Passenger());
    _planeContext.Passengers.Add(passenger);
    return this;
}

Currently, this is how the PlaneBuilder class looks like:

class PlaneBuilder<T>
{

    private PlaneContext _planeContext = new PlaneContext();

    public PlaneBuilder<T> AddPlane(Action<PlaneContext> callback)
    {
        callback(_planeContext);
        return this;
    }

    public PlaneBuilder<T> AddPassenger(Func<Passenger, Passenger> callback)
    {
        // Goal is to create a passenger
        // Add it to the passengers list in PlaneContext
        var passenger = callback(new Passenger());
        _planeContext.Passengers.Add(passenger);
        return this;
    }
}

Lastly, here's the PlaneContext class:

class PlaneContext
{
    public string Name { get; set; }
    public string Model { get; set; }
    public List<Passenger> Passengers { get; set; }
}

In short, how can I add passenger to PlaneContext using callbacks?

  • A very similar question was asked recently here: https://stackoverflow.com/questions/59021513/using-fluent-interface-with-builder-pattern Following that advice you could just add a separate Passenger builder – Simon Katanski Nov 24 '19 at 21:07
  • Thanks @SimonKatanski! I manage to solve the problem, I also realize I had another problem where I forgot to initialize the list which gave me error `Object reference not set to an instance of an object`. I'll post a solution below. – netcompanyguy Nov 25 '19 at 06:45

1 Answers1

1

The is a solution to my problem as described above:

First, the list must be initialized in PlaneContext class like:

public List<Passenger> Passengers = new List<Passenger>();

Secondly, in order to add a passenger to Passengers list: create a new instance of Passenger class, pass it as an argument to the callback method, and then add it to the passengers list like:

public PlaneBuilder<T> AddPassenger(Action<Passenger> callback)
{
    var passenger = new Passenger();
    callback(passenger);
    _planeContext.Passengers.Add(passenger);
    return this;
}