May 2008 Entries

Dangerous Ideas in C# No. 2: Yielding to the Inevitable

C# 2.0 brought us the new 'yield' keyword. In a method or property that has an IEnumerable return type, yield return allows us to procedurally generate the values that will be provided by the resulting enumerator - such a method or property being known as an iterator. The assumption behind most uses of yield return is generally that someone will take the IEnumerable C# gins up for us and stick it in a foreach loop (potentially, in a LINQ world, after applying some query operators that filter or transform our yielded values first). But ultimately that foreach loop will...

posted @ Wednesday, May 28, 2008 9:22 PM | Feedback (2)

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)