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

Time:11-17

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.

CodePudding user response:

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);

CodePudding user response:

Because you initialize result it is safe to use the 'null forgiving operator', !. Like this:

result = await ClientHttp.GetFromJsonAsync<List<Course>>("api/GetCourses")!;

If the Get fails it is up to uyour error handling.

In the rest of your code you can then use result. , without the ?.

  • Related