ImageSourceConverter throws a NullReferenceException ... why?

c#, resources, wpf

Solution

Well you've got plenty of things which could be null in there. I suggest you separate them out:

Bitmap bitmap = coDrivr4.Properties.Resources.Music;
object source = new ImageSourceConverter().ConvertFrom(bitmap.GetHbitmap());
ImageSource imageSource = (ImageSource) source;
videoTile.Icon = imageSource;

Note the use of a cast rather than the `as` operator here. If `source` isn't an `ImageSource`, this will throw an `InvalidCastException` which will be much more descriptive than just ending up as a null reference.

EDIT: Okay, so now we know for sure that it's happening in `ConvertFrom`, I suggest the next step is to find out whether it's a bug in .NET 4.0 beta 1. Are you actually using any .NET 4.0 features? I suggest you try to extract just that bit of code into a separate project (you don't need to display an API, just convert the image. Try to run that code in .NET 3.5. If it fails in the same way, that's eliminated the beta-ness from the list of possible problems.

Problem

I've been tearing my hair out over this issue for the last hour or so. I have some code that goes like this: ``` videoTile.Icon = new ImageSourceConverter().ConvertFrom(coDrivr4.Properties.Resources.Music.GetHbitmap()) as ImageSource; ``` When I run my code, it says a NullReferenceException occurred. Neither 'Music' nor the return of GetHbitmap() are null. I'm trying to get the image via the Properties because it's the only way I've figured out how to access the images in my Resources folder. I would just add them to the app.xaml file as a resource, but I'm not using an app.xaml file for a few reasons. Am I attempting this wrong? All I need to do is get an ImageSource object of an image I have in my Resource directory. I can use them just fine in my XAML, but can't for the life of me do it in any code. P.S.: I can't just add them as a resource to the XAML file because this is just a class and so there is no XAML file.

Original source