Search code examples
c#.net

internal vs public in C#


I want to know the difference between the public and internal visibility modifiers.

When should we use internal on a class and when public? I am confused with when a method should be public or internal.

I read that internal can be accessed through the assembly, while public can also be used through the assembly. Then where does the difference lie?


Solution

  • 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.