logeeks
logeeks

Reputation: 4979

exception while calling GetConstructor

I am trying to construct the following class' instance via reflection.

public class Abc
{
    private int _a;
    public Abc(int a)
    {
        _a = a;
    }


    public void Show()
    {
        MessageBox.Show(_a.ToString());
    }

}

I am using the following snippet to get the constructor of the class, However i am getting an 'Object reference not set to an instance of an object' exception when the code reaches ConstructorInfo csInfo = typa.GetConstructor(types); I've checked msdn and found that such an exception occurs when any of the elements of Type[] types are null. I debugged and found that all elements have valid value. Can you please help me find the actual problem?

Assembly ass = Assembly.GetExecutingAssembly();
Type typa = ass.GetType("Abc");
Type[] types = new Type[1];
types[0] = typeof(int);

ConstructorInfo csInfo =typa.GetConstructor(types);
object [] obj = { 10 };

var AbcObj = csInfo.Invoke(obj) as Abc;

AbcObj.Show();

Thanks

Upvotes: 2

Views: 619

Answers (2)

HatSoft
HatSoft

Reputation: 11201

You need to pass the namespace along with the name of the type

Example

Type typa = ass.GetType("YourNamesPace.Abc");

Upvotes: 1

Varius
Varius

Reputation: 3407

I've compiled Your code (VS2010), this line causes null ref exception:

Type typa = ass.GetType("Abc");

typa is null. Thats because You need class name with namespace. for example:

Type typa = ass.GetType("ConsoleApplication1.Abc");

EDIT: Of course You will need a namespace only if Your class is in a namespace.

Upvotes: 4

Related Questions