-1

I have a Type that implements an interface with a static property:

public class MyClass : IMyClass 
{
   public static string SomeInfo = "Lorem Ipsum";

   ...
}

I want to get the value of SomeInfo without instantiating the class. Seems like I should be able to do this since the property is public static.

I can get the property like this:

var myClass = Type.GetType("MyNamespace.MyClass");
var someInfoProperty = myClass.GetProperty("SomeInfo", BindingFlags.Public | BindingFlags.Static);

However, I cannot figure out how to the value of someInfoProperty. The property method GetValue() requires an object (instance of the class).

Any idea how I can do this, or is it even possible?

Thanks.

realmikep
  • 593
  • 1
  • 6
  • 22
  • 1
    Note, you might find it easier to do `typeof(MyClass)`, rather than `Type.GetType("MyNamespace.MyClass")` – canton7 May 05 '21 at 16:33

1 Answers1

4

The property method GetValue() requires an object (instance of the class).

Nope, you just pass null:

var value = someInfoProperty.GetValue(null);

From the documentation:

Because static properties belong to the type, not individual objects, get static properties by passing null as the object argument.

Admittedly the documentation doesn't mention that as prominently as I'd like to see it...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194