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:
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With