Restricting access to Public Sub New()

  • Thread starter Thread starter Daniel Klein
  • Start date Start date
D

Daniel Klein

I have a situation where I need to prevent just anyone from instantiating a
particular class. The class is instantiated via certain methods from other
classes in the solution, but those are the only classes/methods allowed to
do this.

How can I prevent all other classes from creating a new instance of my
'restricted' class? Or, to put it another way, how can the restricted class
'know' who is trying to instantiate it?

Thanks,
Daniel Klein
Dublin, Ohio USA
 
Another option might be to make the constructor private and provide a shared
method called Create() that returns the constructed object or something like
that?
 
René

I tried that. Problem is that instantiation of the class is not related to
inheritance.

I want to be able to do:

Dim mrc As MyRestrictedClass =
someObject.MethodWhichReturnsRestrictedAnInstanceOfMyRestrictedClass()

but I don't want outside code to be able to do:

Dim mrc As MyRestrictedClass = New MyRestrictClass()

I'm going to give Richard Tappenden's idea a try.

But thanks for responding anyway :-)

Dan
 
Ahhh, kinda like what you have to do for a Singleton. However, what's to
prevent outside code from using the Create() method?

Dan
 
If the only ones that should be able to create an instance of the class
are in the same assembly, why not mark the class as Friend? This would
make that no one outside the assembly can use it. If you need the class
itself to be available outside the assembly, but only created within the
assembly then you could mark the class Public, but the Sub New as
Friend.

HTH

David
 
D#mn, that works!!!

Much thanks, David.

Dan


If the only ones that should be able to create an instance of the class
are in the same assembly, why not mark the class as Friend? This would
make that no one outside the assembly can use it. If you need the class
itself to be available outside the assembly, but only created within the
assembly then you could mark the class Public, but the Sub New as
Friend.

HTH

David
 
Back
Top