0

I am working on a project that requires me to only instantiate ("new") a class by its own assembly, but not other assemblies. Is this possible?

I tried to use abstract, but that means I cannot instantiate it anywhere.

Example: The following to classes are in the same project/assembly.

public class Banana { public Banana() { ... } } public class Food. { public static Banana InstantiateBanana() { Banana banana = new Banana();//<=====How can you instantiate it inside the same assembly? I don't want other assemblies to instantiate it. ... return banana; } } 
9
  • 1
    Remove the abstract and make the instantiate method static. Commented Dec 30, 2019 at 5:57
  • 1
    are you looking for the protected member access modifier? maybe have a look at Accessibility Levels? Commented Dec 30, 2019 at 5:58
  • Thank you for replying so quickly! :) I edited the code, but it still did not work... :( Commented Dec 30, 2019 at 6:05
  • @MinijacksaysreinstateMonica How where should I use the protected modifier? Isn't protected for inherited classes? Commented Dec 30, 2019 at 6:08
  • When you say "other assemblies" what do you mean exactly? If you make the constructor private, but leave everything else the same, nothing else can call new on banana, but can still create one through the instantiate method. Commented Dec 30, 2019 at 6:10

1 Answer 1

0

I figured it out!

public class Banana { private Banana() { ... } public static Banana InstantiateBanana() { Banana banana = new Banana();//<=====How can you instantiate it inside this class? I don't want other assemblies to instantiate it. ... return banana; } } 

This should work. Only instantiate the Banana class inside its own class, but not in other classes. I only need a private constructor and a static method to instantiate.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.