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;
<span class="rem">// No constraints, away we go!</span>
<span class="kwrd">if</span> (constraints == GenericParameterAttributes.None)
    <span class="kwrd">return</span> <span class="kwrd">true</span>;

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

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

<span class="kwrd">return</span> <span class="kwrd">true</span>;

}

Thoughts?  Obvious bugs?

← To MVC or to WebForms?
Austin CodeCamp ‘09: Quite Possibly Better than Bacon →