简体   繁体   中英

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 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, eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM