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?
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?
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
}
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
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.
I've just made a quick test about the use of a base-interface. It's possible, but as I said, not sure if it's worth the effort or even if it's good practice.
public interface IBaseInterface
{
}
public interface IInterface1 : IBaseInterface
{
//some code here....
}
public interface IInterface2
{
//some code here....
}
public class Class1
{
public void Test()
{
Activate<IInterface1>("myPath");
//Activate<IInterface2>("myPath"); ==> doesn't compile
}
public static IT Activate<IT>(string path) where IT : IBaseInterface
{
//some code here....
}
}