Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReSharper shows possible null assignment on Value for generic Collection

I'm using a Dictionary<string, string> and add an item with a null value (in my real situation it's a variable).

var testDictionary = new Dictionary<string, string>();
testDictionary.Add("Test", null);

This leads to warning “Possible 'null' assignment to entity marked with 'NotNull' attribute”. Possible 'null' assignment

If I let ReSharper convert it to a Collection Initializer, it doesn’t show any warnings.

var testDictionary = new Dictionary<string, string> {{"Test", null}};

So, is it true that the Value of a Dictionary is marked with ‘NotNull’ attribute? Or is something else going on?

Edit: This question is not so much different from Resharper: Possible null assignment to entity marked with notnull attribute, but the answers on my question are different (it was a bug in R#, and adding null elements to a collection is not a good idea).

like image 353
comecme Avatar asked Jan 16 '23 22:01

comecme


2 Answers

In general it's a bad practice to put null elements into a collection. The overwhelming majority of code which consumes a collection assumes that values in the collection aren't null. If null is a valid collection element it really complicates all consumption code.

For example, you essentially need to write

foreach (var cur in theCollection) {
  if (cur.Value == null) {
    continue;
  }
  ...
}

For this specific case it simply looks like R# is missing the collection initializer case. It's definitely unexpected for null to be in a collection.

Instead of null why not use String.Empty?

like image 113
JaredPar Avatar answered Jan 22 '23 08:01

JaredPar


This was a bug, fixed in 6.0.

So yes, something else is going on - you need to upgrade your R# ;)

like image 44
AakashM Avatar answered Jan 22 '23 09:01

AakashM