isekaijin
isekaijin

Reputation: 19772

How to use Reflection to retrieve a property?

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

Upvotes: 3

Views: 297

Answers (3)

Matthias
Matthias

Reputation: 1032

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"; }
 } 
}

Upvotes: 5

Jon
Jon

Reputation: 437734

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.

Upvotes: 3

CheeZe5
CheeZe5

Reputation: 995

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

Upvotes: 4

Related Questions