Question

I have ClassLibrary project in C# and all my 'private classes' (under different namespace) are accessible to each other inside the same assembly (project).

Class1.cs
----------------------------
namespace MyClass1App
{
   private class Class1{}
}


Class2.cs
----------------------------
namespace MyClass2App
{
   private class Class2{}
}

Now Class1() can access and create instance of Class2() class [like... new MyClass2App.Class2() ]. and yes, these classes (Class1() and Class2()) are not accessible outside the assembly. Its the same behavior when these classes are made as 'Internal'. Can someone help me understanding whats the actual use/difference of 'private' and 'internal' access specifiers when applied on class level?

Thanks!

Was it helpful?

Solution

alt text

For normal classes you can only apply public and internal other access modifiers don't make sense.

Nested classes can have all access modifiers types.

OTHER TIPS

You should not be able to declare a class as private at the namespace level. You can only have a private class if it is embedded within another class.

I get an error if I try to do this:

namespace MyApp
{
    private class Class1
    {
    }
}

This is the error message:

Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal

Access Modifiers (C# Programming Guide)

Class or struct members can be declared with one of five types of access. They can be public or internal, like the classes and structs themselves. A class member can be declared as protected using the protected keyword, meaning that only derived types using the class as a base can access the member. By combining the protected and internal keywords, a class member can be marked protected internal — only derived types or types within the same assembly can access that member. Finally, a class or struct member can be declared as private with the private keyword, indicating that only the class or struct declaring the member is allowed access to that member.

Duplicate Question: Internal vs. Private Access Modifiers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top