✅ Dealing/resolving nullable warnings
I try to deal with nullable warnings among others e. g. CS8604 "Possible null reference argument for parameter."
I have the following sample code of a C# 7.0 worker service:
Is that so well solved that you always check for is not null?
I have the following sample code of a C# 7.0 worker service:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!PrerequisitesMet())
{
_logger.LogError("the options checked an is NULL");
throw new InvalidOperationException("prerequisites not met.");
}
while (!stoppingToken.IsCancellationRequested)
{
try
{
XDocument doc;
if (_options.ApiQueryURL is not null)
{
doc = await _httpService.GetXmlResponseAsync(_options.ApiQueryURL);
if (doc.Nodes().Any())
{
devices = GetDevices(doc);
await _dataService.UpdateDevicesAsync(devices);
}
}
}
catch (Exception ex)
{
if (OperatingSystem.IsWindows() && _eventLog != null)
{
_eventLog.WriteEntry($"Error occurred: {ex.Message}", EventLogEntryType.Error);
}
}
await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
}
}
private bool PrerequisitesMet()
{
// options
if (_options == null)
return false;
// option "ApiQueryURL"
if (string.IsNullOrWhiteSpace(_options.ApiQueryURL))
return false;
// option "TargetString"
if (string.IsNullOrWhiteSpace(_options.TargetString))
return false;
return true;
}protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!PrerequisitesMet())
{
_logger.LogError("the options checked an is NULL");
throw new InvalidOperationException("prerequisites not met.");
}
while (!stoppingToken.IsCancellationRequested)
{
try
{
XDocument doc;
if (_options.ApiQueryURL is not null)
{
doc = await _httpService.GetXmlResponseAsync(_options.ApiQueryURL);
if (doc.Nodes().Any())
{
devices = GetDevices(doc);
await _dataService.UpdateDevicesAsync(devices);
}
}
}
catch (Exception ex)
{
if (OperatingSystem.IsWindows() && _eventLog != null)
{
_eventLog.WriteEntry($"Error occurred: {ex.Message}", EventLogEntryType.Error);
}
}
await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
}
}
private bool PrerequisitesMet()
{
// options
if (_options == null)
return false;
// option "ApiQueryURL"
if (string.IsNullOrWhiteSpace(_options.ApiQueryURL))
return false;
// option "TargetString"
if (string.IsNullOrWhiteSpace(_options.TargetString))
return false;
return true;
}Is that so well solved that you always check for is not null?
