Search code examples
c#oopprivate

C#: Is there a way to access a private getter and setter?


I am new to C# and I am just wondering if there is any way to access getter and setter.

here is an example code:

public class Foo
{
  private AnotherClass _here;
  private bool Bar
  {
    get{return _here.GetAnswer();}
    set(return _here.SetAnswer(value);)
  }
}

I am aware that there is the Reflection feature in c# but as far as I have read, It only does private variables.

Also, I have been trying This code:

public void func()
{

  MethodInfo privMethod = Foo.GetType().
                        GetMethod("Bar", BindingFlags.NonPublic | BindingFlags.Instance);

  object fff = privMethod.Invoke();

}

But it would not work.

Can anyone help me?


Solution

  • PropertyInfo property = typeof(Foo).GetProperty("Bar", BindingFlags.Instance | BindingFlags.NonPublic);
    MethodInfo getMethod = property.GetGetMethod(true);
    MethodInfo setMethod = property.GetSetMethod(true);