views:

183

answers:

2

I have a class that has an inner struct/class (I have decided which yet, if it matters for this I will use that) I want the inner class to be accessed from other classes but only constructed by the outer class. Is this possible?

Thanks

+4  A: 

The closest you can get is an internal constructor, unfortunately. While private and protected members of an outer class are available to an inner class, the opposite is not true.

Adam Robinson
internal seems to work, I would have liked to have only the outer class have access but this is good enough. Thanks
Android
+4  A: 

Why not declaring an inner interface (or an inner abstract class) so that's not instantiatable, then a private inner class that implements the interface ?

Something like

using System;
namespace test {

    class Outer {

        public interface IInner {
            void SayHello();
        }

        private class Inner : IInner {
            public void SayHello() {
                Console.WriteLine("Hello");
            }
        }

        public IInner MakeInner() {
            return new Inner();
        }

    }

    class Program {
        static void Main(string[] args) {
            Outer x = new Outer();
            x.MakeInner().SayHello();
        }
    }
}

In this way only Outer can create concrete Inner objects, while other classes must invoke the MakeInner method.
Please note that in this way you are also enforcing the constraint for classes in the same assembly.

Paolo Tedesco
+1 A little extra work, but a nice solution anyway.
Thorarin
This is a clever solution, thanks.
Android