At the end of the previous chapter I asked you to sell 100 loaves of bread from a store that had 20, and the program left the stock at -80 without complaining. A negative price works the same way. The Product class controls who changes the data, but it accepts any value.
Today we fix that and put three concepts from chapter 8 into code: encapsulation, inheritance and polymorphism. We also add interfaces, the most practical way to abstract in C#.
Encapsulation: the object protects itself
This is what happens today with the class from the previous chapter (a fragment, it uses that Product class):
var bread = new Product("Bread", -5m, 20);
bread.Sell(100);
Console.WriteLine(bread);
Bread: -5.00 (-80 in stock)
A loaf of bread with a negative price and negative stock. The problem is that Product lets itself be built, or changed, into a state that makes no sense. Encapsulation means the object defends its own state: the data is private or read-only, and every way of creating or changing it validates before accepting.
In C# validation is done with throw: you raise an exception like the ones in chapter 7, and the caller decides what to do with it. The one used for invalid arguments is ArgumentException:
class Product
{
public string Name { get; }
public decimal Price { get; private set; }
public int Stock { get; private set; }
public Product(string name, decimal price, int stock)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("The name cannot be empty.", nameof(name));
}
if (price < 0)
{
throw new ArgumentException("The price cannot be negative.", nameof(price));
}
if (stock < 0)
{
throw new ArgumentException("The stock cannot be negative.", nameof(stock));
}
Name = name;
Price = price;
Stock = stock;
}
public void Sell(int quantity)
{
if (quantity <= 0)
{
throw new ArgumentException("The quantity must be greater than zero.", nameof(quantity));
}
if (quantity > Stock)
{
throw new ArgumentException($"Not enough stock: {Stock} left.", nameof(quantity));
}
Stock -= quantity;
}
}
Quick notes. string.IsNullOrWhiteSpace returns true if the text is null, empty or only spaces. nameof(price) produces the text "price", the name of the parameter that failed, and it updates itself if you rename it. Name { get; } with no set or init can only be assigned in the constructor.
What matters is the effect. A Product can no longer exist with invalid values, because the only door is the constructor. And since Stock has a private set, the only way to lower it is Sell, which checks the quantity. Whoever uses the class does not have to remember to validate.
As in chapter 7, the caller decides what to do with the error:
try
{
_ = new Product("Bread", -5m, 20);
}
catch (ArgumentException ex)
{
Console.WriteLine($"Could not create it: {ex.Message}");
}
Could not create it: The price cannot be negative. (Parameter 'price')
The message ends with the parameter name, which .NET adds on its own. The _ = discards the object: here we only care whether it fails.
Inheritance: a class that starts from another
Some corner store products spoil: milk, cheese. You want them to behave like a Product, but with one more piece of data (days until expiry) and a final price that drops as the date gets close. Inheritance lets you write only what changes:
class PerishableProduct : Product
{
public int DaysToExpire { get; }
public PerishableProduct(string name, decimal price, int stock, int daysToExpire)
: base(name, price, stock)
{
if (daysToExpire < 0)
{
throw new ArgumentException("The days to expire cannot be negative.", nameof(daysToExpire));
}
DaysToExpire = daysToExpire;
}
public override decimal FinalPrice() => DaysToExpire <= 2 ? Price / 2 : Price;
}
Piece by piece:
: ProductmeansPerishableProductis aProduct. It getsName,Price,StockandSellwithout writing them again.: base(name, price, stock)calls the base class constructor. SinceProductrequires those three values and validates them, the child class has to hand them over first.overridereplaces a base method, but only one markedvirtual. For that we add this toProduct:
public virtual decimal FinalPrice() => Price;
virtual says “child classes may change this method”. A regular Product charges its price. A perishable one two days or less from expiry charges half. (condition ? a : b is a one-line if: if the condition is true it returns a, otherwise b.)
You already saw override with ToString(): it is a virtual method of object, the class every C# class inherits from.
A class can be marked abstract when it exists only to be inherited:
abstract class Packaging
{
public abstract decimal Cost();
}
class Bag : Packaging
{
public override decimal Cost() => 0.05m;
}
You cannot do new Packaging(), and every child must implement Cost. We do not need it in our code.
Polymorphism: one message, several answers
Here is where inheritance pays off. A variable of type Product can hold a Product or any class that inherits from it, and when you call FinalPrice() C# runs the version belonging to the real object:
var products = new List<Product>
{
new Product("Coffee", 3.50m, 10),
new PerishableProduct("Milk", 2.40m, 8, 1),
new PerishableProduct("Cheese", 4.00m, 5, 6)
};
foreach (var p in products)
{
Console.WriteLine($"{p.Name}: {p.FinalPrice():0.00}");
}
Coffee: 3.50
Milk: 1.20
Cheese: 4.00
The loop does not know which one is perishable and which is not. It calls FinalPrice() and each object answers in its own way: the milk expires in one day and costs half, the cheese has six days left and costs full price. If tomorrow you add a third kind of product, this loop does not change.
Interfaces: a contract without inheritance
Inheritance has a cost. A class can inherit from only one base, and the child is tied to the base’s details: if you change Product, you can break every child. Used for everything, it ends in tangled class trees; we talk about that in the next chapter.
An interface is a contract: it lists what a class promises it can do, without giving any code. By convention its name starts with I.
A corner store receipt has product lines, but also the shipping fee, and a discount coupon would be another line. Shipping is not a product, so it makes no sense for it to inherit from Product. What they have in common is that each has a description and an amount:
interface IPurchaseLine
{
string Description { get; }
decimal Amount();
}
Every class that signs the contract implements it:
class ProductLine : IPurchaseLine
{
private readonly Product _product;
private readonly int _quantity;
public ProductLine(Product product, int quantity)
{
if (quantity <= 0)
{
throw new ArgumentException("The quantity must be greater than zero.", nameof(quantity));
}
_product = product;
_quantity = quantity;
}
public string Description => $"{_quantity} x {_product.Name}";
public decimal Amount() => _product.FinalPrice() * _quantity;
}
class ShippingFee : IPurchaseLine
{
private readonly decimal _amount;
public ShippingFee(decimal amount)
{
_amount = amount;
}
public string Description => "Shipping";
public decimal Amount() => _amount;
}
private readonly marks a private field that is only assigned in the constructor; the leading underscore is a common convention for those fields. Notice too that ProductLine has a Product instead of being one. That “has a” relationship is called composition, and it is the tool you will reach for most often instead of inheriting.
Since both classes fulfill the contract, a list of IPurchaseLine can mix them:
var receipt = new List<IPurchaseLine>
{
new ProductLine(coffee, 2),
new ProductLine(milk, 3),
new ShippingFee(2.00m)
};
decimal total = 0;
foreach (var line in receipt)
{
Console.WriteLine($"{line.Description}: {line.Amount():0.00}");
total += line.Amount();
}
Console.WriteLine($"Total: {total:0.00}");
It is polymorphism again, but without the classes sharing a base. My rule for deciding: use inheritance when you can truly say “X is a Y” and the base is stable; for everything else, start with an interface and composition. Changing an interface is easier than untangling a hierarchy. PerishableProduct is good for learning override, but in a real system the expiry discount would probably be a separate piece.
The complete program
Here is everything together, ready to paste into Program.cs:
var coffee = new Product("Coffee", 3.50m, 10);
var milk = new PerishableProduct("Milk", 2.40m, 8, 1);
try
{
coffee.Sell(50);
}
catch (ArgumentException ex)
{
Console.WriteLine($"Could not sell: {ex.Message}");
}
var receipt = new List<IPurchaseLine>
{
new ProductLine(coffee, 2),
new ProductLine(milk, 3),
new ShippingFee(2.00m)
};
decimal total = 0;
foreach (var line in receipt)
{
Console.WriteLine($"{line.Description}: {line.Amount():0.00}");
total += line.Amount();
}
Console.WriteLine($"Total: {total:0.00}");
interface IPurchaseLine
{
string Description { get; }
decimal Amount();
}
class Product
{
public string Name { get; }
public decimal Price { get; private set; }
public int Stock { get; private set; }
public Product(string name, decimal price, int stock)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("The name cannot be empty.", nameof(name));
}
if (price < 0)
{
throw new ArgumentException("The price cannot be negative.", nameof(price));
}
if (stock < 0)
{
throw new ArgumentException("The stock cannot be negative.", nameof(stock));
}
Name = name;
Price = price;
Stock = stock;
}
public void Sell(int quantity)
{
if (quantity <= 0)
{
throw new ArgumentException("The quantity must be greater than zero.", nameof(quantity));
}
if (quantity > Stock)
{
throw new ArgumentException($"Not enough stock: {Stock} left.", nameof(quantity));
}
Stock -= quantity;
}
public virtual decimal FinalPrice() => Price;
}
class PerishableProduct : Product
{
public int DaysToExpire { get; }
public PerishableProduct(string name, decimal price, int stock, int daysToExpire)
: base(name, price, stock)
{
if (daysToExpire < 0)
{
throw new ArgumentException("The days to expire cannot be negative.", nameof(daysToExpire));
}
DaysToExpire = daysToExpire;
}
public override decimal FinalPrice() => DaysToExpire <= 2 ? Price / 2 : Price;
}
class ProductLine : IPurchaseLine
{
private readonly Product _product;
private readonly int _quantity;
public ProductLine(Product product, int quantity)
{
if (quantity <= 0)
{
throw new ArgumentException("The quantity must be greater than zero.", nameof(quantity));
}
_product = product;
_quantity = quantity;
}
public string Description => $"{_quantity} x {_product.Name}";
public decimal Amount() => _product.FinalPrice() * _quantity;
}
class ShippingFee : IPurchaseLine
{
private readonly decimal _amount;
public ShippingFee(decimal amount)
{
_amount = amount;
}
public string Description => "Shipping";
public decimal Amount() => _amount;
}
Could not sell: Not enough stock: 10 left. (Parameter 'quantity')
2 x Coffee: 7.00
3 x Milk: 3.60
Shipping: 2.00
Total: 12.60
Mini-exercise: a discount coupon
Add a third kind of receipt line: a coupon.
- Create the
Couponclass implementingIPurchaseLine, with read-onlyCodeandValueproperties. - The constructor must throw
ArgumentExceptionif the code is empty or the value is not greater than zero. Descriptionis"Coupon "followed by the code, andAmount()returns the value as a negative number.- Add
new Coupon("WELCOME", 1.50m)at the end of the receipt list. The loop should not change.
Suggested solution
class Coupon : IPurchaseLine
{
public string Code { get; }
public decimal Value { get; }
public Coupon(string code, decimal value)
{
if (string.IsNullOrWhiteSpace(code))
{
throw new ArgumentException("The code cannot be empty.", nameof(code));
}
if (value <= 0)
{
throw new ArgumentException("The value must be greater than zero.", nameof(value));
}
Code = code;
Value = value;
}
public string Description => $"Coupon {Code}";
public decimal Amount() => -Value;
}
In the receipt list, the last element becomes new ShippingFee(2.00m), new Coupon("WELCOME", 1.50m) (with a comma between the two). The output changes to:
Could not sell: Not enough stock: 10 left. (Parameter 'quantity')
2 x Coffee: 7.00
3 x Milk: 3.60
Shipping: 2.00
Coupon WELCOME: -1.50
Total: 11.10
Notice what you did not touch: the loop, Product, ProductLine. You added a class and the receipt absorbed it. That is the benefit of programming against an interface.
What you learned
- Encapsulation: the state is private or read-only and every constructor or method validates with
throw new ArgumentException(...)before accepting a value. - Inheritance:
: Basemakes a class a special case of another;base(...)calls the base constructor. virtuallets a child change a method, andoverridechanges it.abstractforces the children to implement it.- Polymorphism: a list of a base type or an interface can walk over different objects, and each one answers with its own behavior.
- An interface is a contract without code. A class can implement several, and it does not tie classes together.
- My starting point: interface and composition first; inheritance only when “is a” is obvious and the base is stable.
In the next chapter we look at the most common mistakes with object-oriented programming: classes that do everything, too many classes, inheritance for everything and objects that are only data.
Stuck?
If an exception does not show up where you expected, or you are not sure when to use inheritance and when an interface, DM me on Instagram or ask in the Discord community. Paste your code and what you get, and we will work through it.
