Miguel Moura
Miguel Moura

Reputation: 39404

Possible null reference argument ... when using <Nullable>enable</Nullable> in Net 6

Using Net6 with <Nullable>enable</Nullable>in project definition I have

public class Options {
  public Dictionary<String, String> Accounts { get; set; } = new Dictionary<String, String>();
}

Options options = new Options();

List<KeyValuePair<String, String>> parameters = new List<KeyValuePair<String, String>>();

parameters.Add(new KeyValuePair<String, String>("doc", options?.Accounts["doc"]));

I am getting the error `Possible null reference argument for parameter 'value' in:

options?.Accounts["doc"];

I could use the following:

if (options.Accounts.ContainsKey("doc"))
  parameters..Add(new KeyValuePair<String, String>("to", options?.Accounts["doc"]!));

I added the if statement and the ! ...

Is there another way to solve this without using the if statement?

Upvotes: 0

Views: 2370

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500893

Assuming that you want the value to be potentially null - it definitely will be null if options is null1 - you should change the corresponding type argument to be nullable:

List<KeyValuePair<String, String?>> parameters =
    new List<KeyValuePair<String, String?>>();

parameters.Add(new KeyValuePair<String, String?>("doc", options?.Accounts["doc"]));

The compiler is basically helping you here - anyone consuming parameters could previously have assumed that the value part of each pair was non-null, given that it was a KeyValuePair<string, string>. With the new code, they'll be forced/encouraged to handle null values.


1 I'm assuming that in the real code, options is obtained elsewhere and might be null. If you're really assigning options a definitely-not-null value, you should just use options.Accounts["doc"].

Upvotes: 5

Related Questions