3

How can I use Reflection to get a static readonly property? It's access modifier (public, protected, private) is not relevant.

isekaijin
  • 19,076
  • 18
  • 85
  • 153

3 Answers3

5

you can use the GetProperty() method of the Type class: http://msdn.microsoft.com/en-us/library/kz0a8sxy.aspx

Type t = typeof(MyType);
PropertyInfo pi = t.GetProperty("Foo");
object value = pi.GetValue(null, null);

class MyType
{
 public static string Foo
 {
   get { return "bar"; }
 } 
}
Matthias
  • 1,032
  • 8
  • 21
4

Use Type.GetProperty() with BindingFlags.Static. Then PropertyInfo.GetValue().

CheeZe5
  • 975
  • 1
  • 8
  • 24
3

Just like you would get any other property (for example, look at the answer to this question).

The only difference is that you would provide null as the target object when calling GetValue.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806