Andrey Andrey - 3 months ago 7
C# Question

Interface for method that returns its own type

I have a situation where i have a class

class Foo
{
Foo Bar()
{
return new Foo();
}
}


Now i wan tot create an interface for it

class IFoo
{
??? Bar();
}


What should be in place of the question marks? Each class should return it's own type, not Foo.

The solutions below work but do not looks clean. I don't understand why i have to specify the same class twice, and there is nothing like "this" for the current type

This is how i am using it later

class GenericClass<T> where T : IFoo
{
T foo = new T();
T item = foo.Bar();
}

Answer

You ask:

The solutions below work but do not looks clean. I don't understand why i have to specify the same class twice, and there is nothing like "this" for the current type

The reason why you have to specify it twice is because C# lacks the feature that you need. What you want is something like this:

interface IFoo
{
    IFoo Bar();
}

class Foo : IFoo
{
    Foo Bar() // should work since Foo is an IFoo, but it's not supported by C#
    {
        return new Foo();
    }
}

From a type-safety point of view, this should work (it's called return type covariance). In fact, other programming languages such as C++ or Java support this, see this example on Wikipedia. Unfortunately, return type covariance is not supported by C# (not even C# 4.0, which introduced covariance for generics), which is why you have to use the "generics workaround" illustrated in the other answers.

Covariant return types as well as a "this" type are proposed features for new versions of C#:

Comments