Question

In C# is it possible to constrain the type parameter of a generic method such that it is restricted to an unclosed type of an interface in a type safe manner? Let me elaborate...

For example I have the following psuedo code:

    public bool Validate<TValidator>(object validatable)
        where TValidator : IValidator<>
    {
        // code that finds all implementations of IValidator that closes on 
        // recursive base types / interfaces of the validatable object
        // return true if validates
    }

I have several interfaces that implement IValidator such as ICreateValidator and IDeleteValidator. I can easily enough gather the validators I want in a reflection heavy not quite as generic as I'd like manner that close on all type T, and all base classes of T as well as interfaces implemented by T.

The desire would be able to call something along the lines of

    var validates = Validate<IDeleteValidator<>>(concreteDomainObject);

Which would provide me with the unclosed type of IDeleteValidator<> allowing me to internally find each implementations of IDeleteValidaor where T is either the concreteDomainObject type, an interface that the concreteDomainObject type implements, or recursive base types concreteDomainObject type extends all the way up to object.

Sure I could close the interface on the domain object, it just doesn't make sense to me that I should have to call

    Type unclosedValidatorType = typeof (TValidator).GetGenericTypeDefinition()

Given that I both could not be assured that TValidator would be a generic type at compile time, and that the explicitly closed TValidator would not be used except to strip it's closing type this seems like the wrong way of doing things to me.

The psuedo code I provided obviously function, but is there a type safe equivalent to constrian the type of generic method to an unclosed type of given interface?

edited to correct some terminology

Was it helpful?

Solution

In C# is it possible to constrain the type of a generic method such that it is restricted to an unclosed type of an interface in a type safe manner?

No. Type arguments have to be closed, so it would make no sense to constrain the type parameter to type which couldn't be expressed as type arguments.

Forget the constraint part to start with - this simple code won't work:

using System;

class Test
{
    static void Main()
    {
        Foo<Action<>>();
    }

    static void Foo<T>()
    {
        Console.WriteLine(typeof(T));
    }
}

Errors:

Test.cs(7,20): error CS1525: Invalid expression term '>'
Test.cs(7,23): error CS1525: Invalid expression term ')'
Test.cs(7,24): error CS1026: ) expected
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top