Search code examples
c#castingimplicit-conversion

How to write Implicit Conversion from an Interface to another type?


I am trying to do something like below:

public class SomeWrapper : ISomeWrapper{

  public static implicit operator ActualRec(ISomeWrapper someWrapper)
        {
            return ((SomeWrapper)someWrapper).SomeInfo;
        }
}

But this code fails, saying: "Either parameter or return type must be of type SomeWrapper".

I Understand the problem that compiling is stating. But I need this type conversionb because throughout my application I am using ISomeWrapper as the variable, storing SomeWrapper instance. (Also, SomeWrapper is the only class implementing ISomeWrapper).

Is there any way to do the implicit conversion if ISomeWrapper interface to the type that i know in my concrete class?

Edit: As suggested by all, implicit casting from interface is not possible in C#.

The reason I need to do this? I want to allow (implicitly) to the user of ISomeWrapper to invoke methods that need ActualRec as the parameter WITHOUT giving access to the users of ISomeWrapper to call methods/properties of ActualRec.

For instance, If I include a property ActualRec in ISomeWrapper then users of ISomeWrapper would be able to call methods available in ActualRec ( Say, someWrapper.ActualRec.Dispose() ), which I DO NOT want to expose.

That's the reason for trying to find some implicit conversion.

Also, I do not want to user SomeWrapper across application.

Please suggest if there is some concept/pattern to get this done.

Thanks for your interest.


Solution

  • I would say there is a flaw in your design. You're casting to a concrete type from an interface, that makes the use of the interface pretty pointless. The interface is a contract through which implementing types will conform to provide a required set of services. In your example, is the SomeInfo property not defined in the interface (contract)? If not, why are you trying to cast using the interface at all? You should be using SomeWrapper as the input argument itself.