I have an internal class, an internal constructor won't allow it to be used in a generic collection so I changed it to public. What's the accessibility if you have a public constructor in an internal class and is it any different to having an internal constructor?
internal means that it's only accessible to other classes which are in the same assembly. Public means it's available to all other classes.
internal is useful when you want to declare a member or type inside a DLL, not outside that. Normally, when you declare a member as public , you can access that from other DLLs. But, if you need to declare something to be public just inside your class library, you can declare it as internal .
A public member of a class or struct is a member that is accessible to anything that can access the containing type. So a public member of an internal class is effectively internal.
We can't create public and private constructors simultaneously in a class, both without parameters. We can't instantiate the class with a private constructor. If we want to create an object of a class with private constructor then, we need to have public constructor along with it.
The two are essentially the same. One argument I've seen for distinguishing between them is that making your constructor internal
ensures the type will only ever be instantiated by types within the current assembly, even if it is later decided that the type itself should be public
instead of internal
. In other words you could decide to change the type's visibility without lifting restrictions on its instantiation.
Making the constructor public
has the opposite effect (obviously), and might be sensible if you want for it to be possible to instantiate the type anywhere it is visible.
Also, as you've already pointed out, one small difference is that if the constructor's internal
, the type cannot be used as a generic type argument for a generic type with a where T : new()
constraint, as this constraint requires for the constructor to be public
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With