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”.
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).
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
?
This was a bug, fixed in 6.0.
So yes, something else is going on - you need to upgrade your R# ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With