Home > Blockchain >  I have lots of checks but I am still getting this null error
I have lots of checks but I am still getting this null error

Time:04-12

I am using both Unity and Visual Studio to manage a web site that uses Unity and c#.

I have a world map that loads fine, but displays this error in the browser console:

 ArgumentNullException: Value cannot be null.
Parameter name: key

So I loaded up Unity, to see if I could find any errors and I see one for a file called MapDisplay.cs.

Looking at the error, I am assuming it has something to do with a dictionary object.

In that code file, there is indeed one dictionary object.

However, it looks like the code is checking for anything that may be null.

So I am not sure how much more I can check?

Is there a more efficient way to check for null values in a dictionary so that the error doesn't display?

Here is the code for the dictionary object:

public Dictionary<string, MapController> MapDictionary;
MapController mapController = CreateMapController(mapData);

if (mapController != null)
{
    if (mapController.MapId != null || mapController.MapId != "")
    {
        string mapControllerId = mapController.MapId;

        if (!MapDictionary.ContainsKey(mapControllerId))
        {
            MapDictionary.Add(mapControllerId, mapController);
        }
    }
}

Thanks!

CodePudding user response:

Aside from the if condition issue discussed in the comments.

You can use (?.) optional chaining to deal that the mapController is possibly null.

With .NET Core, you can use Dictionary<TKey,TValue>.TryAdd(TKey, TValue) Method.

string mapControllerId = mapController?.MapId;

if (!String.IsNullOrEmpty(mapControllerId))
{
    MapDictionary.TryAdd(mapControllerId, mapController);
}

If not, you can write a Dictionary extension method for TryAdd to deal with.

public static class DictionaryExtensions
{
    public static bool TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue @value)
    {
        try
        {
            dict.Add(key, @value);
            return true;
        }
        catch
        {
            return false;
        }
    }
}
  • Related