Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 838
Anindya Chatterjee Avatar asked Oct 04 '10 11:10

Anindya Chatterjee


2 Answers

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.

like image 140
Jon Skeet Avatar answered Oct 18 '22 07:10

Jon Skeet


This is not supported. Legal constraints are listed here.

like image 20
Steve Townsend Avatar answered Oct 18 '22 07:10

Steve Townsend