implement a fluent builder for basket in csharp

Here's an example implementation of a fluent builder for a basket class in C#:

main.cs
public class BasketBuilder
{
    private readonly Basket _basket;

    public BasketBuilder()
    {
        _basket = new Basket();
    }

    public BasketBuilder WithItem(string name, decimal price, int quantity = 1)
    {
        _basket.Add(new BasketItem(name, price, quantity));
        return this;
    }

    public BasketBuilder WithDiscount(decimal discountAmount)
    {
        _basket.ApplyDiscount(discountAmount);
        return this;
    }

    public Basket Build()
    {
        return _basket;
    }
}

public class BasketItem
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }

    public BasketItem(string name, decimal price, int quantity)
    {
        Name = name;
        Price = price;
        Quantity = quantity;
    }
}

public class Basket
{
    private List<BasketItem> _items;

    public decimal TotalPrice => _items.Sum(item => item.Price * item.Quantity);

    public decimal TotalDiscount { get; private set; }

    public decimal FinalPrice => TotalPrice - TotalDiscount;

    public Basket()
    {
        _items = new List<BasketItem>();
    }

    public void Add(BasketItem item)
    {
        _items.Add(item);
    }

    public void ApplyDiscount(decimal discountAmount)
    {
        TotalDiscount += discountAmount;
    }

    public IEnumerable<BasketItem> GetItems()
    {
        return _items.AsEnumerable();
    }
}
1430 chars
72 lines

This code defines a BasketBuilder class that exposes fluent methods to add items and discounts to a new Basket instance. The Basket class itself has properties for calculating the total and final prices of the basket, as well as methods to add items and apply discounts.

Here's an example of how to use the BasketBuilder to create a basket:

main.cs
var basket = new BasketBuilder()
    .WithItem("Apples", 0.5m, 2)
    .WithItem("Oranges", 0.75m)
    .WithDiscount(0.1m)
    .Build();
136 chars
6 lines

This code creates a new Basket instance with two apple items, one orange item, and a 10% discount, and assigns it to the basket variable.

gistlibby LogSnag