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?