I need some peer review on this


So I have a problem where I have an open type:

public class ThunderdomeActionInvoker<TController, TInput, TOutput> 
    : IControllerActionInvoker
    where TController : class
    where TInput : class, new()
    where TOutput : class
{
    /*...*/
}

And I need to make a generic one of these bad-boys and then “new” it up.  The only problem is, I don’t know whether my candidate/proposed type for TInput meets the “class” and/or “new()” constraints.  There doesn’t appear to be a Type.TryMakeGenericType() method and calling MakeGenericType() blindly will toss you up a nice fat ArgumentException to catch.

I did some cursory searching, but my Google-fu has failed me this day.  Is there nothing to do this?  If not, then I scrapped something together and I wanted to see what you all thought of this just in case I’m really the first person to have needed this.  I haven’t fully unit tested this (this was a spike, so I didn’t test-drive this… I know… SHAME), so don’t just COPY AND PASTE this or bad things will happen including 7 years bad luck and maybe some rain coming in through your windows.

public static bool MeetsSpecialGenericConstraints(Type genericArgType, Type proposedSpecificType)
{
    var gpa = genericArgType.GenericParameterAttributes;
    var constraints = gpa & GenericParameterAttributes.SpecialConstraintMask;

    // No constraints, away we go!
    if (constraints == GenericParameterAttributes.None)
        return true;

    // "class" constraint and this is a value type
    if ((constraints & GenericParameterAttributes.ReferenceTypeConstraint) != 0
        && proposedSpecificType.IsValueType )
    {
        return false;
    }
           
    // "struct" constraint and this is a value type
    if ((constraints & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0
        && ! proposedSpecificType.IsValueType)
    {
        return false;
    }

    // "new()" constraint and this type has no default constructor
    if ((constraints & GenericParameterAttributes.DefaultConstructorConstraint) != 0
        && proposedSpecificType.GetConstructor(Type.EmptyTypes) == null )
    {
        return false;
    }

    return true;
}

Thoughts?  Obvious bugs?

To MVC or to WebForms?