Simple Reflection example give Exception

T

Tony Johansson

Hi!

This program is supposed to create these rows dynamically
Hashtable tbl new Hashtable();
tbl.Add("Hi","Hello");
int foo = tbl.Count;

Here I have a simple example that give exception when this row is being
executed
*ConstructorInfo ctor = hashType.GetConstructor(argumentTypes);*
the exception I get is the following when I translated from my native
language
"NullReferenceException was unhandled
the Objectreference has not been given to an instance of an object"

Is it anyone that might have an idea what I have to change ?

static void Main(string[] args)
{
string path =
@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll";
Assembly theAssembly = Assembly.LoadFile(path);

Type hashType = theAssembly.GetType("Hashtable");

Type[] argumentTypes = Type.EmptyTypes;
ConstructorInfo ctor = hashType.GetConstructor(argumentTypes);

object newHash = ctor.Invoke(new object[]{});

MethodInfo method = hashType.GetMethod("Add");
method.Invoke(newHash, new object[] { "Hi", "Hello" });

PropertyInfo property = hashType.GetProperty("Count");
int count = (int)property.GetValue(newHash, null);
}

//Tony
 
W

Willem van Rumpt

Hi!

This program is supposed to create these rows dynamically
Hashtable tbl new Hashtable();
tbl.Add("Hi","Hello");
int foo = tbl.Count;

Here I have a simple example that give exception when this row is being
executed
*ConstructorInfo ctor = hashType.GetConstructor(argumentTypes);*
the exception I get is the following when I translated from my native
language
"NullReferenceException was unhandled
the Objectreference has not been given to an instance of an object"

Is it anyone that might have an idea what I have to change ?

static void Main(string[] args)
{
string path =
@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll";
Assembly theAssembly = Assembly.LoadFile(path);

Type hashType = theAssembly.GetType("Hashtable");

Type[] argumentTypes = Type.EmptyTypes;
ConstructorInfo ctor = hashType.GetConstructor(argumentTypes);

object newHash = ctor.Invoke(new object[]{});

MethodInfo method = hashType.GetMethod("Add");
method.Invoke(newHash, new object[] { "Hi", "Hello" });

PropertyInfo property = hashType.GetProperty("Count");
int count = (int)property.GetValue(newHash, null);
}

//Tony

Most likely because theAssembly.GetType("Hashtable") returns null.
Maybe it's an idea to debug the code and check it yourself?
 
A

Alberto Poblacion

Tony Johansson said:
Type hashType = theAssembly.GetType("Hashtable");
*ConstructorInfo ctor = hashType.GetConstructor(argumentTypes);*
"NullReferenceException was unhandled

Willem van Rumpt said:
Most likely because theAssembly.GetType("Hashtable") returns null.

... and the probable reason why it returns null is that you forgot to
specify the namespace:

theAssembly.GetType("System.Collections.Hashtable")
 
Top