I\'m looking to define a nested class that is accessible to the container class and external classes, but I want to control instantiation of the nested class, such that only
How about abstraction via an interface?
public class Container
{
public interface INested
{
/* members here */
}
private class Nested : INested
{
public Nested() { }
}
public INested CreateNested()
{
return new Nested(); // Allow
}
}
class External
{
static void Main(string[] args)
{
Container containerObj = new Container();
Container.INested nestedObj;
nestedObj = new Container.Nested(); // Prevent
nestedObj = containerObj.CreateNested(); // Allow
}
}
You can also do the same thing with an abstract base-class:
public class Container
{
public abstract class Nested { }
private class NestedImpl : Nested { }
public Nested CreateNested()
{
return new NestedImpl(); // Allow
}
}
class External
{
static void Main(string[] args)
{
Container containerObj = new Container();
Container.Nested nestedObj;
nestedObj = new Container.Nested(); // Prevent
nestedObj = containerObj.CreateNested(); // Allow
}
}