C
C#2mo ago
! 0Falco

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
Becquerel2mo 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
! 0Falco
! 0Falco2mo 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
}
! 0Falco
! 0Falco2mo 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
leowest2mo 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
MODiX2mo 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.
Want results from more Discord servers?
Add your server
More Posts
yo im tied to make a game and there is problomtile class using System.Collections; using System.Collections.Generic; using TMPro; using UnityEnginNetArchTests Not Detecting Project Referencesanyone here familiar with netarchtests? I am trying to enforce clean architecture, and for some reasTrying to make a "Distributed SQLite" in C# and gRPC/Protobuf - don't know what to do nextHello, for a project that I am required to do, I need to make a simple distributed database system dUnable to get all the azure ad groups details which logged in user is a part of.I'm using Azure AD login for an app to login with Microsoft credentials and get the groups (and theiTesting my UserEdit Api endpoint using swagger fails and throws a code 400 responseI am trying to use Swagger to test my api endpoints but i get a code 400 when i test them. ``` [HttNative bindings to MacOS ObjC classes?It's very easy to have C bindings in C# on both Windows and Linux, but I'm really struggling to knowHow to get Windows.Storage.ProviderGood afternoon, I'm trying to use the namespace Windows.Storage.Provider (https://learn.microsoft.codependency-injection-dotnet-coreHello. I know that this is an old example but it is very important to me to run this code (If you waAvalonia: how to get the data of a control where the sender belongs to?My program requires a drag-and-drop. when i move a 'part' rectangle into another 'raw material' rectHow do I do an inner GroupJoin on dotnet?I'm using .NET 6 with Entity Framework. This is my situation: I have a BenefitEntity (with Name and