-2

I don't know HOW I did it, but it isn't work. There is a simple for-loop which throws NullReferenceException

https://i.stack.imgur.com/yJe2i.png

Full code:

private static Hex[] maps = new Hex[]
{
    // a bunch of ~40 items
};

private static void Main(string[] args)
{
    List<MapItem> items = new List<MapItem>();

    for (int i = 0; i < maps.Length; i++) //here's an exception is threw. Debugger on this step shows that maps contains ~40 items
    {
        var response = httpClient.GetAsync($"https://war-service-live.foxholeservices.com/api/worldconquest/maps/{maps[i].Name}/dynamic/public").GetAwaiter().GetResult();
        var data = JsonSerializer.Deserialize<MapRegion>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());

        for (int j = 0; j < data.mapItems.Count; j++)
        {
            if (new int[] { 45, 46, 47, 56, 57, 58 }.Contains(data.mapItems[j].iconType))
            {
                Console.WriteLine($"{maps[i].Title} - X: {data.mapItems[j].x} | Y: {data.mapItems[j].y}");
                string s = Console.ReadLine();
                data.mapItems[j].Name = s;
                data.mapItems[j].regionName = maps[i].Name;
                items.Add(data.mapItems[j]);
            }
        }
    }
    // some actions
}

Any ideas?

  • Can you post `some actions`? What you posted wont lead to a null ref exception. – Loocid May 22 '22 at 23:56
  • question edited – mycatlikesmilk May 23 '22 at 00:00
  • The exception is thrown before even entering the loop, or what is the value of `i`? – Lance U. Matthews May 23 '22 at 00:01
  • Why are you using async calls without await? You can make Main async. As for the null reference where is `maps` initialized? – juharr May 23 '22 at 00:03
  • when I use async/await it is still exception. value of i is 0. It is initialized in loop – mycatlikesmilk May 23 '22 at 00:09
  • 3
    @mycatlikesmilk now would be a good time to start stripping out code to the minimal amount possible to reproduce the error. Right now you have too much extraneous code for others to be able to try out easily. This will result in one of two outcomes: 1) you figure out which line of code you remove caused the problem, or 2) It's sufficiently simplified for others to be able to easily reproduce. – Kirk Woll May 23 '22 at 00:30
  • use debugger to step through the code, and hover over all variable/properties to see which is null. – Stewart May 23 '22 at 00:51
  • That same old canonical question doesn't seem so helpful here because we have a screenshot of the debugger showing that the only reference that could be `null` and cause that exception...isn't. – Lance U. Matthews May 23 '22 at 20:11
  • Until Kirk's comment is resolved, this post should stay closed as (what _I_ voted for) "needs debugging information". The posted code [doesn't line up with](https://dotnetfiddle.net/kdg4E1) the screenshot. – gunr2171 May 23 '22 at 21:40

0 Answers0