C# Cookbook by Joe Mayo

C# Cookbook by Joe Mayo

Author:Joe Mayo [Joe Mayo]
Language: eng
Format: epub
Publisher: O'Reilly Media, Inc.
Published: 2021-06-30T16:00:00+00:00


3.6 Customizing Class String Representation

Problem

The class representation in the debugger, string parameters, and log files is illegible and you want to customize its appearance.

Solution

Here’s a class with a custom ToString method:

using System; using System.Text; namespace Section_03_06 { class Order { public int ID { get; set; } public string CustomerName { get; set; } public DateTime Created { get; set; } public decimal Amount { get; set; } public override string ToString() { var stringBuilder = new StringBuilder(); stringBuilder.Append(nameof(Order)); stringBuilder.Append(" {
"); if (PrintMembers(stringBuilder)) stringBuilder.Append(" "); stringBuilder.Append("
}"); return stringBuilder.ToString(); } protected virtual bool PrintMembers(StringBuilder builder) { builder.Append(" " + nameof(ID)); builder.Append(" = "); builder.Append(ID); builder.Append(",
"); builder.Append(" " + nameof(CustomerName)); builder.Append(" = "); builder.Append(CustomerName); builder.Append(",
"); builder.Append(" " + nameof(Created)); builder.Append(" = "); builder.Append(Created.ToString("d")); builder.Append(",
"); builder.Append(" " + nameof(Amount)); builder.Append(" = "); builder.Append(Amount); return true; } } }

Here’s an example of how that’s used:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.