Printable classes

Printable classes#

By implementing public override string toString() in a class, we can create a string representation of classes that are more complex than fundamental classes like string, int etc.

toString() is called whenever an object is printed or shown by the GUI.

When you try to show Orders in a GridLine, you will see that Time is shown correctly but each OrderLines is shown as in Fig. 23.

../_images/order-datagrid-if-tostring-not-defined.png

Fig. 23 If toString for the ObservableCollection is not defined, then we don’t see its contents, but only its type.#

public class PrintableObservableCollection<T> : ObservableCollection<T>
{
    public override string ToString()
    {
        return string.Join(Environment.NewLine, Items);
    }
}

Here we concatenate every item stored in the list with a newline (\n). Before concatenation, each item in the list are converted to string.

Each Order has a collection of OrderLines, so we have to define toString for OrderLine that creates a string representation. This method is also used when your Console.Write an object:

public class OrderLine
{
    public Item Item { get; set; }
    public decimal Quantity { get; set; }

    public override string ToString()
    {
        return $"{Item.Name} x {Quantity}";
    }
}

Then you can use the new class in the Order class, so we can see a string representation of OrderLines.

public class Order
{
    public PrintableObservableCollection<OrderLine> OrderLines { get; set; }
...
}