Modifying private variables from outside the containing class?

  • Thread starter Thread starter lukaslipka
  • Start date Start date
L

lukaslipka

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
 
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.
 
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.Instance | BindingFlags.Private)
fi.SetValue(a,value); //where a is an instance of A type
 
Back
Top