Resharper wanted me to change this code:
foreach (var item in cmbxColor1.Items)
{
cmbxColor2.Items.Add(item);
. . .
...because it said, "Possible 'System.NullReferencesException'"
So it should be this:
foreach (var item in cmbxColor1.Items)
{
if (null != cmbxColor2.Items)
{
cmbxColor2.Items.Add(item);
. . .
?
I don't get this - how could a combobox's Items be null, unless null == empty? And if null == empty, then that's exactly what they [s,w]ould be when this code is called.
I suppose Resharper is wrong here, as Items
collection of the ComboBox
seems to be initialized by its constructor. That is:
ComboBox c = new ComboBox();
c.Items.Add("1");
is guaranteed to be OK.
Also only get
accessor is available for us here so that no one could replace this collection with another (or null
). Though I am no quite sure, if there were a possibility to influence this collection while deriving from ComboBox
(I couldn't find smth at once), I guess even then it still remains guaranteed not null.
Null is not empty.
The Resharper team have done some automatic code analysis of many of the .NET classes to determine which methods and properties can return null. If Resharper claims that it can be null, that's probably because there is some way (perhaps obscure) that it could actually be null.
If you’re using an external library (e.g.
mscorlib.dll
), it doesn’t seem feasible to specify contracts for its entities using attributes. Enter External Annotations. This ReSharper feature allows you to complement the already compiled entities with attributes used by ReSharper’s analysis engine. External Annotations let you ‘cheat’ the engine, by making it see the attributes (for methods, parameters and other declarations) which weren’t declared at the time the library was compiled. To do this, the attributes must be specified in an XML file located in<ReSharper install directory>\Bin\ExternalAnnotations
.Such is the definition of contracts for standard libraries stored in this folder when ReSharper is installed. These contracts are obtained based on source code analysis as well as Microsoft Contracts. The contracts obtained using the former technique are stored in files of the type
*.Generated.xml
, while those obtained using the latter technique are stored in files of the type*.Contracts.xml
.
However I agree that it's not likely to be null
in practice. It could also be that Resharper is over cautious - proving whether something can ever be null or not is a hard problem. You can modify the annotations if you think the analysis is wrong and want to correct it.
Related
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