Partager via


How to: Create a C# Class by Using the CodeModel Object

The CodeModel2 object hierarchy has methods for generating code automatically. While you would generally type the code manually, there are situations where you might want to automate some of the process. Automation allows you to:

  • Enforce naming conventions.

  • Enforce documentation standards.

  • Create standardized projects.

This procedure assumes that you know how to create an add-in project. For more information, see Creating Add-ins and Wizards.

The class in the following procedure will be contained in a new source file. Later a method is added to the class.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Customizing Development Settings in Visual Studio.

To add a new source file to the project

  1. Create a Visual Studio Add-in project by using Visual C#.

  2. On the Project menu, click Add Reference, click the .NET tab, select VSLangProj, VSLangProj2, and VSLangProj80, and click OK.

  3. Add the following method call to the OnConnection method.

    public void OnConnection(object application, 
    ext_ConnectMode connectMode, object addInInst, ref Array custom)
    {
        _applicationObject = (DTE2)application;
        _addInInstance = (AddIn)addInInst;
        // Call the AddClass method.
        AddAClass(_applicationObject);
    }
    
  4. Add the AddAClass method directly below the OnConnection method.

    public void AddAClass(DTE2 dte)
    {
    }
    
  5. Add the following code to the AddAClass method to add a new, empty code file to the project.

    The CodeFile template is installed with Visual Studio and can be located by using the GetProjectItemTemplate method. The method takes two parameters, the language templates for which you are searching, and the file name for the resulting project item. The project item is created by using the AddFromTemplate method.

    The code, proj = soln.Projects.Item(1);, necessitates that a Visual C# solution is open in Visual Studio integrated development environment (IDE) before you run this example.

    Project proj;
    String csItemTemplatePath;
    Solution2 soln;
    soln = (Solution2)_applicationObject.Solution;
    // Open a C# solution in the Visual Studio IDE
    // before running this add-in.
    proj = soln.Projects.Item(1);
    ProjectItem pi;
    csItemTemplatePath = soln.GetProjectItemTemplate("CodeFile",
     "CSharp");
    proj.ProjectItems.AddFromTemplate(csItemTemplatePath, "MyFile.cs");
    pi = proj.ProjectItems.Item("MyFile.cs");
    

To add a namespace to the source file

  • Add the following code to add a namespace to the source file.

    The FileCodeModel property contains a reference to the FileCodeModel2 object that represents all the code elements in the file. The FileCodeModel2 object provides several methods for adding code elements to the source file. The AddNamespace method returns a CodeNamespace object. You will use this CodeNamespace reference to add a class definition to the source code.

    FileCodeModel2 fcm = (FileCodeModel2)pi.FileCodeModel;
    CodeNamespace games;
    

To add the class to the namespace

  • Use the AddClass method to add a Chess class to the Games namespace. The AddClass method returns a reference to a CodeClass instance, which you can use to add properties and methods to the class.

    games = fcm.AddNamespace("Games", -1);
    CodeClass2 chess;
    

To define a method

  • Use the AddFunction method to add a Move method to the Chess class. The first argument to the method specifies the name of the created function. The second argument determines the type of created function, because operators and constructors are also added by using the AddFunction method. The third argument specifies the return type of the function and is substituted exactly into the method signature.

    if (games != null)
    {
        // Add a class to the namespace.
        chess = (CodeClass2)games.AddClass("Chess", -1, null, null,
     vsCMAccess.vsCMAccessDefault);
        // Add a method with a parameter to the class.
        CodeFunction2 move;
        move = (CodeFunction2)chess.AddFunction("Move",
     vsCMFunction.vsCMFunctionFunction,
     "int", -1, vsCMAccess.vsCMAccessDefault, null);
        move.AddParameter("IsOK", "bool", -1);
    }
    

    The source file produced by these procedures is shown below.

    namespace Games
    {
        class Chess
        {
            int Move(bool IsOK)
            {
                return default(int);
            }
        }
    }
    

    The add-in code is shown below.

    public void OnConnection(object application, ext_ConnectMode connectMode, 
    object addInInst, ref Array custom)
    {
        _applicationObject = (DTE2)application;
        _addInInstance = (AddIn)addInInst;
        // Call the AddClass method.
        AddAClass(_applicationObject);
    }
    public void AddAClass(DTE2 dte)
    {
        Project proj;
        String csItemTemplatePath;
        Solution2 soln;
        soln = (Solution2)_applicationObject.Solution;
        // Open a C# solution in the Visual Studio IDE
        // before running this add-in.
        proj = soln.Projects.Item(1);
        ProjectItem pi;
        csItemTemplatePath = soln.GetProjectItemTemplate("CodeFile", "CSharp");
        proj.ProjectItems.AddFromTemplate(csItemTemplatePath, "MyFile.cs");
        pi = proj.ProjectItems.Item("MyFile.cs");
        FileCodeModel2 fcm = (FileCodeModel2)pi.FileCodeModel;
        CodeNamespace games;
        try
        {
            // Add a namespace.
            games = fcm.AddNamespace("Games", -1);
            CodeClass2 chess;
            if (games != null)
            {
                // Add a class to the namespace.
                chess = (CodeClass2)games.AddClass("Chess", -1, null, null, 
    vsCMAccess.vsCMAccessDefault);
                // Add a method with a parameter to the class.
                CodeFunction2 move;
                move = (CodeFunction2)chess.AddFunction("Move", 
    vsCMFunction.vsCMFunctionFunction, "int", -1,
     vsCMAccess.vsCMAccessDefault, null);
                move.AddParameter("IsOK", "bool", -1);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed to add a code model element, because " 
    + ex.Message);
        }
    }
    
    Public Sub OnConnection(ByVal application As Object, _
     ByVal connectMode As ext_ConnectMode, ByVal addInInst As Object, _
     ByRef custom As Array) Implements IDTExtensibility2.OnConnection
        _applicationObject = CType(application, DTE2)
        _addInInstance = CType(addInInst, AddIn)
        AddAClass(_applicationObject)
    End Sub
    
    Public Sub AddAClass(ByVal dte As DTE2)
        Dim proj As Project
        Dim csItemTemplatePath As String
        Dim soln As Solution2
        soln = CType(_applicationObject.Solution, Solution2)
        ' Open a C# solution in the Visual Studio IDE before
        ' running this add-in.
        proj = soln.Projects.Item(1)
    
        Dim pi As ProjectItem
        csItemTemplatePath = soln.GetProjectItemTemplate("CodeFile", "CSharp")
        proj.ProjectItems.AddFromTemplate(csItemTemplatePath, "MyFile34.cs")
        pi = proj.ProjectItems.Item("MyFile34.cs")
        Dim fcm As FileCodeModel2 = CType(pi.FileCodeModel, FileCodeModel2)
        Dim games As CodeNamespace
        Try
            ' Add a namespace.
            games = fcm.AddNamespace("Games")
            Dim chess As CodeClass2
            If Not games Is Nothing Then
                ' Add a class to the namespace.
                chess = CType(games.AddClass("Chess"), CodeClass2)
                ' Add a method with a parameter to the class.
                Dim move As CodeFunction2
                move = CType(chess.AddFunction("Move", vsCMFunction.vsCMFunctionFunction, _
                "int"), CodeFunction2)
                move.AddParameter("IsOK", "bool")
            End If
        Catch e As Exception
            MsgBox("Failed to add a code model element, because " & _
            e.ToString())
        End Try
    End Sub
    

    Replace the code in the OnConnection class with the example code above. For additional information about how to run this example, see How to: Control Add-Ins By Using the Add-In Manager.

See Also

Tasks

How to: Use the CodeModel Object to Analyze Visual Basic Code

Concepts

Overview of the CodeModel Object for Visual Basic and C# Applications

Discovering Code by Using the Code Model (Visual Basic)

Discovering Code by Using the Code Model (Visual C#)