NullReferenceException while calling GetConstructor
Question)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();
Answer) Type typa = ass.GetType(“Abc”) should be fully qualified with namespace. eg:- ass.GetType(“TesterApp.Abc”)
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();
Answer) Type typa = ass.GetType(“Abc”) should be fully qualified with namespace. eg:- ass.GetType(“TesterApp.Abc”)
Comments