0

I have a simple helper class:

class WebsiteStatus
{
    public string siteName { get; set; }
    public Nullable<DateTime> lastDownTime { get; set; }
}

I make an array of the class based on the number of sites being evaluated:

string URLs = "http://www.qqq.com;http://www.rrr.com;http://www.ttt.com;";
string[] sites = URLs.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
WebsiteStatus[] siteArray = new WebsiteStatus[sites.Count()];

When I try to input data into one of the objects in the array I'm getting a null exception error:

siteArray[0].siteName = sites[0];

enter image description here

I don't understand why this is happening. What am I doing wrong?

David Tunnell
  • 7,252
  • 20
  • 66
  • 124
  • siteArray[0] is null – Sievajet Feb 16 '15 at 20:40
  • 1
    _When I try to input data into one of the objects in the array_ That's your problem. There are no objects in that array – Steve Feb 16 '15 at 20:41
  • 1
    It's not initialized. You've just created the array but not the object inside. I guess you miss the siteArray[0] = new WebsiteStatus(); – Ofir Winegarten Feb 16 '15 at 20:42
  • 1
    You have initialized the array here: `WebsiteStatus[] siteArray = new WebsiteStatus[sites.Count()];` So it is initialized and not `null`, it is even correctly sized. But all elements are `null`, there is not even one `WebsiteStatus` inside. So you have to add them before you access them. – Tim Schmelter Feb 16 '15 at 20:44

2 Answers2

1

siteArray[0] is null, so attempting to access siteName on that object is always going to return a NullReferenceException. You created the array, but didn't add any elements to it.

Jon La Marr
  • 1,358
  • 11
  • 14
1

You have to use this instead:

siteArray[0] = new WebsiteStatus { siteName = sites[0], lastDownTime = null };

The array of WebsiteStatus objects may have been initialized, but neither of the separate WebsiteStatus objects has been instantiated.

Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98