views:

262

answers:

7

Why does Visual Studio declare new classes as private in C#? I almost always switch them over to public, am I the crazy one?

A: 

C++, upon which C# is derived, specified that the default class access level is private. C# carries this forward for better or worse.

Craig
A: 

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.

Nick Berardi
+12  A: 

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:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;   

namespace $rootnamespace$
{
    class $safeitemrootname$
    {
    }
}

All you need to do is add “Public” before the class name. The outcome should look like this:

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;   

namespace $rootnamespace$
{
    public class $safeitemrootname$
    {
    }
}

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):

devenv /installvstemplates

And that’s it, no more private classes by default. Of course you can also add internal or whatever you want.

Source

Espo
Wow, exactly what i was looking for!
Adam Naylor
A: 

for security reasons. You want to expose certain methods not your whole class

SQLMenace
+8  A: 

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.

McKenzieG1
A: 

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.

Joel Coehoorn
A: 

Good question

Lulu