How does C# verify the C# Private Definition?
.net, c#, compiler-construction, visual-studio
Solution
You omitted the relevant lines from the generated IL:
.method private hidebysig instance void privateHelloWorld () cil managed
.method public hidebysig instance void publicHelloWorld () cil managed
And that's all there is to it. See the accessibility section in this Common Type System MSDN page.
When mangling the IL to call the private method and compiling it with ilasm, at runtime you'll get:
Unhandled Exception: System.MethodAccessException: Attempt by method 'Program.Main(System.String[])' to access method 'CallPublicHelloWorld.privateHelloWorld()' failed.
at Program.Main(String[] args)
So there is an accessibility check performed by the runtime.
Problem
I use private and public methods all the time. However, I do not understand why they work. Creating a small Hello World Program: ``` public class CallPublicHelloWorld { public void CallHelloWorld() { publicHelloWorld(); privateHelloWorld(); } private void privateHelloWorld() { Console.WriteLine("Hello World"); } public void publicHelloWorld() { Console.WriteLine("Hello World"); } } ``` The IL created for the public method: ``` IL_0000: nop IL_0001: ldstr "Hello World" IL_0006: call void [mscorlib]System.Console::WriteLine(string) IL_000b: nop IL_000c: ret ``` The IL created for the private method: ``` IL_0000: nop IL_0001: ldstr "Hello World" IL_0006: call void [mscorlib]System.Console::WriteLine(string) IL_000b: nop IL_000c: ret ``` It's the exact same. How does the JIT differentiate and verify that the private/public rules were followed?