How can we help you today? How can we help you today?

How to get Namespace of GenericArguments?

Hello. When I enumerate the GenericArguments of a type I don't seem to have access to the namespace string. How do I get the namespace string of the generic arguments? Here is the code I wrote and am using now (contents of foreach loop edited for brevity):
void PrintClassGenericArguments(ITypeDeclaration type, out string output)
{
    output = string.Empty;

    ITypeCollection arguments = type.GenericArguments;

    foreach(IType argument in arguments)
        output += argument.ToString(); // gives me the type, but not
                                                       // fully qualified with namespace
}

One example of what I get is 'KeyValuePair<Object, Object>', but what I want is 'System.Collections.Generic.KeyValuePair<System.Object, System.Object>'. I would ask Lutz himself, but given that Reflector isn't on his plate anymore I don't really want to bother him with it. Though I hope he reads this post and helps me out :)
CodeJingle
0

Comments

1 comment

  • CodeJingle
    After digging for another hour I finally figured out at least one way to do it :D . Funny enough figuring this out required opening Reflector in Reflector. So it turns out that each of the Generic arguments is of a derived IType interface type, and guessing ad-hoc which derived interface type it is and moving on from there works just fine (however inefficient that way of doing it may be). A Generic argument IType is always implementing one of these interfaces (all derived from IType):
    IArrayType
    IDefaultConstructorConstraint
    IFunctionPointer
    IGenericArgument
    IOptionalModifier
    IPointerType
    IReferenceType
    IReferenceTypeConstraint
    IRequiredModifier
    ITypeReference
    IValueTypeConstraint
    

    Use the 'as' construct or something similar to attempt casting to each type:
    IType argument;
    IArrayType arrayTypeArgument = argument as IArrayType;
    

    If it fails the derived instance will be null so try to cast to next derived interface, otherwise if it is successful you found the right type. The Generic argument will always derive from one of the above interface types (and not more than one of the above).
    CodeJingle
    0

Add comment

Please sign in to leave a comment.