Modifying private variables from outside the containing class?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • lukaslipka@gmail.com

    Modifying private variables from outside the containing class?

    Hey,

    Is it possible to set a value for a private variable from outside the
    class in which it was declared using perhaps reflection?

    Something like

    class A {
    private string s;
    }

    class B {
    private void Foo (string str)
    {
    A a = new A ();

    // Here I need a way to set the value of A.s, without making it
    public
    }
    }

    Is something like this possible? I dont mind if its in a hacky
    fashion :-)

    Lukas

  • Andy

    #2
    Re: Modifying private variables from outside the containing class?

    On May 8, 8:46 am, lukasli...@gmai l.com wrote:
    Hey,
    >
    Is it possible to set a value for a private variable from outside the
    class in which it was declared using perhaps reflection?
    >
    Something like
    >
    class A {
    private string s;
    >
    }
    >
    class B {
    private void Foo (string str)
    {
    A a = new A ();
    >
    // Here I need a way to set the value of A.s, without making it
    public
    }
    >
    }
    >
    Is something like this possible? I dont mind if its in a hacky
    fashion :-)
    >
    Lukas
    It is, but it wouldn't recommend it at all. When you do this, your
    breaking encapsulation. If the implmentation of A changes, your code
    very well may break. If you need to be able to change the value and
    the class A is under your control, expose it as a property.

    Comment

    • TS25

      #3
      Re: Modifying private variables from outside the containing class?

      class B {
      private void Foo (string str)
      {
      A a = new A ();
      >
      // Here I need a way to set the value of A.s, without making it
      }
      }
      yes you can, as long as you run in Full Trust environment:

      the code should look sth like that:

      Type t = typeoof(B);
      FiledInfo fi = t.GetField("a", BindingFlags.In stance | BindingFlags.Pr ivate)
      fi.SetValue(a,v alue); //where a is an instance of A type

      Comment

      Working...