4

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?
Community
  • 1
  • 1
GETah
  • 20,922
  • 7
  • 61
  • 103

3 Answers3

7

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.

Asti
  • 12,447
  • 29
  • 38
  • 1
    Actually, that's not true. From outside the assembly, the "protected" modifier still comes into play. If you declare an empty constructor as "internal" only, you can inherit the class outside the assembly, but you can't add a custom constructor to it. If you make it "protected internal", then you can. –  Sep 03 '14 at 19:07
  • 1
    @RobinHood70 I simply answered his specific query. In the the general case, you are correct. – Asti Sep 04 '14 at 05:27
4

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.

0

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

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122