tags:

views:

2728

answers:

5

Is there any way to use reflection to get the value of a private member on a static class?

+10  A: 

Yes.

Type type = typeof(TheClass);
FieldInfo info = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Static);
object value = info.GetValue(null);

Edit: Code has been tested and fixed, and now works (on my machine).

Edit #2: This is for a Field. For a Property, change type.GetField to type.GetProperty. You can also access private methods in a similar fashion.

configurator
Works on my machine. The most utter pharse by a developer.
David Basarab
Followed closely by "it is supposed to do that".
chuckj
So the key is to pass in null for the object on the GetValue call. Thats what I was missing. Thanks!
chief7
@chuckj: I thought "it wasn't supposed to do that". @chief7 - yep, null is the 'this' reference for static members.
configurator
This answer is certified correct: http://www.codinghorror.com/blog/archives/000818.html
configurator
A: 

Try something like this:

Type type = typeof(MyClass);
MemberInfo[] members = type.GetMembers(BindingFlags.NonPublic | BindingFlags.Static);

I would think that is should work.

David Pokluda
A: 

As stated above, you can probably use System.Type::GetMembers() with BindingFlags::NonPublic | BindingFlags::Static, but only if you have the right ReflectionPermission.

jeffamaphone
A: 

If you have full trust, you should be able to do:

Type t = typeof(TheClass);
FieldInfo field = t.GetField("myFieldName", BindingFlags.NonPublic | BindingFlags.Static);
object fieldValue = field.GetValue(myObject);

However, if you run this on a system without full trust, the GetField call will fail, and this won't work.

Reed Copsey
GetField returns a FieldInfo, not an array.
configurator
Indeed. This code will not compile, because GetField is invoked improperly. See: http://msdn.microsoft.com/en-us/library/system.type.getfield(VS.80).aspx
strager
Sorry about that - part of what happens when I'm typing these a little too fast. *blush* I fixed it, so it should be correct now.
Reed Copsey
+1  A: 

I suppose someone should ask whether this is a good idea or not? It creates a dependency on the private implementation of this static class. Private implementation is subject to change without any notice given to people using Reflection to access the private implementation.

If the two classes are meant to work together, consider making the field internal and adding the assembly of the cooperating class in an [assembly:InternalsVisibleTo] attribute.

John Saunders