RE: Provide access to a class without access to the constructor
- From: Peter Ritchie [C# MVP] <PRSoCo@xxxxxxxxxxxxxxxxx>
- Date: Thu, 10 Apr 2008 10:16:03 -0700
One way is to put A and B in one assembly and make the constructor for B
internal.
Another is with nested classes:
public class B
{
private B()
{
}
public class A
{
public A()
{
}
public B CreateB()
{
return new B();
}
}
}
But, then the class A would resolve through B:
B.A a = new A();
B b = a.CreateB();
--
Browse http://connect.microsoft.com/VisualStudio/feedback/ and vote.
http://www.peterRitchie.com/blog/
Microsoft MVP, Visual Developer - Visual C#
"Weeble" wrote:
Suppose I have a class A that works with instances of class B. I would
like it so that only an instance of A can generate instances of B, but
I would still like users of A to be able to handle instances of B,
including passing them as arguments to methods on A. Is there any way
to achieve this? Ideas so far:
Make B public, but make its constructor internal. This is okay, but
not great. It stops code in other assemblies from constructing
instances of B, but I'd rather prevent *everything* outside of A from
constructing instances of B.
Have a public interface, IB, and make B a private class inside of A.
This is not good because other code can still create instances of IB,
which might not behave at all like B, and pass them as arguments to
methods on A.
Give B a private constructor, and put A inside B. This works, but it's
*weird*, and becomes horrible if I want to have multiple classes like
B, because it requires A to be inside all of them, so they end up like
russian dolls.
I feel sure there must be a simple way to do this, but I can't think
of it. Any help would be much appreciated.
.
- References:
- Prev by Date: Re: Provide access to a class without access to the constructor
- Next by Date: Re: Provide access to a class without access to the constructor
- Previous by thread: Re: Provide access to a class without access to the constructor
- Next by thread: Re: Provide access to a class without access to the constructor
- Index(es):
Relevant Pages
|