Dangers of the public access modifier.

Microsoft .NET

Did you know that the public access modifer in C# is essentially the equivalent to extern in C++? According to the C# 4.0 language specification, it is.

People need to be careful with the public keyword. public in C# is not equivalent to public in C++! In C++, it means “internal to my compilation unit.” In C#, it means what extern meant in C++ (i.e., everybody can call it). This is a huge difference!

This was best said by Krzysztof Cwalina, quoted in the revised Fourth Edition of The C# Programming Language. It actually makes more sense to me know when I browse the .NET Framework source code as to why I see Microsoft using internal access modifiers quite a bit more often. If you are rusty and don’t quite remember the access modifiers they are:

public
Access not limited.

protected
Access limited to this class or classes derived from this class.

internal
Access limited to this program.

protected internal
Access limited to this program or classes derived from this class.

private
Access limited to this class.

But remember, as Christian Nagel said it best, that internal is rather best described as being “access limited to this assembly”, because a program can be defined as a collection of executables and assemblies, and a class marked as internal cannot be accessed by an assembly referencing it.

2 Comments

  1. Andrew Marlow

    Please can you explain Cwalina’s comment some more?

    I am a C++ programmer trying to learn C#. I have only just started, with “The C# Programming Language”. I got to the bit on access specifiers where Cwalina makes this comment and have been googling in the hope that more light is shed somewhere. All the example code in C# that I have seen uses public access in the way that I would as a C++er. I have a feeling that the comment is designed to make people consider using internal but I am not sure exactly why.

    Reply
    1. David Anderson (Post author)

      When you make a type public in a CLR language like C#, anyone can add a reference to your assembly and have access to that type, just like extern in C++. For example if you have a class that does sensitive work and you don’t want it to be public, you should mark it internal instead so it is only usable from types within the defining assembly. Of course someone can decompile your application and view it anyway, but it is an extra step to code access security.

      Reply

Leave a Comment

Your email address will not be published. Required fields are marked *

%d bloggers like this: