0

I have been trying to create an array of multiple geofences.

example : geoFence001,geoFence002,geoFence001...........

i have tried doing it in the following ways:

Declare at the top

GeoFence[] myGeoFenceArray;

... then in my loop

geoFenceCounter++;

myGeoFenceArray[geoFenceCounter] = new GeoFence(geoFenceCounter.ToString(),Color.Blue);

Since that Didn't work i also tried the following :

Declare at the top

List<GeoFence> myGeoFenceList;

... then in my loop

geoFenceCounter++;

myGeoFenceList.Add  .....................

with both of these i get a nullException error.

any assistance would be greatly appreciated as if have been stuck on this for a few days now;

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
GeoSaffer
  • 143
  • 12

1 Answers1

2
List<GeoFence> myGeoFenceList;

The above line declares the variable, but doesn't initialize it and thus you get a NullReferenceException. You must initialize it like below before you can add to it.

List<GeoFence> myGeoFenceList = new List<GeoFence>();

On a side note, you can also take advantage of the var keyword in C#, so the code is less redundant and easier to change. The compiler can infer what the type of myGeoFenceList should be, so you don't lose any strong typing advantages.

var myGeoFenceList = new List<GeoFence>();
Community
  • 1
  • 1
mason
  • 31,774
  • 10
  • 77
  • 121
  • To add to mason's answer, the variable is "not initialized" because it is a reference type, not a value type. In fact, it really is initialized. All variables get initialized to default values automatically, but the default value for a reference type is always null. – Katie Kilian Jan 26 '15 at 16:17