How to correctly handle possible null values/converting null literals to non-nullable types in C#

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật