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
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.
The Mikado Method by Ola Ellnestam Daniel Brolund(22542)
Hello! Python by Anthony Briggs(21724)
Secrets of the JavaScript Ninja by John Resig Bear Bibeault(20297)
Dependency Injection in .NET by Mark Seemann(19635)
The Well-Grounded Java Developer by Benjamin J. Evans Martijn Verburg(19406)
Kotlin in Action by Dmitry Jemerov(19348)
OCA Java SE 8 Programmer I Certification Guide by Mala Gupta(18841)
Algorithms of the Intelligent Web by Haralambos Marmanis;Dmitry Babenko(17650)
Adobe Camera Raw For Digital Photographers Only by Rob Sheppard(16969)
Grails in Action by Glen Smith Peter Ledbrook(16801)
Sass and Compass in Action by Wynn Netherland Nathan Weizenbaum Chris Eppstein Brandon Mathis(14285)
Secrets of the JavaScript Ninja by John Resig & Bear Bibeault(12245)
Test-Driven iOS Development with Swift 4 by Dominik Hauser(10948)
A Developer's Guide to Building Resilient Cloud Applications with Azure by Hamida Rebai Trabelsi(10598)
Jquery UI in Action : Master the concepts Of Jquery UI: A Step By Step Approach by ANMOL GOYAL(10070)
Hit Refresh by Satya Nadella(9125)
The Kubernetes Operator Framework Book by Michael Dame(8542)
Exploring Deepfakes by Bryan Lyon and Matt Tora(8367)
Robo-Advisor with Python by Aki Ranin(8311)