-2

I have a C# method to convert from a list into an array. The code goes like this:

public String[] ConvertToArray(List<InstallationControl> list)
        {
            String[] Array = null;
            Int32 i = 0;
            foreach (var item in list)
            {
                Array[i] = item.Value.ToString();
                i++;
            }

            return Array;
        }

However, it's always giving me the Null exception. Can someone explain this to me?

user2701646
  • 139
  • 4
  • 4
  • 20
  • 7
    You're not initializing your array. String[] Array = new String[list.Count] – Michael Sep 23 '13 at 16:53
  • I think you should just use the `ToArray()` method... That or rewrite your loop to something that makes more sense, like a traditional for instead of a foreach with an index variable... Doesn't that just defeat the purpose of using foreach? Plus initialize your array to `list.Count()`. – evanmcdonnal Sep 23 '13 at 16:56

3 Answers3

4

You are not initializing the array you are trying to fill.

String[] Array = new String[list.Count]

Should solve your problem.

This will create an array of [list.Count] strings. You should be aware that each of those strings are null until you them assign a value.

MSDN Arrays

Michael
  • 1,803
  • 1
  • 17
  • 26
1

You need to initialize the array

String[] Array = new String[list.Count];

or simply

String[] Array =list.Select(x=>x.Value.ToString()).ToArray();
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

Change the line to initialize the array

String[] Array = new String[list.Count];

Should work

MichaC
  • 13,104
  • 2
  • 44
  • 56