Groups | Blog | Home
all groups > c# > january 2007 >

c# : Why Nested Classes?


Mark R. Dawson
1/5/2007 7:48:00 PM
Hi Jake,
nested classes are most often used when they are declared private, so only
the enclosing class can see them. They can then be used as helper classes
inside another class without having to expose them to any other types or
clutter up your object model.

Mark.
--
http://www.markdawson.org
http://themightycoder.spaces.live.com


[quoted text, click to view]
Jake K
1/5/2007 10:16:19 PM
What purpose does nesting a class inside another class typically server?
Are there conditions where this would be beneficial? Thanks a lot.
Jake K
1/5/2007 11:23:21 PM
Thanks Mark. I appreciate the explanation.


[quoted text, click to view]
Dave Sexton
1/6/2007 3:49:25 AM
Hi Jake,

Sometimes nested classes are made public.

A nested, public class can be useful when two classes are closely related,
when one class has purpose only when its used along with the other class,
and when one needs to access private implementation details of the other,
but must remain publicly accessible.

For instance, the System.Windows.Forms.Control.ControlCollection class.
It's a nested, public class that can be inherited as well.

When an instance of the nested class has a reference to an instance of the
containing class, it can access its private members. If it were to be
declared externally than those private members would have to be marked
internal, making them visible to all classes within the same assembly.

Here's an example of two classes. The Outer class contains the nested,
Inner class and the Inner class references the Outer class to access its
private members:

public class Outer
{
static void Main()
{
Outer outer = new Outer("This is the outer value.");

Outer.Inner inner = new Outer.Inner(outer);

inner.WriteOuterValue();
}

string value;
public Outer(string initialValue)
{
value = initialValue;
}

public class Inner
{
Outer outer;
public Inner(Outer outer)
{
this.outer = outer;
}

public void WriteOuterValue()
{
Console.WriteLine(outer.value);
}
}
}

--
Dave Sexton
http://davesexton.com/blog

[quoted text, click to view]

Laurent Bugnion [MVP]
1/6/2007 10:43:32 AM
Hi,

[quoted text, click to view]

I typically use nested classes to implement a UML composition (as
opposed to aggregation). The composition is typically used when a class
doesn't have a life on its own, but is very closely related to another
class. An example would be a treeview's node: The node alone doesn't
make sense, it's only viable if it belongs to a treeview. In that case,
it can be interesting to declare the Node class nested into the Treeview
class.

HTH,
Laurent
--
Laurent Bugnion [MVP ASP.NET]
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Jake K
1/6/2007 11:26:31 AM
Thanks a lot for the replies. Much appreciated.


[quoted text, click to view]
AddThis Social Bookmark Button