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;
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Tommy
  • 349
  • 4
  • 13
  • 1
    Remove the abstract and make the instantiate method static. – Ron Beyer Dec 30 '19 at 05:57
  • 1
    are you looking for the [`protected`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected) member access modifier? maybe have a look at [Accessibility Levels](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/accessibility-levels)? – Minijack Dec 30 '19 at 05:58
  • Thank you for replying so quickly! :) I edited the code, but it still did not work... :( – Tommy Dec 30 '19 at 06:05
  • @MinijacksaysreinstateMonica How where should I use the protected modifier? Isn't protected for inherited classes? – Tommy Dec 30 '19 at 06: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. – Ron Beyer Dec 30 '19 at 06:10
  • @RonBeyer I don't want other projects to use the constructor, but i still want to instantiate it in classes in banana's project. – Tommy Dec 30 '19 at 06:17
  • [`internal` c'tor modifier](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/internal)? – Uwe Keim Dec 30 '19 at 06:20
  • Yes, internal is what you're looking for, make the constructor internal instead of public. – Ron Beyer Dec 30 '19 at 06:23
  • @RonBeyer Solved it. Thank you! – Tommy Dec 30 '19 at 06:42

1 Answers1

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.

Tommy
  • 349
  • 4
  • 13