'I can't seem to test for a null in this c# Unity script

I have a Unity App that is using c#.

I am getting a NullReferenceException: Object reference not set to an instance of an object on the line:

WeatherDict.Add(WeatherTypes[i].WeatherId, new List<WeatherMaps>());

for WeatherTypes[i].WeatherId

I am trying to check for null by using string.IsNullOrWhiteSpace as you can see.

for (int i = 0; i < WeatherTypes.Length; i++)
{
    if (!string.IsNullOrWhiteSpace(WeatherTypes[i].WeatherId))
    {
        if (!WeatherDict.ContainsKey(WeatherTypes[i].WeatherId))
        {
            WeatherDict.Add(WeatherTypes[i].WeatherId, new List<WeatherMaps>());
        }
    }
}

I also tried this:

if (WeatherTypes[i].WeatherId != null || WeatherTypes[i].WeatherId != "")

But that still throws the same exception.

Is there another way to check for null?

Thanks!



Solution 1:[1]

If Weathertypes is null, the following code will cause a null reference exception:

if (WeatherTypes[i].WeatherId != null || WeatherTypes[i].WeatherId != "")

A safer approach looks like this.

if (WeatherTypes == null || WeatherTypes[i] == null)

You should learn to use the debugger. It will allow you to step through the code and look and see exactly what is null.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonathan Wood