Alex Rivera | Logout

Interface for method that returns its own type

Asked 2010-06-15T13:39:44.410
9

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();
}
Edit
Report

3 Answers

4

I think that the real question is: why you need the derived type in the interface? Interface is exactly for that reason - abstracting from the concrete classes. If it's just for convenience, so you don't have to cast to Foo after calling Bar(), you can implement the interface explicitly:

interface IFoo
{
    IFoo Bar();
}

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

    IFoo IFoo.Bar()
    {
        return Bar();
    }
}

Ask yourself the question: why do you introduce an interface when you want the concrete type?

answered 2010-06-15T14:07:51.770
0
public interface IFoo<T>
{
    T Bar();
}

Your implementation would then be:

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

class Baz : IFoo<Baz>
{
    Baz Bar()
    { 
        return new Baz(); 
    }
}
answered 2010-06-15T13:42:36.497
0

Not sure what you are trying to accomplish but it could be done this way:

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



   class Foo:IFoo<Foo>
    {

        #region IFoo<Foo> Members

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

        #endregion
    }

Or Like this:

    interface IFoo
    {
        IFoo Bar();
    }

class Foo : IFoo
    {

        #region IFoo Members

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

        #endregion
    }
answered 2010-06-15T13:49:08.103

Your Answer