Is there a way to get the following function declaration?
public bool Foo() where T : interface;
ie. where T is an interface type
To follow up on Robert's answer, this is even later, but you can use a static helper class to make the runtime check once only per type:
public bool Foo() where T : class
{
FooHelper.Foo();
}
private static class FooHelper where TInterface : class
{
static FooHelper()
{
if (!typeof(TInterface).IsInterface)
throw // ... some exception
}
public static void Foo() { /*...*/ }
}
I also note that your "should work" solution does not, in fact, work. Consider:
public bool Foo() where T : IBase;
public interface IBase { }
public interface IActual : IBase { string S { get; } }
public class Actual : IActual { public string S { get; set; } }
Now there's nothing stopping you from calling Foo thus:
Foo();
The Actual class, after all, satisfies the IBase constraint.