GETah
GETah

Reputation: 21409

Protected internal constructor

I have a class ClassA that is a base class of other classes. I want this class constructor to be internal and protected so that it can't be inherited and instantiated from outside of my assembly (I can't make it sealed because I have other internal classes inheriting from it, you can see my other related question here) so I modified it to be like this:

public abstract ClassA{
    internal protected ClassA(){
    }
}

I have been told that this won't work as the combination internal protected is interpreted as internal OR protected which apparently makes the constructor only protected :( (visible from the outside)

Questions

  1. If that is true, why is internal protected interpreted as internal OR protected and not as internal AND protected?
  2. Is there a way I can declare a constructor internal and protected?

Upvotes: 4

Views: 3809

Answers (3)

user1482155
user1482155

Reputation:

If you specify the constructor as internal it will be visible for all classes in your assembly and will not be visible to classes outside of it, which is exactly what you want to achieve. In short if a constructor or a class member of class A is:

  • Protected - visible to all classes that inherit from A in its and in any other assembly
  • Internal - visible to all classes in class A's assembly
  • Protected Internal - visible to all classes that inherit from A in its and in any other assembly and to all classes in A's assembly

So in you case you only need to specify the constructor as internal.

Upvotes: 4

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

Did you try ?

Msdn tell us that

Constructors can be marked as public, private, protected, internal, or protected internal.

http://msdn.microsoft.com/en-us/library/ms173115%28v=vs.100%29.aspx

Upvotes: 0

Asti
Asti

Reputation: 12667

Specifying internal is enough.

It's an abstract class - it's implied that its constructor is protected because you can't make an instance of it - you can do nothing BUT inherit it.

Upvotes: 7

Related Questions