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
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
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.
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.