3

What does the following class declarations mean ?

internal class A { }

public class B { }

I am able to access both of them in another class in another assembly using the reference of the assembly having class A and B. What's the difference in internal and public access specifiers in terms of class?

Nouman Bhatti
  • 1,341
  • 6
  • 28
  • 54
Aditya Shukla
  • 87
  • 1
  • 5
  • You shouldn't be able to access class A from another assembly. – Blorgbeard May 23 '16 at 23:27
  • 1
    @Blorgbeard Unless he is using the `InternalsVisibleToAttribute` – Lukazoid May 23 '16 at 23:28
  • 1
    Yes, but you would *think* he'd mention that in the question - it's not something you can do by mistake.. – Blorgbeard May 23 '16 at 23:29
  • Maybe this is in an already established project and doesn't realise it is in place. I'm not disagreeing with your point, just pointing out a small caveat :) – Lukazoid May 23 '16 at 23:31
  • @Aditya Shukla as Lukazoid stated, you should not be able to access the `internal` class A from another assembly unless you use the `InternalsVisibleToAttribute` for that assembly. Maybe you misunderstood the definition of an assembly? – Jan Paolo Go May 23 '16 at 23:32

2 Answers2

7

Internal is only available within the assembly it resides in.

Public is available to any assembly referencing the one it resides in.

If you can access the internal class from another assembly you either have "InternalsVisibleTo" set up, or you're not referencing the class you think you are.

Logarr
  • 2,120
  • 1
  • 17
  • 29
  • how to change InternalsVisibleTo? – Aditya Shukla May 23 '16 at 23:33
  • @AdityaShukla - In your `AssemblyInfo.cs` file you can put `[assembly:InternalsVisibleTo("AssemblyB")]` in there to make internal classes, methods, etc available to `AssemblyB`. This is normally used for testing purposes. – Logarr May 24 '16 at 00:15
1

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.

HaukurHaf
  • 13,522
  • 5
  • 44
  • 59
  • There is no technical difference between the two. public in C# means “accessible to anyone who can see the class”; making a public member of an internal class does not make the member more accessible than making it internal would. – ankit Feb 04 '22 at 07:10