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();
}
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With