Code Trivia #4

Got the inspiration for this one in a recent stackoverflow question.

What should the following code output and why?

class Program
{
    class Author
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public override string ToString()
        {
            return LastName + ", " + FirstName;
        }
    }

    static void Main()
    {
        Author[] authors = new[]
            {
                new Author { FirstName = "John", LastName = "Doe" },
                new Author { FirstName = "Jane", LastName="Doe" }
            };
        var line1 = String.Format("Authors: {0} and {1}", authors);
        Console.WriteLine(line1);

        string[] serial = new string[] { "AG27H", "6GHW9" };
        var line2 = String.Format("Serial: {0}-{1}", serial);
        Console.WriteLine(line2);

        int[] version = new int[] { 1, 0 };
        var line3 = String.Format("Version: {0}.{1}", version);
        Console.WriteLine(line3);
    }
}

Update:

The code will print the first two lines

// Authors: Doe, John and Doe, Jane
// Serial: AG27H-6GHW9

and then throw an exception on the third call to String.Format because array covariance is not supported in value types. Given this the third call of String.Format will not resolve to String.Format(string, params object[]), like the previous two, but to String.Format(string, object) which fails to provide the second argument for the specified format and will then cause the exception.

Advertisements

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 )

Google+ photo

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

Connecting to %s