#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

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: