- VBForums
- .NET and More
- C#
- 5.0 [RESOLVED] How to Restrict a class from being instantiated from particular class only
-
Oct 17th, 2020, 09:36 AM
#1
Thread Starter
PowerPoster
[RESOLVED] How to Restrict a class from being instantiated from particular class only
For illustration purpose
I have a class called ChildFactory & I need to restrict that, this class Can be called only by the Parents Class, but not by other classes
how to restrict the implementation in this way.
-
Oct 17th, 2020, 10:00 AM
#2
Re: How to Restrict a class from being instantiated from particular class only
Off the top of my head, there's no way to restrict the instantiation of one class to another specific but what you could do is put those two classes in their own library and then declare the constructor(s) of the one class internal, which means that that class can only be instantiated by classes declared in the same assembly. That's how it is that you cannot create a DataRow object directly in your own code but the DataTable class can.
-
Oct 17th, 2020, 10:30 AM
#3
Thread Starter
PowerPoster
Re: How to Restrict a class from being instantiated from particular class only
Thank you
vb.net Code:
namespace ProductionOperations{ public class Parents { public void Do_ChildDesign() { ChildFactory Cf = new ChildFactory(); Cf.DesignChild(); } } internal class ChildFactory { internal ChildFactory() { } private void DesignChild() { return; } } }
-
Oct 17th, 2020, 09:20 PM
#4
Re: How to Restrict a class from being instantiated from particular class only
For the record, I wasn't suggesting that you make the class internal; just the constructor. By making the class internal to, you restrict it to be used at all only within that assembly. If that works for you then you probably didn't need another assembly in the first place and you could have just declared the one class private inside the other. In both cases, you end up with ChildFactory being known and able to be used only by Parents.
-
Oct 18th, 2020, 07:51 AM
#5
Thread Starter
PowerPoster
Re: [RESOLVED] How to Restrict a class from being instantiated from particular class
you could have just declared the one class private inside the other. In both cases, you end up with ChildFactory being known and able to be used only by Parents.
Yes sir it worked for me
- VBForums
- .NET and More
- C#
- 5.0 [RESOLVED] How to Restrict a class from being instantiated from particular class only
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|