C
C#10mo ago
Falco

How to get rid of nullable warning?

What are the usual ways to get rid of these warnings? Do I have to check if everything is null before doing something? That would mean I would have to add a lot of if statements all the time which I hope could be prevented
No description
7 Replies
Monsieur Wholesome
Do null checks and handle null cases Null coalescing operator Null conditional operator Null forgiving operator
becquerel
becquerel10mo ago
you can either do null-checks or assert that the relevant variable/field is never null with annotations if the compiler knows something can never be null (it's given a value in a constructor), it won't give you these warnings
Falco
FalcoOP10mo ago
So I have this code where I get data from an api which is nested in some objects I can retrieve it using: weatherData.Hourly.Time So this is a nested object but if I want the time value, I cannot just check if weatherData is null. I also have to check if weatherData.Hourly is null. But then my code ends up like this
if (weatherData != null) {
if (weatherData.Hourly != null) {
if (weatherData.Hourly.Time != null) { }
}
if (weatherData != null) {
if (weatherData.Hourly != null) {
if (weatherData.Hourly.Time != null) { }
}
Some nested if statements just to check if each object is not null I dont like that solution Any other options?
Monsieur Wholesome
if(weatherData?.Hourly?.Time is not null) // or "!= null"
{

}
if(weatherData?.Hourly?.Time is not null) // or "!= null"
{

}
if you are specifically wanting Time, you could also do
if(weatherData?.Hourly?.Time is { } time)
{
// time is now a variable that was assigned from weatherData.Hourly.Time if none of them was null, and you can use it without typing it all out
}
if(weatherData?.Hourly?.Time is { } time)
{
// time is now a variable that was assigned from weatherData.Hourly.Time if none of them was null, and you can use it without typing it all out
}
Falco
FalcoOP10mo ago
class ApiManager
{
public async Task<T?> ApiRequest<T>(string apiUrl, string apiKey = "")
{
using (var client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync(apiUrl);

if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();

T model = JsonConvert.DeserializeObject<T>(responseBody);
return model;
}
else
{
Console.WriteLine($"Failed to make request. Status code: {response.StatusCode}");
return default; // Return default value for type T
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
return default; // Return default value for type T
}
}
}
}
class ApiManager
{
public async Task<T?> ApiRequest<T>(string apiUrl, string apiKey = "")
{
using (var client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync(apiUrl);

if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();

T model = JsonConvert.DeserializeObject<T>(responseBody);
return model;
}
else
{
Console.WriteLine($"Failed to make request. Status code: {response.StatusCode}");
return default; // Return default value for type T
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
return default; // Return default value for type T
}
}
}
}
I have the same issue for this line T model = JsonConvert.DeserializeObject<T>(responseBody); Using a if function to check if responsebody is null does not seem to work
leowest
leowest10mo ago
Use System.Text.Json instead...
public async Task<T?> ApiRequest<T>(string apiUrl, string apiKey = "")
{
try
{
return await client.GetFromJsonAsync<T>(apiUrl);
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
return default;
}
}
public async Task<T?> ApiRequest<T>(string apiUrl, string apiKey = "")
{
try
{
return await client.GetFromJsonAsync<T>(apiUrl);
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
return default;
}
}
You may also consider using httpfactory instead to avoid exhaustion problems with using + httpclient
MODiX
MODiX10mo ago
Make HTTP requests using IHttpClientFactory in ASP.NET Core
Learn about using the IHttpClientFactory interface to manage logical HttpClient instances in ASP.NET Core.
Use IHttpClientFactory to implement resilient HTTP requests - .NET
Learn how to use IHttpClientFactory, available since .NET Core 2.1, for creating HttpClient instances, making it easy for you to use it in your applications.

Did you find this page helpful?