Here is a sample to explain my problem
class Foo
{
int a;
class Bar
{
void ChangeA()
{
a = 1;
}
}
}
function ChangeA() does not work because 'a' doesn't belong to Bar; it
belongs to Foo. So the question is: how can I make a function inside
class Bar change an element that belongs to Foo?
This could be possible cause(in my program) each object of kind Foo
has inside it at least one object of kind Bar and this object have to
change his 'parent' object.
Alberto Poblacion - 23 Oct 2007 17:15 GMT
> Here is a sample to explain my problem
>
[quoted text clipped - 13 lines]
> belongs to Foo. So the question is: how can I make a function inside
> class Bar change an element that belongs to Foo?
There is no direct way to do that. Even if the class is nested, it doesn't
see the contents of the surrounding class. One possible solution is to pass
a reference to the container into the contained class when instancing the
latter:
class Foo
{
public int a;
public void DoSomethingWithBar()
{
Bar x = new Bar(this);
x.ChangeA();
}
class Bar
{
private Foo container;
public Bar(Foo container)
{
this.container=container;
}
public void ChangeA()
{
container.a = 1;
}
}
}
Jon Skeet [C# MVP] - 23 Oct 2007 17:43 GMT
> Here is a sample to explain my problem
>
[quoted text clipped - 17 lines]
> has inside it at least one object of kind Bar and this object have to
> change his 'parent' object.
The objects are completely separate - there's no implicit Foo instance
for every Bar instance, or vice versa. You could pass one to the other,
of course, and Bar can access all the private members of Foo, but
you'll need a reference in order to use instance members.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
ssamuel - 23 Oct 2007 17:46 GMT
The problem here isn't so much that one thing can't see the other as
that you're trying to change instance members in class definitions.
You create a class definition that defines int a, then a class that
tries to change the instance of int a. The class definition of Foo
doesn't actually contain any int a, just the notion that an object of
the type defined in Foo would have an int a. You'll notice that Mr.
Poblacion's response clearly defines this distinction by instantiating
classes.
Mr. Poblacion's solution should work perfectly for many needs.
Another, one that would serve other needs, would be to define Foo.a as
a static int, in which case Foo.Bar.ChangeA() could modify Foo.a. In
that case, Foo myFoo would contain no definition int a, i.e., there
would be no myFoo.a, just Foo.a.
s}
> Here is a sample to explain my problem
>
[quoted text clipped - 18 lines]
> has inside it at least one object of kind Bar and this object have to
> change his 'parent' object.