Implementing an interface with a return type that implements the required return type

Why can't I do this?

IHasOperatingSystem {
IOperatingSystem OperatingSystem { get; }
} 

Computer<T> : IHasOperatingSystem where T : IOperatingSystem {
public T OperatingSystem { get; }
}

It's telling me that the type should be IOperatingSystem, but if T implements IOperatingSystem, shouldn't that be sufficient?

Also, I realize that the title to this question might be a little confusing, but I couldn't think of a better way to phrase it.

Jon Skeet
people
quotationmark

It's telling me that the type should be IOperatingSystem, but if T implements IOperatingSystem, shouldn't that be sufficient?

No. That's just not the way C# works. In order to implement an interface, or override a method, the parameter types and the return type have to match exactly. From section 13.4.4 of the C# 5 specification:

For purposes of interface mapping, a class member A matches an interface member B when:

  • A and B are methods, and the name, type, and formal parameter lists of A and B are identical.
  • ...

(Here "type" should be read as "return type".)

Now you could make your IHasOperatingSystem type generic, of course:

public interface IHasOperatingSystem<T> where T : IOperatingSystem
{
    T OperatingSystem { get; }
}

public class Computer<T> : IHasOperatingSystem<T> where T : IOperatingSystem
{
    public T OperatingSystem { get { ... } }
}

Or alternatively you could use explicit interface implementation in the Computer<T> class:

public interface IHasOperatingSystem
{
    IOperatingSystem OperatingSystem { get; }
} 

public class Computer<T> : IHasOperatingSystem where T : IOperatingSystem
{
    // Explicit interface implementation...
    IHasOperatingSystem.OperatingSystem IOperatingSystem
    {
        // Delegate to the public property
        get { return OperatingSystem; }
    }

    public T OperatingSystem { get { ... } };
}

people

See more on this question at Stackoverflow