Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 253
Andrey Avatar asked Jun 15 '10 13:06

Andrey


1 Answers

You could add a generic type and constrain it using the interface type:

public interface IFoo<T>
{
    T Bar();
}

You'd implement this as follows:

public class Foo : IFoo<Foo>
{
    public Foo Bar()
    {
        return new Foo();
    }
}

public class Cheese : IFoo<Cheese>
{
    public Cheese Bar()
    {
        return new Cheese();
    }
}

Update, if you never care about the concrete return type of Foo, then you can do the following:

public interface IFoo
{
    IFoo Bar();
}

Which is implemented like:

public class Foo : IFoo
{
    public IFoo Bar()
    {
        return new Foo();
    }
}

Then in your generic class:

public class GenericClass<T> where T : class, IFoo, new()
{
    public T Rar()
    {
        T foo = new T();
        T item = foo.Bar() as T;
        return item;
    }
}

GenericClass<Foo>.Rar(); will be a concrete implementation of Foo.

like image 157
djdd87 Avatar answered Oct 21 '22 13:10

djdd87