Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a public constructor in an internal class and an internal constructor?

Tags:

c#

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?

like image 432
Ed D Avatar asked Sep 23 '10 17:09

Ed D


People also ask

What is the difference between internal and public class?

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.

Is Internal better than public?

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 .

Can internal class have public methods?

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.

Can a class have both private and public constructors?

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.


1 Answers

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.

like image 124
Dan Tao Avatar answered Sep 28 '22 15:09

Dan Tao