0

Still Arrays?

by volkanuzun 24. March 2009 17:48

     I am a moderator in one of the Turkish forums: ceviz.net. Although I can’t as much time as before, I am still checking the forum to see what difficulties people are facing. I can’t still believe that people are still using arrays in C#, and not surprisingly most of their problems are related with arrays too. I can’t think of 1 reason to use arrays (unless you are targeting clr 1.1 or some old function that requires array). They are not type safe, they are not dynamic, you have to reallocate space when it is full etc.

    I really want to know why not List<T> but still arrays? Is it the syntax that is scary? For example one of the members asked a question in the forum complaining about his application being crashed every time he runs his program. Here is his application:

   1:  string[] myArray = {"a","b","c"};
   2:  string[] wanted={};
   3:  Random rnd  = new Random();
   4:  int index = rnd.Next(0,3);
   5:  wanted[0] = myArray[index];

The problem with this small function is obvious, the programmer is assigning a value at line 5 to an array location that never been allocated. This type of bugs usually happen when you use array, and if you are really really lucky (or unit test your code and get a good code coverage), you will catch the bug quickly. As an answer to this question, i adviced him to use either new to allocated space, or use List which is a much better way. Here is the version with List<T>

   1:  List<string> myArray = new List<string>{"a","b","c"};
   2:  List<string>wanted = new List<string>();
   3:  Random rnd = new Random();
   4:  int index = rnd.Next(0,3);
   5:  wanted.Add(myArray[index]);

It is this simple but I am sure that in a few days, I will see another question in the forum complaining about a program crash smile_sad

Tags:

Comments are closed

Powered by BlogEngine.NET 1.6.0.0
Original Design by Laptop Geek, Adapted by onesoft