Harsha
Harsha

Reputation: 1879

Restrict object's creation

I have a very strange question here. I have Class A, Class B and Class C. I want to create object of Class B which can create the object of A. But how to restrict Class C from creating object of Class A.

One way is define Class A inside Class B, so that Only Class B can create the instance of Class A and Class C cannot access Class A.

But, I think nesting is a wrong way.

Do we have any way to restrict the object creation? Is it possible to use attribute and reflection to help to restrict? If possible is there a recommended way?

Please share your thoughts. Thanks in advance.

Upvotes: 0

Views: 2951

Answers (2)

Alexandr
Alexandr

Reputation: 1460

You can make constructor private, and create fabric method that retuns instance of A, and parameter in this method will be instance of B.

public class A
{
  private A (){}

    public static Instance(B BInstance)
    {
       A result = null;
       if (BInstance != null)
       {
         result = new A(); 
         //create here 
       }

       return result;

    }


    }

Upvotes: 0

Emond
Emond

Reputation: 50672

You can place class A and B in a single assembly and mark the constructor of class A as internal.

This way, only classes within that assembly can create instances of class A.

Upvotes: 1

Related Questions