Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C# have package private?

I'm learning C# and coming from a Java world, I was a little confused to see that C# doesn't have a "package private". Most comments I've seen regarding this amount to "You cannot do it; the language wasn't designed this way". I also saw some workarounds that involve internal and partial along with comments that said these workarounds go against the language's design.

Why was C# designed this way? Also, how would I do something like the following: I have a Product class and a ProductInstance class. The only way I want a ProductInstance to be created is via a factory method in the Product class. In Java, I would put ProductInstance in the same package as Product, but make its constructor package private so that only Product would have access to it. This way, anyone who wants to create a ProductInstance can only do so via the factory method in the Product class. How would I accomplish the same thing in C#?

like image 986
Vivin Paliath Avatar asked Feb 11 '11 01:02

Vivin Paliath


2 Answers

internal is what you are after. It means the member is accessible by any class in the same assembly. There is nothing wrong with using it for this purpose (Product & ProductInstance), and is one of the things for which it was designed. C# chose not to make namespaces significant -- they are used for organization, not to determine what types can see one another, as in java with package private.

partial is nothing at all like internal or package private. It is simply a way to split the implementation of a class into multiple files, with some extensibility options thrown in for good measure.

like image 184
Kirk Woll Avatar answered Oct 13 '22 00:10

Kirk Woll


Packages don't really exist in the same way as they do in Java. Namespaces are used to organize code and prevent naming clashes, but not for access control. Projects/assemblies can be used for access control, but you can't have nested projects/assemblies like you can with packages.

Use internal to hide one project's members from another.

like image 9
Martin Doms Avatar answered Oct 12 '22 23:10

Martin Doms