Nested Class

U

UncleJoe

Hi all,

What is the syntax to declare a nested class that can only be
instantiated by the outer class, yet visible to the other classes?
Essentially I want to limit the instantiation and access of the nested
class through the outer class. Thanks for your help in advance.
 
C

Christoph Nahr

I don't think that's possible. The inner class's constructor must
have at least internal visibility so that the outer class can
instantiate it, but internal visibility allows instantiation by other
classes in the same assembly.
 
B

Bill Butler

UncleJoe said:
Hi all,

What is the syntax to declare a nested class that can only be
instantiated by the outer class, yet visible to the other classes?
Essentially I want to limit the instantiation and access of the nested
class through the outer class. Thanks for your help in advance.

The best way is to probably define a public interface for your private nested class and the simply
return the interface.

Try this

using System;

class Test
{
public static void Main()
{
Outer outer = new Outer();
IX ix = outer.GetX();
ix.Foo();
}

public interface IX
{
void Foo();
}

public class Outer
{
public IX GetX()
{
return (new Nested());
}

private class Nested : IX
{
public void Foo()
{
Console.WriteLine("in Nested.Foo()");
}
}
}
}
 
C

Chris Priede

Hi,
What is the syntax to declare a nested class that
can only be instantiated by the outer class, yet
visible to the other classes?

You can put the two classes in a separate assembly and declare the Inner
class constructor "internal". If you are creating some kind of a reusable
library already, this could be exactly what you want.

You can also declare a public interface and have your Inner class declared
within the Outer class as private, but implementing the public interface.
With this combination, you can only instantiate objects of the Inner class
within the Outer class, but still expose the objects through the outer class
(as being type of the interface).

The result is more or less what you want, in either case.
 

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

Top