Restricting access to Public Sub New()

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
 
R

Richard Tappenden

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?
 
D

Daniel Klein

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
 
D

Daniel Klein

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

Dan
 
D

David Williams , VB.NET MVP

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

Daniel Klein

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top