#663 – Visual Studio Debugger Will Call Your Object’s ToString Method

When you examine the value of a variable in the Visual Studio debugger, the debugger will call the object’s ToString method in order to display a single value for the object.  If the object’s type contains other members, you can typically expand the display to show the various members.

What this means for custom types is that you’ll see the results of the default implementation of ToString, which is to just display the name of the type.  We can see this by looking at a couple of Dog objects in the Locals window of the debugger.  Note that the “value” of each is just listed as DogLibrary.Dog.

However, if we implement the Dog.ToString method and have it dump out the dog’s name and age, we’ll now see that information in the debugger.

This demonstrates why it’s often useful, for debugging purposes, to implement ToString.

Advertisements

#662 – Overriding the ToString Method for a Custom Type

Every type inherits a ToString method, since every type inherits, directly or indirectly, from System.Object.  For a custom type, this method will by default just display the name of the type.

Dog kirby = new Dog("Kirby", 13);

Console.WriteLine(kirby.ToString());

You can, however, override the ToString method in your class so that it provides information about the specific instance of the class.  In the example below, we override Dog.ToString.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public override string ToString()
        {
            return string.Format("Dog [{0}] is {1} years old", Name, Age);
        }
    }

#661 – Every Object Has A ToString Method

Since every type inherits either directly or indirectly from System.Object, and System.Object has a ToString method, every object inherits a ToString method.

The ToString method is intended to return a string identifying or representing the object, i.e. that specific instance.  This is true for both value types and reference types.

For built-in types, ToString generally returns what you’d expect.  For example, for a System.Int32 (int), it returns the value of the integer.

For custom types, if you don’t override ToString and provide something more meaningful, ToString just returns a string representing the type of the object.

Dog kirby = new Dog("Kirby", 13);
Cow bessie = new Cow("Bessie");
int i = 12;
double d = 1.38e-23;
DayOfWeek bestDay = DayOfWeek.Saturday;
object o = new System.Object();
DateTime dt = new DateTime(1536, 5, 19);

// ToString can be called explicitly, or is called
// implicitly when passing object as string parameter
Console.WriteLine(kirby.ToString());   // Explicit
Console.WriteLine(bessie);             // Implicit
Console.WriteLine(i);
Console.WriteLine(d);
Console.WriteLine(bestDay);
Console.WriteLine(o);
Console.WriteLine(dt);

#196 – Using the ToString() Method on a Flags-Based Enum Type

When you use the ToString method on an enumeration type that has been defined with the Flags attribute, the method correctly decomposes the current value into its constituent flags.

Assuming the following enumeration type:

        [Flags]
        public enum Talents {
            Singing = 1,
            Dancing = 2,
            Juggling = 4,
            JokeTelling = 8};

And the following enumerated values:

            Talents wcFields = Talents.Juggling;
            Talents fredTalents = Talents.Singing | Talents.Dancing;
            Talents ernieTalents = Talents.Singing | Talents.Juggling | Talents.JokeTelling;

The ToString method, implicitly called by Console.WriteLine, produces the following output:

            Console.WriteLine(wcFields);            // Juggling
            Console.WriteLine(fredTalents);         // Singing, Dancing
            Console.WriteLine(ernieTalents);        // Singing, Juggling, JokeTelling

#193 – An Enum Type’s ToString Method Displays the Member’s Name

Normally, when you call the ToString method on a variable that stores an integer value, the value of the integer is displayed.

            int x = 42;
            Console.WriteLine(x.ToString());   // Displays: 42
            Console.WriteLine(x);     // Same thing--ToString implicitly called

If you call ToString on an enum type variable, however, the textual name of the enumerated member is displayed.

        public enum Mood {
            Crabby = -5,
            Happy = 5,
            Petulant = -2,
            Elated = 10};

        static void Main()
        {
            Mood myMood = Mood.Crabby;
            Mood dogsMood = Mood.Elated;

            Console.WriteLine(myMood);     // ToString implicitly called; displays: Crabby

            Console.WriteLine(dogsMood);   // Displays: Elated
        }

#95 – ToString() Called Automatically When Doing String Concatenation

When doing string concatenation, either using the + operator or when using the String.Concat or String.Format methods, you can concatenate objects that are not strings.  .NET will attempt to convert these objects to strings before doing the concatenation by calling the object’s ToString method.

Here’s an example:

string s1 = "Ten: " + 10;   // Ten: 10

This is equivalent to:

 int n = 10;
 string s1 = "Ten: " + n.ToString();

This works for any object:

 DateTime dt = DateTime.Now;
 string s2 = "Date and time: " + dt;

This causes the DateTime.ToString method to be called, which results in a string that looks like:

Date and time: 9/16/2010 4:01:44 PM