How to access nested parent?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello

//-----------------
I have following situation:
public class Class1
{
public struct Struct1
{
public void Function1()
{
//Question here. How to access current Class1 instance
}
}
}
//-----------------

Struct1 is nested into Class1.
My Question is how to access from Struct1 code, to current Class1 instance.

Thank you.
 
Hi MilanB,
to access an instance of Class1 from Struct1 you need to pass in the
instance of Class1 as a reference either in the constructor or in whatever
method you are calling.

Mark Dawson
http://www.markdawson.org
 
MilanB said:
Hello

//-----------------
I have following situation:
public class Class1
{
public struct Struct1
{
public void Function1()
{
//Question here. How to access current Class1 instance
}
}
}
//-----------------

Struct1 is nested into Class1.
My Question is how to access from Struct1 code, to current Class1 instance.

Hi,
Mark already gave you the solution, but I have a few comments.
In your example, there is NO instance of Class1 associated with an instance of Struct1.
You can create a new Struct1 without ever creating a Class1 (and vice versa)
Nested classes have a scoping relationship with each other.
This does not imply that an instance of Outer contains an instance of Outer.Inner
Here is a simple test program (I changed Struct1 to a class and changed the names)
-----------------------
using System;

public class Test
{
static void Main()
{
Outer.Inner inner = new Outer.Inner();
inner.FUNC();
}
}

public class Outer
{
public Outer()
{
Console.WriteLine("new Outer()");
}
public class Inner
{
public Inner()
{
Console.WriteLine("new Outer.Inner()");
}
public void FUNC()
{
Console.WriteLine("In FUNC()");
}
}
}
-----------------------
Output:
new Outer.Inner()
In FUNC()

We created an instance of Outer.Inner without ever creating an instance of Outer

Hope this helps
Bill
 
Bill Butler said:
Nested classes have a scoping relationship with each other.
This does not imply that an instance of Outer contains an instance of
Outer.Inner

Exactly. All objects are peers and exist as areas of memory on the heap or
the stack. Some objects hold references to other objects, but no object is
ever physically contained within another. Objects generally don't know which
other objects hold references to them, unless they have been told (e.g. a
reference passed in via a constructor). This is true even for objects that
are defined as private within other objects.
 

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

Back
Top