in4man
in4man

Reputation: 23

NullReference Exception unhandled. C# Reflection

ControlType = "System.Windows.Forms.WindowsFormsApplication1." + "PictureBox1";
System.Reflection.Assembly asm;
asm = typeof(Form).Assembly;
ControlObject = (System.Windows.Forms.Control)asm.CreateInstance(ControlType);
ControlObject.Name = ControlName;

The next code generated following exception for me:

ControlObject.Name = ControlName;

NullReferenceException was unhandle Object reference not set to an instance of an object.

Upvotes: 0

Views: 417

Answers (5)

jason
jason

Reputation: 241583

Assembly.CreateInstance is expecting a type name and you appear to be passing it the name of an instance of a type (namely, a PictureBox named PictureBox1.). Therefore, ControlObject is null and thus ControlObject.Name will throw a NullReferenceException.

It's not clear what you're trying to do, but that is why you are encountering the problem that you are. If you're trying to create a new instance of PictureBox I don't see why you don't just say new PictureBox(); this class has a public parameterless constructor. Alternatively, if you insist on reflection, you could say

controlType = PictureBox1.GetType();
controlObject = Activator.CreateInstance<Control>(controlType);

We could help more if we knew what you were trying to do instead of just throwing code that doesn't work at us and expecting us to solve world hunger.

Additionally,

ControlType = "System.Windows.Forms.WindowsFormsApplication1." + "PictureBox1";
  1. Please rename this variable to controlType. You should use camel case for variable names.

  2. Why do you have your application class WindowsFormsApplication1 living in the system namespace System.Windows.Forms? Don't do this.

Upvotes: 4

Edgar Hernandez
Edgar Hernandez

Reputation: 4030

It means that asm.CreateInstance(ControlType); is returning null.

So, ControlType has a wrong value. It is supposed to recieve as parameter a type http://msdn.microsoft.com/en-us/library/dex1ss7c.aspx and it seems that you are sending an instance PictureBox1.

It should be ControlType = "System.Windows.Forms.PictureBox";

Upvotes: 0

SLaks
SLaks

Reputation: 887225

You're probably trying to write

ControlObject = new PictureBox();

Upvotes: 1

Jakub Konecki
Jakub Konecki

Reputation: 46008

Surly your application is not in System.Windows.Forms namespace

"System.Windows.Forms.WindowsFormsApplication1." + "PictureBox1"

Try:

ControlObject = (System.Windows.Forms.Control)asm.CreateInstance(typeof(PictureBox));

or just

ControlObject = new PictureBox();

to create a new instance of control.

Or maybe you want to find an existing PictureBox control on your form?

Upvotes: 0

Etienne de Martel
Etienne de Martel

Reputation: 36852

Looks like CreateInstance returns null, which means the type wasn't found in the assembly. Is PictureBox1 a type or an object?

Upvotes: 0

Related Questions