How to properly return T from a generic method while implimenting an interface?

I am working through a bug. In recreating the bug for the following sample I was able to determine why the problem is happening. But I am stuck for a better solution. So given the following program:

I was expecting the output to be:

But what I am getting is:

Seeing the problem simplified like this it is obvious that Bar.OutputType isn’t overriding Foo.OutputType. What are my best options for improving this design?
Bar.OutputType can’t override Foo.OutputType because the signatures are different. Changing the signature of Bar.OutputType to match Foo.OutputType won’t work because then Bar won’t be implimenting IFoo.

Asked on April 7, 2016 in C#.
Add Comment
1 Answer(s)

I am not certain what it is you are wanting to accomplish in the end but would this help?

If you add a Generic to what ever implements IFoo then you can specify the type when the derived object is created…

public class Foo<TFoo> : IFoo<TFoo>


//Then you code would allow this...
//Again other then returning Bar both times I am not certain exactly what you are 
//wanting to accomplish But specifying the type at create will allow you to return Bar 
//even if you created a Foo or a Bar...

class Program {
    static void Main(string[] args) {
        Foo foo = new Foo<Bar>();

    static void CallOutputType<T>(T t) where T : Foo {
Answered on April 7, 2016.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.