Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to explicitly implement an interface member of type object when the member has already been implemented with another type?

Consider the following example:

namespace Test
{
    interface IContract : IContract<object> { }

    interface IContract<T>
    {
        void Definition(T data);
    }

    public class SomeClass : IContract, IContract<SomeContractClass>
    {
        public void Definition(SomeContractClass data)
        {
            // ...
        }
    }

    public class SomeContractClass { }
}

I thought I would have satisfied the interface by supplying Definition(SomeContractClass data) since as stated in MDSN:

In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.

But instead the compiler asks me to define it explicitly:

Error 1 'Test.SomeClass' does not implement interface member 'Test.IContract.Definition(object)'

like image 547
Phil Cooper Avatar asked Dec 21 '22 09:12

Phil Cooper


1 Answers

You are implementing the interface IContract.

If we flatten the inheritance heirarchy, we can see that IContract essentially looks like this:

interface IContract
{
    void Definition(object data);
}

You do not supply a method matching the signature void Definition (object data) - the method you supply takes a SomeContractClass instead. Therefore, you get the stated error message.

However, I think the underlying issue is that your class implements both IContract and IContract<T> (which is the same as saying IContract<object> and IContract<T>). I think your design needs some work...

like image 51
RB. Avatar answered May 19 '23 18:05

RB.