Code Trivia #4

Posted by João Angelo on Exceptional Code See other posts from Exceptional Code or by João Angelo
Published on Fri, 16 Jul 2010 11:00:26 +0000 Indexed on 2010/12/06 16:59 UTC
Read the original article Hit count: 512

Filed under:
|
|

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.


© Exceptional Code or respective owner

Related posts about .NET

Related posts about c#