Programming

Stuff relating to the techie things I do for a living.
Dangerous Ideas in C# No. 1: A 'Better' Switch

Switch statements are rubbish. Only work on strings and numbers. Require an exact match value. Let’s abuse, oh, to pick a C# feature at random, collection initialisers, and use it to make them better! string switchValue = "house"; switch (switchValue) { case "hello": Console.WriteLine("Value was hello"); break; // But how can we handle, say, all other strings that start with h? default: Console.WriteLine("No match - Fallthrough"); break; } // here’s one way: new Switch<string>(switchValue) { { "hello",...

posted @ Friday, May 23, 2008 9:57 AM | Feedback (3)