Monday , 24 April 2017
Home » Code You Should Not Be Writing – Part 6

Code You Should Not Be Writing – Part 6

I want to bring in the new year with this code that doesn’t seem all very harmful, but could be written in a more elegant way. I just hope this will educate people on some of the new functional additions to C#.

[sourcecode language=”csharp”] public List<int> GetListOfIntegers()
{
List<int> list = new List<int>();
for(int i = 0; i < 24; i++)
{
list.Add(i);
}
return list;
}
[/sourcecode]

At its very core essence, this is simply creating a list of numbers from 0 to 23. However, try to find out the various possibilities of mistakes one can make with this code. I’ll leave it as an exercise of the reader to figure out all the possibilities of mistakes in this code. (side note: In fact, there was an error made in the original code. Yes, it looks simple, yet error-prone.)

Here’s a simpler and elegant way to do something like the above.

[sourcecode language=”csharp”] public List<int> GetListOfIntegers()
{
Enumerable.Range(0, 24).ToList();
}
[/sourcecode]

One of the interesting things with Enumerable.Range is it returns an IEnumerable. This effectively generates the numbers lazily. However in this example, in order not to change the signature of the method, ToList() is called to generate the numbers instantly, instead of lazily.

With ranges, you can create various interesting sets of numbers with Linq in a more functional way. I hope this week’s “Code You Should Not Be Writing” helps someone out there.

About Justin Lee

Check Also

Samsung Galaxy Note7 – “Eye-ing” the Next Evolution in the Galaxy Note Series

The next generation Samsung Galaxy Note7 combines both style and innovative features and top of …

Leave a Reply