Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 206
Manish Basantani Avatar asked Dec 06 '22 22:12

Manish Basantani


1 Answers

This is restricted in C#. Read below.

http://msdn.microsoft.com/en-us/library/aa664464%28VS.71%29.aspx

A class or struct is permitted to declare a conversion from a source type S to a target type T provided all of the following are true:

...

Neither S nor T is object or an interface-type.

Also,

User-defined conversions are not allowed to convert from or to interface-types. In particular, this restriction ensures that no user-defined transformations occur when converting to an interface-type, and that a conversion to an interface-type succeeds only if the object being converted actually implements the specified interface-type.

like image 113
Priyank Avatar answered Dec 28 '22 22:12

Priyank