Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

internal vs public in C#

Tags:

c#

.net

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?

like image 957
NoviceToDotNet Avatar asked Nov 15 '10 06:11

NoviceToDotNet


People also ask

What is the difference between internal and public?

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.

What is internal in C?

The internal keyword is an access modifier for types and type members. This page covers internal access. The internal keyword is also part of the protected internal access modifier. Internal types or members are accessible only within files in the same assembly, as in this example: C# Copy.

Is an internal class public?

A public member of a class or struct is a member that is accessible to anything that can access the containing type. So a public member of an internal class is effectively internal.

Is Internal same as private?

Private: - Private members are only accessible within the own type (Own class). Internal: - Internal member are accessible only within the assembly by inheritance (its derived type) or by instance of class.


2 Answers

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.

like image 127
Program.X Avatar answered Oct 06 '22 00:10

Program.X


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.

like image 30
Dr TJ Avatar answered Oct 06 '22 01:10

Dr TJ