I’m currently interning as a .NET developer this summer, and it’s my first-time diving into the wonderful world of C#. I quite frequently run into the following warnings when working on a project:
Converting null literal or possible null value to non-nullable type
As an example, here is a section of code I have written for parsing a configuration file.
private List<string> ParseConfiguration(IConfiguration configuration)
{
// Attempt to parse configuration file and load connection data into a list.
// Will be used to build out connection string later.
try
{
List<string>? configurationInfo = configuration.GetSection("connection_info").Get<List<string>>();
// Check to make sure configurationInfo is not null, as we have made
// the list nullable earlier.
if (configurationInfo == null)
{
throw new NoNullAllowedException();
}
return configurationInfo;
}
catch (Exception ex)
{
// Error re-thrown for Event Log. Outputting to console for
// debugging purposes only.
Console.WriteLine($"Error occurred attempting to parse configuration file.n" +
$"{ex.Message}");
throw;
}
}
On the first line after the try block, I’m attempting to pull data from a configuration file into a non-nullable type of List<string>
. However, the configuration could be null
, which causes a warning to occur.
Clearly, I have remedied the warning by appending a question mark after the List<string>
, which makes the object nullable, and therefore removes the warning.
However, this doesn’t seem very safe for reason. Is there a better (safer) way of dealing with these warnings? I’d like to know what industry professionals do! Does it just involve if ()
statements to check the object’s state?
3
Why isn’t it “safe”? The method can return null
so you must check for such a condition and handle it appropriately. The compiler knows the var is not null after the null check handles the null condition and terminates which is why it doesn’t complain that you’re returning a nullable string.
You can use the null coalescing operator to throw an exception which would then also allow your variable declaration to not be a nullable type.
List<string> configurationInfo = configuration.GetSection("connection_info")
.Get<List<string>>()
?? throw new NoNullAllowedException(); // this should include a description of what was null such as "config section connection_info"
You can throw instantly when Get
returned null.
List<string> configurationInfo = configuration.GetSection("connection_info").Get<List<string>>() ?? throw new NoNullAllowedException();
This way configurationInfo
is kept as not-nullable.
The default implmentation of Get<List<string>>()
returns default(List<string>)
which would be null.
Below is just opinion:
Personally, I usually do .Get<List<string>?>()
when dealing with configurations, even if the type is nullable already. This way I can clarify the returned value can be null (not found), and deal with such case, thus making code reading easier.