Information Technology Reference
In-Depth Information
public override string ToString()
{
return Name;
}
If you don't follow any of the other recommendations in this item, follow
that exercise for all the types you define. It will save everyone time imme-
diately. When you provide a reasonable implementation for the Object
.ToString() method, objects of this class can be more easily added to WPF
controls, Silverlight controls, Web Form controls, or printed output. The
.NET BCL uses the override of Object.ToString() to display objects in any
of the controls: combo boxes, list boxes, text boxes, and other controls. If
you create a list of customer objects in a Windows Form or a Web Form,
you get the name displayed as the text System.Console.WriteLine() and
System.String.Format() as well as ToString() internally. Anytime the .NET
BCL wants to get the string representation of a customer, your customer
type supplies that customer's name. One simple three-line method handles
all those basic requirements.
In C# 3.0, the compiler creates a default ToString() for all anonymous
types. The generated ToString() method displays the value of each scalar
property. Properties that represent sequences are LINQ query results and
will display their type information instead of each value. This snippet of
code:
int [] list = new int [] { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 };
var test = new { Name = "Me" ,
Numbers = from l in list select l };
Console .WriteLine(test);
will display:
{ Name = Me, Numbers =
System.Linq.Enumerable+WhereSelectArrayIterator`2
[System.Int32,System.Int32] }
Even compiler-created anonymous types display a better output than your
user-defined types unless you override ToString(). You should do a better
job of supporting your users than the compiler does for a temporary type
with a scope of one method.
This one simple method, ToString(), satisfies many of the requirements
for displaying user-defined types as text. But sometimes, you need more.
 
Search WWH ::




Custom Search