Reputation: 1277
I really dont understand why, but it seems like the internal access modifier doesn't work :S
I've looked at this tutorial: http://msdn.microsoft.com/en-us/library/7c5ka91b(v=vs.110).aspx
But for me, it compiles. ALso, i have a bought a book Illustrated C# 2012. And the author explains the internal class etc etc... But still, it doesn't do anything.
Here is my complete code that works EVEN with internal access.
//Program.cs
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Class1 myclass = new Class1(); //works
myclass.display(); //works
myclass.display2(); //works even though its not public :S
Console.Read();
}
}
}
-
//Class1.cs
namespace ConsoleApplication1
{
internal class Class1
{
public void display()
{
Console.WriteLine("display()");
}
internal void display2()
{
Console.WriteLine("display2()");
}
}
}
I can even access the function internal void display2() :S
Upvotes: 2
Views: 2900
Reputation: 141
The internal
access modifier means the member can be accessed anywhere from within the same assembly.
In your case, the classes "Program" and "Class1" are within the same assembly, therefore, Program can access display2 (Which is also internal
and within the same assembly).
If you don't want display2 to be accessed from the Program class, you could simply make it private
and therefore it would only be accessible from Class1.
Upvotes: -1
Reputation: 109557
internal
means "Acessible by anything in the same assembly".
Because your class Class1 and class Program are in the same assembly, class Program can access display2().
I think you've accidentally put them in the same assembly; if you look carefully at Microsoft's sample code you'll see it says "Assembly1.cs" and "Assembly2.cs"
If you are using Visual Studio, the easiest way to test this with a different assembly is to create a new class library project in the same solution. That will then count as a separate assembly. You'd have to add to the main project a reference to the new project (via Add Reference and then the Solution tab).
There's a Stack Overflow question about "What's an assembly?" if you need more info.
Upvotes: 7
Reputation: 98740
From MSDN
;
Internal types or members are accessible only within files in the same assembly
Since Program
and Class1
in the same assembly, there shouldn't be a problem..
What does the internal modifier do exactly? It states that "The intuitive meaning of internal is 'access limited to this program.'"
In other words, no external program will be able to access the internal type.
Upvotes: 1
Reputation: 16423
If both classes are in the same assembly then internal
is working as expected.
The internal
modifier is used to make sure that types and members are only available to files in the same assembly.
Ref: http://msdn.microsoft.com/en-gb/library/7c5ka91b%28v=vs.80%29.aspx
Upvotes: 2