(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 `Order`s in a `GridLine`, you will see that `Time` is shown correctly but each `OrderLine`s is shown as in {numref}`order-datagrid-if-tostring-not-defined`.

:::{figure} ../img/order-datagrid-if-tostring-not-defined.png
:name: order-datagrid-if-tostring-not-defined
If `toString` for the `ObservableCollection` is not defined, then we don't see its contents, but only its type.
:::


```cs
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 `OrderLine`s, so we have to define `toString` for `OrderLine` that creates a `string` representation. This method is also used when your `Console.Write` an object:

```cs
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`.

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