Search code examples
c#apiblazorwebassemblynullable

Nullable warning in Blazor in object List and API (controller) calling


I'm new in Blazor and I'm a little bit confused about warnings and nullable. If I declare a varible like this: List<Course> result = new List<Course>(); I get a warning in here: result = await ClientHttp.GetFromJsonAsync<List<Course>>("api/GetCourses");

But if I set the variable as nullable: List<Course>? result = new List<Course>(); The first warning dissapears but I get a new one: result.Remove(aux);

So, I can build with the warnings and I could hide them but I would like to know what is really happening and how control it.


Solution

  • When a variable is set to be nullable, it may occasionally become null. You need to check if the result is null before removing an item. If the result is null, a null exception will be thrown.

    result?.Remove(aux);