I'm learning reflection in C# and by tinkering with its tools I was able to create some code to:
- Load a DLL assembly from a file
- Get a public static class type from the assembly
- Get PropertyInfo of a public static property from the class
- Get/Set the value of the property
I'm writing the code in Visual Studio 2019, the solution is a simple WPF app and a DLL, both written in C#.
The code blocks for setting and getting the value of the property:
int Number = int.Parse(InputBox.Text);
Assembly MyDll = Assembly.LoadFile(@"D:[...]\WPFapp\ClassLibrary\bin\Debug\ClassLibrary.dll");
Type TestType = MyDll.GetType("ClassLibrary.Class1");
PropertyInfo PropInfo = TestType.GetProperty("Number");
PropInfo.SetValue(null, Number);
Assembly MyDll = Assembly.LoadFile(@"D:[...]\WPFapp\ClassLibrary\bin\Debug\ClassLibrary.dll");
Type TestType = MyDll.GetType("ClassLibrary.Class1");
PropertyInfo PropInfo = TestType.GetProperty("Number");
DiffAssemblyBox.Text = PropInfo.GetValue(null).ToString();
The DLL:
namespace ClassLibrary
{
public static class Class1
{
public static int Number {get; set;}
}
}
The code above runs, and I made the app so a number entered by the user would be sent to the DLL and back. However, when I try to send it it throws a System.NullReferenceException at SetValue. I tried to debug, and it seems that the TestType type is properly set to the class, but PropInfo is null.
Thanks for any help