radbyx
radbyx

Reputation: 9660

How to define the default code when creating a new C# Class with Visual Studio 2010

Making a new class in VS10 gives me

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Foo
{
    class Bar
    {
    }
}

Is it possible to setup VS10 so I get this instead?

namespace Foo
{
    public class Bar
    {
    }
}

Upvotes: 4

Views: 743

Answers (2)

btlog
btlog

Reputation: 4780

Yes you can. This MSDN article http://msdn.microsoft.com/en-us/library/s365byhx.aspx has links to several approaches to achieve this.

I think the easiest way is to make a file with the template that you want, substitue parameters and export the template. In your example create a new class with the existing template

 namespace Foo
 {
     public class Bar
     {
     }
 }

Swap out the variable parts of this. ie the namespace name 'Foo' and the class name 'Bar'

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

Save the change

  • You can now go File -> Export Template. Select Item Template (click Next)
  • Select the file you created for this example (click Next)
  • Select any item references you want to add to the project. In this
    case there aren't any (click next)
  • Enter a Template Name (ie PublicClass). This is what the file will be called in the new file dialog. Also what the default file will be called on creation

This will create a zip file in {userpath}/My Documents/Visual Studio 2010/My Exported Templates. You do not need to run as admin or run any other tools. VS will automatically pull this up from the this path.

I realise this doesn't replace the existing option. If you want to do this I would use the same process, use the same Item Name as the default Item Name. In this case class. I would use the path and registration process defined by @James Hill

Upvotes: 1

James Hill
James Hill

Reputation: 61792

Yes, you can modify it. See this article for a decent walk-through.

Here's a snip-it from the article that explains where to find the template:

Step One - find the template

Visual Studio 2010

64 bit:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

32 bit: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip

Step Two - modify the template

Extract the zip file.

Using a text editor, open the Class.cs file.

Save the file.

Rebuild the zip file with the new Class.cs. Be careful to build the zip file correctly.

Copy the new zip file back here and overwrite the existing one

Step Three - update VS

Open a command prompt as Administrator.

Change to the appropriate directory and run command:

devenv.exe /installvstemplates

Upvotes: 3

Related Questions