Is it possible to define valid C# interface that cannot be implemented?
This trivia question is not a good fit for StackOverflow, but what the heck, it is easily answered. (Wrongly, as it turns out! Read on!)
class C
{
private C() {}
}
interface IFoo where T : C, new()
{
}
IFoo
cannot be implemented for any T
because there is no type argument that can be substituted for T
. C
doesn't work because C
does not have a public parameterless constructor, and there can be no derived class of C
because the default constructor is private. (Well, there could be an accessible derived class of C
inside C
, but there isn't in this case.)
UPDATE: Commenter "mike z" correctly points out that
class X : IFoo where T : C, new() {}
implements the interface, though of course now there is no way to instantiate X
!
Even better, user "GranBurguesa" points out that a derived class of C is permitted to be declared, just so long as it never calls the private constructor; this is only possible if it crashes and dies on instantiation. (Well, to be picky, it would also be permitted for the recursive calls to be optimized down to an infinite loop instead of a crash.)
Both devious workarounds pose a philosophical question: if an interface is implemented by a class no one can instantiate, is it really implemented? Of course GranBurguesa demonstrates that IFoo
can be implemented and constructed, so my answer is actually wrong.
There are also cases, such as the one hinted at in SLaks' deleted answer, in which an abuse of the generic mechanism leads to an "infinitary" type. Such types are not legal in the CLR; the C# design team has considered adding similar language to the C# compiler spec but hasn't gotten around to it yet. Use of these types can crash the compiler or the runtime.
For an example of an infinitary type that crashes the compiler, see my article:
To Infinity But Not Beyond
Here's one. Cut n paste this code into Visual Studio and you'll see that this interface cannot be implemented:
interface ΙAmAPerfectlyOrdinaryInterface { }
class C : IAmAPerfectlyOrdinaryInterface { }