Search code examples
c#.netvisual-studio-extensionsvsixenvdte

VSIX DTE - Create class marked as partial


Problem: Creating a tool similar to the EF model generator, where You can enter tables/columns/relations and it will generate model classes. It is plugin to Visual Studio, running this in VSIX with DTE (Development Tools Environment).

I have succesfully created abstract class with properties. Now I want to create other class in same file, which will inherit from the abstract class, and also will be marked as partial. I have no idea how to mark the class as a partial, IntelliSence is not giving any suitable method/property and search on Google/SO/MSDN has not give me any relevant results.

Some code to get the idea:

ProjectItem File = CreateOrFindClassFile(/*params*/); //Creating project file            
if (File != null)
{
    var NS = File.FileCodeModel.AddNamespace("ABC"); //Added namespace ABC

    string ChildClassName = "Xyz";
    string BaseClassName = "XyzBase";


    //Generate base abstract class
    var BaseClass = NS.AddClass(BaseClassName);
    if (BaseClass != null)
    {
        BaseClass.Access = vsCMAccess.vsCMAccessPublic;
        BaseClass.IsAbstract = true;

        //some methods to add variables/methods/properties
    }


    //Generate partial child class
    var ChildClass = lNamespace.AddClass(ChildClassName);
    if (ChildClass != null)
    {
        ChildClass.Access = vsCMAccess.vsCMAccessPublic;
        ChildClass.AddBase(lBaseClassName);

        //TODO: add some code to mark as partial
    }
}

Question: Is there an OOP way (through DTE class tree) to mark a class as partial?

Or am I forced to write the class as a string line:

NS.GetStartPoint(..)
     .CreateEditPoint()
     .Insert("public partial class Xyz : XyzBase\n{\n}\n");

Note: It works but I'm loosing the control and OOP approach to the classes.

Edit1: Just found some reference on EnvDTE partial class keyword


Solution

  • Try casting your ChildClass to EnvDTE80.CodeClass2 and then use this following property:

    ((EnvDTE80.CodeClass2)ChildClass).ClassKind = EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass;
    

    Note that this property might be hidden in the Object Browser or Intellisense.