Bookmark and Share

Int32 + String = String

This past weekend, we were throwing around C# trivia at a bar in Baton Rouge after SQL Saturday #28. Another speaker asked me one that he used in his session that day: what happens if you call Console.WriteLine(5 + “5”). I nonchalantly replied, “the number 55 written to the console.”

It really never occurred to me to attempt to add an int to a string, so I encountered this behavior in the context of something a little more bizarre: creating LINQ to Object. Here’s the extension method I used.

public static TResult SelectMany<TSource, TCollection, TResult>(this TSource source, 
    Func<TSource, TCollection> collectionSelector, 
Func<TSource, TCollection, TResult> resultSelector) { return resultSelector(source, collectionSelector(source)); }

There’s nothing particularly special about this extension method, but it allows you to combine two objects in a query expression. My first test was with types of the same kind.

[TestMethod]
public void SelectMany()
{
    var result = from x in 2
                 from y in 3
                 select x + y;

    Assert.AreEqual(5, result);
}

I know, that’s a really long-hand way to write 2 + 3. However, it proved that the SelectMany extension method worked. I then attempted it with an integer and a double. By all the rules, it should return a double.

[TestMethod]
public void SelectManyDifferentTypes()
{
    var result = from x in 2
                 from y in 3.1
                 select x + y;

    Assert.AreEqual(5.1, result);
}

Again, this was worked as I thought it would. But as I played with modifying the test to do an integer and a string, I noticed that it still compiled without any modifications to the select clause. Here’s the final test.

[TestMethod]
public void SelectManyIntAndString()
{
    var result = from x in 4
                 from y in "2"
                 select x + y;

    Assert.AreEqual("42", result);
}

I was dumbfounded. Was the act of passing the types through functions working magic with the types? I had to test it out on straight code to find out.

[TestMethod]
public void IntAndString()
{
    var result = 4 + "2";

    Assert.AreEqual("42", result);
}

There is no magic, unless you believe the compiler is a mystical force that binds all your code together. This is one of the compiler rules I had not encountered simply because it never occurred to me to add an int and a string together. I was expecting a type mismatch, but I missed one simple rule about strings buried deep in the C# specifications.

Whenever you use the + operator with a string, a string concatenation is performed. With a type that isn’t a string, this ends up calling String.Concat(object, object), which will use the ToString method of the object. If the parameter is null, String.Empty is used. You know all those places where you see “Hello “ + World.ToString() + “!!!”; completely unnecessary call to ToString().

Just because you know this works doesn’t mean you should do it. Readability of code is more important that doing tricks with strings. I would recommend calling ToString() when concatenating, prefering String.Format over concatenation, and using StringBuilder with large amounts of strings. But hey, it makes a great trivia question.

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
Telerik Developer Evangelist, C# MVP

JustCode

Telerik .NET Ninja

 

INETA Community Speakers Program

 

MVP - Visual C#

 

Friend of RedGate

World Map

Tag cloud

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.