Search code examples
c#.netgenericstype-constraints

How to specify a type parameter which does NOT implement a particular interface?


I have developed some extension methods for objects, which I don't want to be used/shown in intellisense for objects which implements IEnumerable. Conceptually I want something like as follows

public static T SomeMethod<T>(this object value) where T != IEnumerable
        {

        }

Is it possible to impose this kind of constraint anyway in C#?

Edit

Sorry, I put the question in a wrong way. I know the allowable constraints in C#, what I want to know is that if there is any other way to accomplish this?


Solution

  • Just to confirm Øyvind's comment: there's no such constraint in C#. The only types of constraint are:

    • where T : struct (non-nullable value type constraint)
    • where T : class (reference type constraint)
    • where T : SomeClassName (conversion to a particular class constraint)
    • where T : ISomeInterfaceName (conversion to a particular interface constraint)
    • where T : U (conversion to another type parameter constraint)
    • where T : new() (parameterless constructor constraint)

    Note that I've only separated out the specific class and interface constraints as the former is a primary constraint and the latter is a secondary constraint.