[Home](../../) › [Metalama](../../metalama) › [Use Cases](../applications.md) › [Applications](classics.md) › [Classic Object Services](object-services.md) › ToString

# ToString

> Learn how to use Metalama to automatically generate ToString methods for C# classes, improving debugging and logging with customizable formatting options.

Canonical: https://postsharp.net/metalama/applications/tostring.html

A well-crafted `ToString` implementation speeds up debugging and log analysis. Typically, it should return a concise description of the object, highlighting its identity and state. With Metalama, you can skip writing this repetitive code manually.

## Example

Consider the [ToString example aspect](https://doc.metalama.net/examples/tostring/tostring-1), applied to a class. In this scenario, we adopt an opt-out approach, marking members with `[NotToString]` that we prefer to exclude.

```csharp
// [<focus>]
[ToString]
// [<endfocus>]
internal class MovingVertex
{
    public double X { get; set; }

    public double Y { get; set; }

    public double DX { get; set; }

    public double DY { get; set; }

    // [<focus>]
    [NotToString]
    // [<endfocus>]
    public double Velocity => Math.Sqrt((this.DX * this.DX) + (this.DY * this.DY));
}
```

The aspect generates the following code:

```csharp
public override string ToString()
{
    return $"{{MovingVertex DX={DX}, DY={DY}, X={X}, Y={Y}}}";
}
```

To modify the code generation pattern, adjust the aspect class itself, `ToStringAttribute`.

## Resources

- Commented example: [ToString](https://doc.metalama.net/examples/tostring/tostring-1)

---

## Site navigation

- Previous: [Cloning](cloning.md)
- Next: [Equatable](equatable.md)
- Index of the whole site: [llms.txt](../../llms.txt)

