Re: NOOB QUESTION: How can I access an element in nested classes

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



"hstagni" <stagni@xxxxxxxxx> wrote in message news:1193154118.609622.91980@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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?

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;
}
}
}

.



Relevant Pages