Home > Back-end >  ToDictionary() returns a nullable dictionary
ToDictionary() returns a nullable dictionary

Time:10-16

I'm trying to create a dictionary from the IdentityResult Errors property which is an IEnumerable<IdentityError> like so:

var dictionary = result.Errors.ToDictionary(e => e.Code, e => e.Description);

For some reason dictionary is now a Dictionary<string,string>? I would like this to be Dictionary<string,string> (not nullable). Am I doing something stupidly here?

CodePudding user response:

From the documentation Declaration statements :

When var is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable.

ToDictionary return a non nullable reference, but with var the variable is considered as nullable reference.

If you want force the variable to be non nullable reference, you need to declare the variable's type explicitly :

Dictionary<string, string> dictionary = result.Errors.ToDictionary(e => e.Code, e => e.Description);

But it's rarely necessary. Even if the variable is nullable, if null is never affected in the variable, then the compiler don't warn if the variable isn't checked before to be used.

var dictionary = result.Errors.ToDictionary(e => e.Code, e => e.Description);
var type = dictionary.GetType(); //No warning
var dictionary = result.Errors.ToDictionary(e => e.Code, e => e.Description);
dic = null;
var type = dictionary.GetType(); //Warning CS8602 Dereference of a possibly null reference.
  • Related