C# Error CS0767 – Cannot inherit interface ‘{0}’ with the specified type parameters because it causes method ‘{1}’ to contain overloads which differ only on ref and out

C# Error

CS0767 – Cannot inherit interface ‘{0}’ with the specified type parameters because it causes method ‘{1}’ to contain overloads which differ only on ref and out

Reason for the Error & Solution

Cannot inherit interface with the specified type parameters because it causes method to contain overloads which differ only on ref and out

Example

The following sample generates CS0767:

// CS0767.cs (0,0)

using System;

namespace Stuff
{
    interface ISomeInterface<T, U>
    {
        void Method(ref Func<U, T> _);
        void Method(out Func<T, U> _);
    }

    class Explicit : ISomeInterface<int, int>
    {
        void ISomeInterface<int, int>.Method(ref Func<int, int> v) { v = _ => throw new NotImplementedException(); }
        void ISomeInterface<int, int>.Method(out Func<int, int> v) { v = _ => throw new NotImplementedException(); }
    }
}

In this example, implementing ISomeInterface<int,int> creates two Method overloads with the same type of parameter but differs only by ref/out. This effectively declares a class that would otherwise raise error CS0663:

    class BadClass 
    {
        void Method(ref Func<int, int> v) { v = _ => throw new NotImplementedException(); }
        void Method(out Func<int, int> v) { v = _ => throw new NotImplementedException(); }
    }

To correct this error

The simplest way to correct this error is to use different type arguments for ISomeInterface<T,U>, for example:

    class Explicit : ISomeInterface<int, long>
    {
        void ISomeInterface<int, long>.Method(ref Func<long, int> v) { v = _ => throw new NotImplementedException(); }
        void ISomeInterface<int, long>.Method(out Func<int, long> v) { v = _ => throw new NotImplementedException(); }
    }

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...