Ok, so I’m sure most MS .Net dev’s have already seen these posts far too many times, for the Mono users out there, I have a little treat. While Moonlight and WPF get tons of hype, I think the biggest and most exciting change coming soon to a C# compiler near you is support for lambda expressions, anonymous types, and extension methods.
Now on the whole this doesn’t sound all that exciting, I mean, before a few months ago, I had never really used lambda expressions to accomplish much beyond pass that unit in an intro to CS class. Individually, there’s nothing to jump for joy about, but when used in conjunction, we can produce startlingly clean and readable code.
To demonstrate this I’ve whipped up two examples that I was fiddling with as I read a million tutorials. They aren’t fancy XML or Database providers, just some simple (and quite common in my experience) text parsing tasks that have disproportionately complex code. We will use some of the new C# 3.0 features to make far cleaner and more readable code.
The first example is an exclusion string, or a set of characters that are not allowed in another.
var illegalchars = "abcdefg";
string testString1 = "Kevin";
string testString2 = "hijkmlppp";
The ‘old’ way of checking both strings for one of the illegal chars:
foreach (char c in illegalchars) {
if (testString1.Contains(c) || testString2.Contains(c))
Console.WriteLine("illegal char!");
}
Using awesome new stuff:
if (testString1.Intersect(illegalchars).Any()
|| testString2.Intersect(illegalchars).Any())
Console.WriteLine("Linq found it too");
Our next example is ‘exploding’ or splitting a series of values out of a string (CSV and PSV are common examples of this) into an array:
string pipeDelined = "Kevin | McCool | Kubasik";
An old solution might have been (I know we could optimize this, or clean it up, just making a point
):
List<string> names = new List<string>();
foreach (string s in pipeDelined.Split(‘|’)) {
var ts = s.Trim();
if (ts == "") continue;
names.Add(ts);
}
var allNames = names.ToArray();
Using our cool new C# 3.0 tools, we can change this to the super-sexy:
var allLinqNames = pipeDelined.Split(‘|’)
.Select(s => s.Trim())
.Where(s => s != "")
.ToArray();
While a hardened child of OOP (via C# and Java) might baulk at the new syntax, I think that it can quickly start to grow on a developer. Moreover, it has the distinct advantage of being unambiguous, and makes reading someone else’s dense code much more fluid.
I really can’t wait for C# 3.0, and not for those flashy API’s, just the simple syntactical sugar that is already making me lazier by the minute.