Thursday, June 12, 2008

C# Puzzle No.1 (level: beginner)

Would you like to see a collection which magically creates an item as soon as you ask for it? Well, here it is. The collection is asked to return a value for a key, and volia, you will be informed that the item exists in the collection.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main( string[] args )
        {
            NameValueCollection Collection = new NameValueCollection();
 
            Console.WriteLine( 
                "Does NameValueCollection magically create items? " +
                Collection["foo"] != null ? " Yes, it does!" : "No, it doesn't." 
                );
        }
    }
}

Can you spot the problem in the code?

1 comment:

apl said...

The + operator has higher precedence that the ?: operator, therefore the result of Collection["foo"] is first concatenated with the "Does NameValueCollection magically create items? " string and then compared to null.