#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