Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
315 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...