by KodefuGuru
10. June 2009 12:00
Taking advantage of language features can make sleeker, easier to maintain code. One of these language features are array initializers.
Have you ever created an array, then assigned each element in the array? This incurs many lines of code with no tangible benefit. Check out this code from the NameMangler class in LINQ to XSD.
char[] splitters = new char[4];
splitters[0]='/';
splitters[1]='.';
splitters[2]=':';
splitters[3]='-';
string[] pieces = xsdNamespace.Split(splitters);
There are five lines of code that do nothing but initialize the array so it can be passed to a split operation. Here's how we can remove that mess.
string[] pieces = xsdNamespace.Split(new[] { '/', '.', ':', '-' });
We've gone down from 6 to 1 line without losing readability. The compiler sees that every element in the array declaration is a char, so it makes an array of char with the correct size. If you really wanted to keep the temporary variable splitters, you can assign the initialized array to it instead.
Now, imagine that you missed a splitter character and you have to edit the code. In the original piece of code you will need to increase the size of the array and add a new assignment. In the refactored version, you merely need to add a new element (e.g. , ';').