Skip to main content
edited tags
Link
mxscho
  • 2.2k
  • 2
  • 18
  • 29
Source Link
mxscho
  • 2.2k
  • 2
  • 18
  • 29

Use of C# 8 null-forgiving operator within C# 6 index initializers

When using an index initializer to fill a dictionary without recreating it before that, is there an option to specify the null-forgiving operator somewhere?

Example:

public class Program
{
    public IDictionary<string, string>? NullableDictionary { get; set; }
       = new Dictionary<string, string>();

    public static void Main(string[] args)
    {
        new Program
        {
            NullableDictionary =
            {
                ["key"] = "value"
            }
        };
    }
}

I know that this use case (without recreating a new Dictionary<string, string> before index initialization { [...] = ... }) is probably not very common. But I am still wondering whether there is a solution to prevent this compiler warning for the above case:

[CS8602] Dereference of a possibly null reference.

I could imagine using the null-forgiving operator like this:

new Program
{
    NullableDictionary! =
    {
        ["key"] = "value"
    }
};