For the kind of scenario you give as an example, I would give the class an
IFormattable implementation as well as ToString() override. Then a user of
the class can format the name in any of the ways the implementation
supports, rather than being confined to a fixed way of doing it. Your
ToString() override would then just call the ToString("g",null) ("g" for
generic/general, following the framework implementation for standard
format strings) of the IFormattable. You could have format strings "f" and
"l" for first name and last name, and so call ToString("g",null) giving
"Michael Phelps" (arbitraily chosen "standard format), ToString("f",null)
giving "Michael", ToString("l",null) giving "Phelps", ToString("fl",null)
giving "Michael Phelps", ToString("lf",null) giving "Phelps, Michael" etc.
(I would probably also provide a ToString(string fmt) which just calls
IFormattable.ToString(fmt,null) to avoid having to pass a null all the
time.)
>
For debugging, I often use the DebuggerDisplay (or DebuggerProxy)
attribute on the class. Sometimes I just call ToString() from this, more
often I will individually access certain properties so it's clear what
each property value in the object is. It all depends on what I want to see
for that particular class.
>
// Alternative 1a
[DebuggerDisplay("Name = {ToString()}")]
// Alternative 1b
[DebuggerDisplay("Name = {ToString("lf")}")]
// Alternative 2
[DebuggerDisplay("FirstName = {FirstName}, LastName = {LastName}")]
class Person : IFormattable
{
public string FirstName { get; }
public string LastName { get; }
>
public override string ToString()
{
return ToString("g",null);
}
>
public string ToString(string fmt, IFormatProvider fp)
{
switch (fmt)
{
case "g":
default:
return string.Format("{0} {1}",FirstName,LastName);
case "f":
case "l":
case "fl":
case "lf":
//etc.
}
}
}
>
"Berryl Hesh" <efinger9@yahoo.comwrote in message
news:poIqk.257$RV7.105@newsfe01.iad...
Quote:
Originally Posted by
>I'm interested in how experienced.Net developers might handle routine
>display tasks as a general strategy. Let's say you have a use in your
>domain for value objects that encapsulate a person's Name, for example.
>>
>Would anyone write a custom format provider to display the last name
>first ("Phelps, Michael"), or first name first ("Michael Phelps")? Or use
>the familiar name instead ("Mike"). Would you use some other technique?
>Would you provide a Parse method?
>>
>How about generalized debugging ToString stratagies? Any favorite
>techniques and / or tools? For example, "[FIRSTNAME = Mike, LASTNAME =
>Phelps]".
>>
>TIA, and thanks for sharing your experience!
>>
>
>