Why does this implicit type conversion fail in C #?

Background:

Suppose I have the following class:

class Wrapped<T> : IDisposable { public Wrapped(T obj) { /* ... */ } public static implicit operator Wrapped<T>(T obj) { return new Wrapped<T>(obj); } public void Dispose() { /* ... */ } } 

As you can see, it provides an implicit type conversion operator for TWrapped<T> . Ultimately, I would like to use this class as follows:

 interface IX { /* ... */ } class X : IX { /* ... */ } ... IX plainIX = new X(); using (Wrapped<IX> wrappedIX = plainIX) { /* ... */ } 

Problem:

However, type conversion is not performed in the using clause above. Although I can assign new X() directly to wrappedIX , I am not allowed to assign it anything like IX . The compiler will complain about the following error:

Compiler Error CS0266: Unable to implicitly convert type 'IX' to 'Wrapped <IX>'. Explicit onversion exists (do you miss the role?)

I do not understand this. What is the problem?

+4
source share
1 answer

I believe because IX is an interface. The compiler believes that perhaps a value of type IX can already be obtained from Wrapped<IX> (even if Wrapped<T> sealed), so it does not use a conversion.

Details are quite complex in sections 6.4.3 and 6.4.4 of the C # 3.0 specification. Mostly because IX is an interface, it does not "encompass" any types, which means that the later step in 6.4.4 fails.

I suggest you create a non-generic Wrapped type with this method:

 public static Wrapped<T> Of<T>(T item) { return new Wrapped<T>(item); } 

Then you can simply write:

 using (Wrapped<IX> wrappedIX = Wrapped.Of(plainIX)) 

Mostly conversions can be a bit complicated for various reasons - simple methods are usually easier to understand, IMO.

+5
source

Source: https://habr.com/ru/post/1305246/


All Articles