11
votes

Whenever I create new classes using Visual Studio 2010 Express C# it creates them with no access modifier. 9 times out of 10 I want my new classes to be public. How can I have Visual Studio create empty class templates with the "public" modifier by default?

3
+1 Good question. I also want to add "using System.Linq;" to default Silverlight class template.. - Markus Johnsson
You do have this backward, 9 out of 10 classes in your assembly ought to be internal. Little workers that get the job done, unobserved from the outside. So that you can modify them without ever breaking any client code. Avoid making a design flaw a feature. - Hans Passant
@Hans: Fair enough however, most of the example code I've seen for ASP.NET MVC and WPF MVVM seems to use public classes and these guys always seem concerned with best practices. Of course I want to limit the scope as much as possible. In any case, I don't like the implicitness of no access modifier. - User
@HansPassant that depends on what project you are working on. If you are developing a proper N-tier solution, you're going to want to expose your interfaces, repositories and domain entities to other projects in the solution. It's only the presentation project which would consist mostly of internal objects. - Captain Kenpachi

3 Answers

6
votes

The trick is to create a new item template named Class. Then when you do Add > New Class, your template will be selected by default rather than the built-in Class template. (I am not sure if this behaviour is guaranteed but it Works On My Machine (TM).) To create the template:

  1. Right-click in your project and choose Add > Class. You can accept the default name (Class1) -- this is just a temporary file.
  2. Modify the generated class as, for example by adding the public modifier. Save everything.
  3. Choose File > Export Template.
  4. Choose Item Template and specify the relevant file (Class1.cs).
  5. Click Next until you get to the Template Options page. For the template name, enter Class.
  6. Click Finish.
  7. Delete the temporary Class1.cs file.

Now do an Add > Class and you should see your Class template being used by default instead of the built-in one.