Why Nested Classes?

  • Thread starter Thread starter Jake K
  • Start date Start date
J

Jake K

What purpose does nesting a class inside another class typically server?
Are there conditions where this would be beneficial? Thanks a lot.
 
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.
 
Thanks Mark. I appreciate the explanation.


Mark R. Dawson said:
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.
 
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);
}
}
}
 

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