-1

I tried to write a shuffle string array algo but I get a null reference error.. I can't figure out why..

public static string[] arrRandomized;
public static string[] ShuffleWords(string[] Words)
{
    Random generator = new Random();
    for (int i=0;i < Words.Length; i++) {
        int pos = generator.Next(Words.Length);
        Console.WriteLine(Words[pos]); // I SEE RANDOM ITEM
        Console.Read(); // NULL REFERENCE ERROR AFTER THIS
        if (Words[pos] != null)
        {
            arrRandomized[i] = Words[pos];
            //remove item at pos so I get no duplicates
            Words[pos] = null;
        }
    }

I don't want to use ArrayList, i have my reasons but thats off topic I just want to know how come this isn't working :/ thanks

ace007
  • 577
  • 1
  • 10
  • 20

2 Answers2

3

I think you should initialize arrRandomized:

arrRandomized = new string[Words.Length];
Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
0

Your arrRandomized is never intialized. I would also recommend that you return an array rather then use a static reference because the subsequent calls to the method will change all references to the arrRandomized.

public static string[] ShuffleWords(string[] Words)
{    
    string[] arrRandomized = new string[Words.Length];
    Random generator = new Random();
    for (int i=0;i < Words.Length; i++) 
    {
        int pos = generator.Next(Words.Length);
        Console.WriteLine(Words[pos]); // I SEE RANDOM ITEM
        Console.Read(); // NULL REFERENCE ERROR AFTER THIS
        if (Words[pos] != null)
        {
            arrRandomized[i] = Words[pos];
            //remove item at pos so I get no duplicates
            Words[pos] = null;
        }
    }
    return arrRandomized;
}
Brad Semrad
  • 1,501
  • 1
  • 11
  • 19
  • got ridd of the error, but now the return array only has 2 items instead of 4.. the other 2 are there but empty :/ – ace007 Nov 10 '12 at 18:52