Access a Private Static Member of a another Class using C# (.NET)
This method allows access to a private static member variable of any class. I've used this primarily in NUnit tests, where I wanted to check on hidden details, that were not exposed via the public or protected access modifiers.
public static T GetStaticMember<T>(Type ObjectType, string MemberName)
{
const BindingFlags eFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField;
var field = ObjectType.GetField(MemberName, eFlags);
if (field == null)
throw new ArgumentException("'" + MemberName + "' is not a valid static member in '" + ObjectType + "'.");
return (T) field.GetValue(null);
}
Written By: datfinesoul on April 08, 2009 at 15:46
Submit a comment, suggestion, or additional information about this snippet
If you login or register,
you'll be able to post a comment or provide feedback about this snippet.
Comments
Awesome, this is exactly what I was looking for. Would you be able to add some additional code on how to call a static private method of another class?