I'm using Visual Studio 2013 to create a Visual C# Windows Forms Application and I'm not using the Designer to setup the form.
I'm trying to use a Dictionary to store Bitmaps so that I can call them later by name. But when I debug the script I get the error:
An unhandled exception of type 'System.NullReferenceException' occurred in SimpleForm.exe
Additional information: Object reference not set to an instance of an object.
From the line:
width = imgLetters["a"].Width;
Any help would be greatly appreciated.
Cut down version of code which still produces the error:
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace SimpleForm
{
public class Test : Form
{
static Bitmap bmpLetterA;
static Bitmap bmpLetterB;
static Bitmap bmpLetterC;
private Dictionary<string, Bitmap> imgLetters;
public Test()
{
ImgInitialize();
ImgWidth();
}
private void ImgInitialize()
{
Dictionary<string, Bitmap> imgLetters;
bmpLetterA = new Bitmap("a.png");
bmpLetterB = new Bitmap("b.png");
bmpLetterC = new Bitmap("c.png");
imgLetters = new Dictionary<string, Bitmap>();
imgLetters.Add("a", bmpLetterA);
imgLetters.Add("b", bmpLetterB);
imgLetters.Add("c", bmpLetterC);
}
private void ImgWidth()
{
int width = 0;
width = imgLetters["a"].Width;
}
}
}
The problem is in your
ImgInitialize()
method.remove this Line
What you are doing is creating a local variable with the same name as your global variable. So it is this one that you are adding values to. This then lost when the method has completed due to its scope.
Your global variable is still null at this point and this is why the error occurs.
Friendly tip to prevent such mistakes in the future: when using a class member, append
this
:This way, even if you have local variable with the same name it won't interfere.
Remove the line
Dictionary<string, Bitmap> imgLetters;
fromImgInitialize
. This creates a local variable with the same name as the member variable. It is then filled, but never used, while the member variable remains uninitialized.Tipps for avoiding problems like this:
m_member
instead ofmember
).this.
to make clear which variable you want to access.The problems lies here:
This variable shadows the class's field
private Dictionary<string, Bitmap> imgLetters;
. Remove this declaration from the methodImgInitialize
and it'll work fine.