I have a generic class X<T>
; This class has a covariant part that I want to be able to access covariantly. So I factor it out into an interface IX<out T>
. However, I want this interface to be visible only to the class itself, because it contains also methods that are ment to be private
.
I.e., inside the class itself, I can upcast to IX<T>
and use it covariantly. E.g.:
class X<T> : IX<T> {
private interface IX<out T>{ // the private covariant interface
void foo();
}
// It grants access to the private method `foo`
private T foo(){...}
public T IX.foo(){ return foo(); }
private static void someMethod(IX<T> x) {
// Here I can use `x` covariantly
}
}
Is this possible? I have never heard of private
nested interfaces before, since a private interface usually makes no sence at all. However, with generics such an interface becomes necessary for implementing "private-only covariance".
When I try to compile this, I receive the following error:
foo.cs(1,14): error CS0246: The type or namespace name `IX' could not be found. Are you missing an assembly reference?
foo.cs(9,14): error CS0305: Using the generic type `X<T>.IX<S>' requires `1' type argument(s)
Which is basically clear, an inner type of a generic type needs a type parameter for the outer type. Is there a way to get this code to compile correctly?