Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is possible to point that the type used for a generic method, should be an interface?

Here is my generic method code:

  public static IT Activate<IT>(string path)
  {
        //some code here....
  }

I'd want to set that generic IT must be only an interface.

Is this possible?

like image 615
DreadAngel Avatar asked Oct 04 '12 15:10

DreadAngel


People also ask

Can a generic type be an interface?

Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable. Generic constructors are the same as generic methods.

Can an interface have a generic type Java?

Java Generic Interface In similar way, we can create generic interfaces in java. We can also have multiple type parameters as in Map interface. Again we can provide parameterized value to a parameterized type also, for example new HashMap<String, List<String>>(); is valid.

Which types can be used as arguments of a generic type?

The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).


3 Answers

No, there's no such constraint in C#, or in .NET generics in general. You'd have to check at execution time.

if (!typeof(IT).IsInterface)
{
    // Presumably throw an exception
}
like image 161
Jon Skeet Avatar answered Sep 28 '22 09:09

Jon Skeet


No, you can't constraint IT to any interface type and interface alone. The closest you have is the class constraint and it applies to any class, interface, delegate, or array type. - http://msdn.microsoft.com/en-us/library/d5x73970.aspx

like image 25
manojlds Avatar answered Sep 28 '22 07:09

manojlds


The closest thing I can think of would be a runtime check in the static contructor. Like this:

static MyClass<IT>()
{
    if(!typeof(IT).IsInterface)
    {
        throw new WhateverException("Oi, only use interfaces.");
    }
}

Using the static contructor hopefully means it will fail fast, so the developer would discover the mistake sooner.

Also the check will only run once of each type of IT, not every method call. So won't get a performance hit.

like image 22
Buh Buh Avatar answered Sep 28 '22 07:09

Buh Buh