Search code examples
c#classabstractinstantiation

Class instantiation ("new") problems with assemblies and classes


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;
    }
}

Solution

  • 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.