Given this class:
public class Wrapper<T>
{
public Wrapper(T value)
{
Value = value;
}
public T Value { get; }
public static implicit operator Wrapper<T>(T value)
{
return new Wrapper<T>(value);
}
}
This code snippet doesn't compile:
IEnumerable<int> value = new [] { 1, 2, 3 };
Wrapper<IEnumerable<int>> wrapper = value;
error CS0266: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable< int>' to 'Spikes.Implicit.Wrapper< System.Collections.Generic.IEnumerable< int>>'. An explicit conversion exists (are you missing a cast?)
But the compiler is perfectly happy with this:
Wrapper<IEnumerable<int>> wrapper = new [] { 1, 2, 3 };
Why?
The C# Language Specification states this clearly:
Section 6.4.1 Permitted user-defined conversions
For a given source type S and target type T, if S or T are nullable types, let S0 and T0 refer to their underlying types, otherwise S0 and T0 are equal to S and T respectively. A class or struct is permitted to declare a conversion from a source type S to a target type T only if all of the following are true:
- S0 and T0 are different types.
- Either S0 or T0 is the class or struct type in which the operator declaration takes place.
- Neither S0 nor T0 is an interface-type.
- Excluding user-defined conversions, a conversion does not exist from S to T or from T to S.
Your case violates point 3 of the conditions. The source type is an interface!
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