internal vs public in C#

public is visible from wherever.

internal is visible only within an assembly.

You tend to use internal only to protect internal APIs. For example, you could expose several overloads of a method:

public int Add(int x, int y)
public int Add(int x,int y, int z)

Both of which call the internal method:

internal int Add(int[] numbers)

You can then put a lot of sophistication on a method, but "protect" it using facade methods that may help the programmer to call the method correctly. (The implementation method with the array parameter may have an arbitrary limit of values, for example.)

Also worth noting that using Reflection, any and all methods are callable regardless of their visibility. Another "hack" to control/gain access to internally hidden APIs.


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.

In formal definition: internal members are visible just inside the current assembly.


internal is also useful when writing unit tests. The InternalsVisibleTo attribute lets your test assembly access internal methods in your code assembly. That is, you can test methods that appear private to the outside world without using reflection.

Tags:

C#

.Net