Search code examples
c#propertiesaccess-specifier

Is it Possible to expose a private variable in c# ?


i just wanted to know Is it Possible to expose a private variable in c# ? I know if data of a class is private means is not accessible from outside class. if, yes, then how ?


Solution

  • It is possible. Use Reflection for that:

    Type type = yourObj.GetType();
    BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
    FieldInfo field = type.GetField("fieldName", flags);
    object value = field.GetValue(yourObj);
    

    Reflection allows to read type's metadata at runtime and uncover types internals (fields, propertis etc).