Search code examples
c#.netvisual-studiot4envdte

How to get the generic type parameters for a ENVDTE CodeInterface?


I'm writing a T4 template in Visual Studio 2010 and am generating code based on existing classes in a project. The code I need to generate depends on the generic type arguments of the interface that the classes implement, but I don't see a way to access that information through the Visual Studio core automation EnvDTE. Here is an example of a class that I need to analyse:

public class GetCustomerByIdQuery : IQuery<Customer>
{
    public int CustomerId { get; set; }
}

From this definition I want to generate code (using T4) that looks like this:

[OperationContract]
public Customer ExecuteGetCustomerByIdQuery(GetCustomerByIdQuery query)
{
    return (Customer)QueryService.ExecuteQuery(query);
}

Currently, the code in my T4 template looks a bit like this:

CodeClass2 codeClass = GetCodeClass();

CodeInterface @interface = codeClass.ImplementedInterfaces
    .OfType<CodeInterface>()
    .FirstOrDefault();

// Here I want to do something like this, but this doesn't work:
// CodeClass2[] arguments = @interface.GetGenericTypeArguments();

But how do I get the generic type arguments of a CodeInterface?


Solution

  • It's not pretty, but this does the trick for me:

    CodeInterface @interface;
    
    // FullName = "IQuery<[FullNameOfType]>
    string firstArgument = @interface.FullName.Split('<', '>')[1];