Refactor to Array Initializer

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. , ';').

Tags: ,

Kodefu

Comments

6/10/2009 1:40:46 PM #

trackback

Trackback from DotNetKicks.com

Refactor to Array Initializer

DotNetKicks.com

6/10/2009 1:42:38 PM #

trackback

Trackback from DotNetShoutout

Refactor to Array Initializer

DotNetShoutout

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen

Whois KodefuGuru

Chris Eargle

Chris Eargle
.NET Community Champion

LinkedIn Twitter Technorati Facebook

MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er


World Map

RecentComments

Comment RSS

Tag cloud

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010