1

I'm learning reflection in C# and by tinkering with its tools I was able to create some code to:

  1. Load a DLL assembly from a file
  2. Get a public static class type from the assembly
  3. Get PropertyInfo of a public static property from the class
  4. 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

Ketell
  • 13
  • 4
  • 2
    You need to use the `GetProperty` overload so u can use `BindingFlags` [see link](https://learn.microsoft.com/en-us/dotnet/api/system.type.getproperty?view=netframework-4.8#System_Type_GetProperty_System_String_System_Reflection_BindingFlags_) . You need to specify `BindingFlags.Static`. – Matthiee Jul 15 '19 at 09:10

1 Answers1

2

get static property like as below and try

Type TestType = MyDll.GetType("ClassLibrary.Class1");
var field = TestType.GetProperty("Number ", BindingFlags.Public | BindingFlags.Static);

Basically you have to user BindingFlags to get static property that's trick here.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263