Modifying private variables from outside the containing class?

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
 
A

Andy

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.
 
T

TS25

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top