How to get the value of private field in C#?

As others have said, since the field is private you should not be trying to get it with normal code. The only time this is acceptable is during unit testing, and even then you need a good reason to do it (such as setting a private variable to null so that code in an exception block will be hit and can be tested).

You could use something like the method below to get the field:

/// <summary>
/// Uses reflection to get the field value from an object.
/// </summary>
///
/// <param name="type">The instance type.</param>
/// <param name="instance">The instance object.</param>
/// <param name="fieldName">The field's name which is to be fetched.</param>
///
/// <returns>The field value from the object.</returns>
internal static object GetInstanceField(Type type, object instance, string fieldName)
{
    BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
        | BindingFlags.Static;
    FieldInfo field = type.GetField(fieldName, bindFlags);
    return field.GetValue(instance);
}

So you could call this like:

string str = GetInstanceField(typeof(YourClass), instance, "someString") as string;

Again, this should not be used in most cases.


You can't - and you're not meant to. It's private. If this is someone else's class, then clearly they don't want you to have access to that field. The fact that it's private allows them to change the implementation later - they might end up with that value as part of another variable, or renamed, or possibly gone completely if it's no longer required in order to implement the public API.

If it's your own class and you're sure you want other people to be able to access it, just expose it with a property:

public string SomeString { get { return someString; } }

EDIT: Having seen your comments, you can access the private fields with reflection... but for an acceptance test you shouldn't have to. You should be testing the public API. For unit tests it makes sense to bend the rules sometimes, and treat the class as a "white box" rather than doing "black box" testing, but for acceptance tests I would definitely stick to the public API.

If this doesn't help, I suggest you talk to the developers of the production code: explain why you want access, and ask them to expose it via a property. They could make it an internal property, and use [InternalsVisibleTo] to get access to it in your test assembly. I would personally prefer this over using reflection - otherwise if the production code changes in a perfectly valid way, your tests will fail when they shouldn't.


Use reflections, but be prepared to be hit with a big stick from a fellow programmer.

Tags:

C#