Notbad
Notbad

Reputation: 6296

implementing a generic interface that inherits from a non generic one

I know how to implement a generic interface that inherits form a non generic one, but there's something I do not understand in this process:

Why the non generic interface method must not be declared as public in the class implementing the interfaces?.

An example:

    interface InputTestSocket
    {
        object GetValue();
    }

    interface InputTestSocket<T> : InputTestSocket
    {
        new T GetValue();
    }

    class FloatInputSocketValues : InputTestSocket<float>
    {
        IFloatConvertable _output;
        public void SetConvertable(IFloatConvertable output) { _output = output; }

        //If I make this method public it won't compile. Musn't all interfaces be public?
        object InputTestSocket.GetValue() { return null; }

        public float GetValue() { return _output.ToFloat(); }
    }

Upvotes: 4

Views: 231

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391664

That's called explicit implementation of an interface. You do that when you won't (or can't) expose the members as instance members on the concrete type, but only make them available through the interface.

The reason the compiler complains with this:

CS0111 Type 'FloatInputSocketValues' already defines a member called 'GetValue' with the same parameter types

is that you cannot differ between two members by their return types only, and if you make the method public you would have:

//If I make this method public it won't compile. Musn't all interfaces be public?
public object GetValue() { return null; }

public float GetValue() { return _output.ToFloat(); }

and these two differ by their return type only.

So you can't do that.

The reason you can't do that is that when the compiler tries to determine which method you want to call when you do this:

something.GetValue()

is that it doesn't consider the return type at all. The compiler thus tells you that there is no way you could ever call this method because it would be ambiguous, and thus it doesn't allow you to do that.

This has nothing to do with generics or inheritance though, you would get the exact same problem with this smaller example:

interface ITest
{
    object GetValue();
}

public class Test : ITest
{
    public object GetValue() { return null; }

    // just a public method on our class
    public float GetValue() { return 0.0f; }
}

Upvotes: 3

Related Questions