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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...