开发者

NullReferenceException with an Array in C#

I want to create an array containing all the Pushpin objects I am dealing with. While trying to populate the Array, I am getting a NullReferenceException Unhandled error thrown. I 开发者_StackOverflow中文版have read as much documentation as I can find and cannot work out what is going on.

I have tried at least the following:

Pushpin[] arrayPushpins;
int i = 0;
foreach (Result result in arrayResults)
                {
                    Pushpin pin;
                    pin = new Pushpin();
                    pin.Location = d;
                    myMap.Children.Add(pin);
                    arrayPushpins[i] = new Pushpin();
                    arrayPushpins.SetValue(pin, i);;
                    i++;
                }

AND...

Pushpin[] arrayPushpins;
int i = 0;
foreach (Result result in arrayResults)
                {
                    Pushpin pin;
                    pin = new Pushpin();
                    pin.Location = d;
                    myMap.Children.Add(pin);
                    arrayPushpins[i] = new Pushpin();
                    arrayPushpins[i] = pin;
                    i++;
                 }

And nothing seems to work... I get the NullReference error every time. Any ideas? Many thanks! Will.


The problem is that you don't initialize your array:

Pushpin[] arrayPushpins = new Pushpin[10]; // Creates array with 10 items

You might consider using IEnumerable<Pushpin> if you don't know the number of items in advance, e.g:

IEnumerable<Pushpin> pushpins = new List<Pushpin>


You didn't initialize the array

 Pushpin[] arrayPushpins = new Pushpin[/*number goes here*/];
    int i = 0;
    foreach (Result result in arrayResults)
                    {
                        Pushpin pin;
                        pin = new Pushpin();
                        pin.Location = d;
                        myMap.Children.Add(pin);
                        arrayPushpins[i] = new Pushpin();
                        arrayPushpins.SetValue(pin, i);;
                        i++;
                    }

Edited to add: I'd avoid using a raw array, and go with something like a List<Pushpin> instead


I think you should use a list instead of an array. That way, you won't have to know in advance how many elements will you have in your list.


In your code, the array is only declared, not initialized. You need to initialize it with the new keyword.

Pushpin [] arrayPushpins= new Pushpin[50]; 

As the other answers recommend, you can use lists or collections.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜