Whidbey Readiness Quiz (Answer): Converting array values

Well, lots of good responses… I can see this is going to be a hard group to stump. Nat nailed all the points quickly, even if it took him two posts to do it ;-)… there were several other great responses as well.

 

Here is the code I came up with… I wanted to high light three things:

  1. The “funcational” methods on Array… You can do some neat stuff with ConvertAll, ForEach and friends with C# new annonoums method support… give them a whirle and see what cool thigs you can come up with.
  2. TryParse()… It allows you to avoid catching and eating exceptions… bad programming practices and bad perf. If you find your self doing anything like this today you will love TryParse:
      int i;

        try

        {

            i = Int32.Parse("42");

        }

        catch (FormatException)

        {

            i = -1;

        }

  1. Of couse, I have to plug a bit of Color console… you can’t do a reasonable whidbey CLR demo without it ;-)

using System;

class Program

{

    static void Main(string[] args)

    {

        string[] inputValues = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "bad value" };

        int[] outputValues;

        outputValues = Array.ConvertAll<string, int>(inputValues, delegate(string value)

        {

    int i;

            if (!Int32.TryParse(value, out i)) return -1;

            return i;

        });

        Array.ForEach<int>(outputValues, delegate(int value)

        {

            if (value % 2 == 0) Console.ForegroundColor = ConsoleColor.Red;

  else Console.ForegroundColor = ConsoleColor.White;

            Console.Write(value + ",");

        });

        Console.ReadLine();

    }

}