Why does Visual Studio declare new classes as private in C#? I almost always switch them over to public, am I the crazy one?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
For security reasons.
You want to expose certain methods and not your whole class.
C++, upon which C# is derived, specified that the default class access level is private. C# carries this forward for better or worse.
Even if you mark a class as public, members are still private by default. In other words, the class is pretty much useless outside the same namespace. I think making it public by default instead may go too far, though. Try using 'internal' some. It should provide enough access for most purposes.
No I always have to slap that "public" keyword on the front of the class, so you are not alone. I guess the template designers thought it was a good idea to start with the very basics. You can edit these templates though in your Visual Studio install, if it really annoys you that much, but I haven't gotten to that point yet.
Private access by default seems like a reasonable design choice on the part of the C# language specifiers.
A good general design principle is to make all access levels as restrictive as possible, to minimize dependencies. You are less likely to end up with the wrong access level if you start as restrictive as possible and make the developer take some action to make a class or member more visible. If something is less public than you need, then that is apparent immediately when you get a compilation error, but it is not nearly as easy to spot something that is more visible than it should be.
I am not sure WHY it does that, but here's what you do in order to get Visual Studio to create the class as Public by default:
Go over to “Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033″, you will find a file called Class.zip, inside the .zip file open the file called Class.cs, the content of the file looks like this:
All you need to do is add “Public” before the class name. The outcome should look like this:
One last thing you need to do is flush all the Templates Visual Studio is using, and make him reload them. The command for that is ( it takes a while so hold on):
And that’s it, no more private classes by default. Of course you can also add internal or whatever you want.
Source