tags:

views:

408

answers:

3

JetBrains ReSharper Issue

We have the following C# code where we are populating an imagelist from an image resource file. ReSharper is indicating "Possible "null" assignment to entity with "NotNull" attribute".

The issue would indicate to us that we simply need to check to ensure that our ResMan_Graphics is not null but when we put a check for null in place ... the issue remains.

Here is the code which generates the ReSharper issue;

ResourceManager ResMan_Graphics = new ResourceManager("_Graphics", Assembly.ReflectionOnlyLoad("lib"));
ImageList Icons = new ImageList();

Icons.Images.Add((Image)ResMan_Graphics.GetObject("ICON_Main"));

Has anybody come across this ReSharper comment before and do you have any suggestions on how we can populate an imageList from resource without producing this problem.

NOTE: If we place an imageList component onto a form and then populate the imageList from a resource in code, ReSharper does not produce the comment.

A: 

So you've tried:

if( ResMan_Graphics != null ) {
  Icons.Images.Add((Image)ResMan_Graphics.GetObject("ICON_Main"));
}
Ryan Emerle
+7  A: 

It's because GetObject might return null. You want to do this:

Image image = (Image)ResMan_Graphics.GetObject("ICON_Main");
if (image != null)
    Icons.Images.Add(image);
Roger Lipscombe
excellent ... that works. the intermediate step of casting it to an Image and then checking that Image for null.Thanks for your quick reply!
+1  A: 

ReSharper should be able to work out that ResMan_Graphics isn't null - you've just called a constructor. However, it's possible that GetObject will return null - I expect is what it's complaining about.

Is it the last line that is at fault? It sounds like you could do:

Image image = (Image) ResMan_Graphics.GetObject("ICON_Main");
if (image == null)
{
    // Throw some nasty exception
}
Icons.Images.Add(image);
Jon Skeet