Nested Classes

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

Guest

Dear Folk,
I have implemented a nested class as follows:

Class Enclosing
{
string strName;

Class Nested1
{
}

Class Nested2
{
}

}
How to access the Variables declared in the enclosing class with in
thenested class. in this case i want to access and set the value of strName
in Nested1.
please let me know of this at the earliest

regards
 
Hi Sundararajan,
nested classes have the ability to access all fields of the outer class
even if they are declared private, you should be able to do something like:

class Enclosing
{
private string strName;

class Nested1
{
public Nested1(Enclosing objEnc)
{
objEnc.strName = "myName";
}
}
}

Hope that helps
Mark.
 
Sundararajan said:
Dear Folk,
I have implemented a nested class as follows:

Class Enclosing
{
string strName;

Class Nested1
{
}

Class Nested2
{
}

}
How to access the Variables declared in the enclosing class with in
thenested class. in this case i want to access and set the value of strName
in Nested1.
please let me know of this at the earliest

Enclosing.Nested1 needs to have a reference to an instance of
Enclosing. For example

Class Nested1
{
public Nested1(Enclosing Instance)
{
this.Instance = Instance;
}

private Enclosing Instance;
}
 
Sundararajan said:
I have implemented a nested class as follows:

Class Enclosing
{
string strName;

Class Nested1
{
}

Class Nested2
{
}

}
How to access the Variables declared in the enclosing class with in
thenested class. in this case i want to access and set the value of strName
in Nested1.
please let me know of this at the earliest

Unlike in Java's inner classes, C#'s nested classes don't implicitly
have a reference to an instance of the enclosing class - you don't need
to create an instance of the enclosing class at all in order to create
an instance of the nested class.

So, in order to have access to strName, the nested class needs to be
passed a reference to an instance of Enclosing.
 
Jon Skeet said:
Unlike in Java's inner classes, C#'s nested classes don't implicitly
have a reference to an instance of the enclosing class - you don't need
to create an instance of the enclosing class at all in order to create
an instance of the nested class.

So, in order to have access to strName, the nested class needs to be
passed a reference to an instance of Enclosing.

Or to be a subclass of Enclosing.
 
Back
Top