Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# why can't I pass "base" interface by ref?

I want to know why this is a compile error, in order to understand the C# language better.

In my code I have an interface (IMyInterface) that derives from IDisposable. I have another method that takes a param of type 'ref IDisposable'. But I cannot pass a member var of type IMyInterface to that method. Here is my example code below:

using System;

namespace CompileErrorBaseInterface
{
    public interface IMyInterface : IDisposable { }

    class Program
    {
        private IMyInterface _myInterfaceObj;

        static void Main(string[] args) { }

        public void ExampleMethod()
        {
            MyMethodBaseInterface(ref _myInterfaceObj); //compile error
            MyMethodDerivedInterface(ref _myInterfaceObj); //no compile error
        }

        private void MyMethodBaseInterface(ref IDisposable foo) { }

        private void MyMethodDerivedInterface(ref IMyInterface foo) { }
    }
}

The compile errors are:

  • Argument 1: cannot convert from 'ref CompileErrorBaseInterface.IMyInterface' to 'ref System.IDisposable' The best overloaded method match for
  • 'CompileErrorBaseInterface.Program.MyMethodBaseInterface(ref System.IDisposable)' has some invalid arguments

Can anyone explain why this is not allowed, or not possible for the compiler to do? I have a workaround using generics, so I just want to understand why it is not allowed to do it this way.

Thanks.

like image 350
PhoSho Avatar asked Mar 13 '23 18:03

PhoSho


1 Answers

Consider the following example:

private void MyMethod(ref IDisposable foo)
{
    // This is a valid statement, since SqlConnection implements IDisposable
    foo = new SqlConnection();
}

If you were allowed to pass an IMyInterface to MyMethod, you'd have a problem, since you just assigned an object of type SqlConnection (which does not implement IMyInterface) to a variable of type IMyInterface.

For more details, have a look at the following blog entry of C# guru Eric Lippert:

  • Why do ref and out parameters not allow type variation?
like image 92
Heinzi Avatar answered Mar 24 '23 21:03

Heinzi