9

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?

Steven
  • 166,672
  • 24
  • 332
  • 435
  • why not `Type[] types = @interface.GenericTypeArguments()`? – cuongle Sep 30 '12 at 16:03
  • @Cuong: And how do I get that Type instance of the interface exactly? Don't forget that Visual Studio interop works with `CodeClass` instances, not with `Type`. – Steven Sep 30 '12 at 17:48
  • 1
    I'm having the same issue, but it's worse in that the ImplementedInterfaces has a count of 0. There has to be a better way to get the generics on a class implementation... – James Hancock Jan 15 '14 at 15:26

1 Answers1

7

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

CodeInterface @interface;

// FullName = "IQuery<[FullNameOfType]>
string firstArgument = @interface.FullName.Split('<', '>')[1];
Steven
  • 166,672
  • 24
  • 332
  • 435