I'd like to automatically wrap a value in a generic container on return (I am aware that this is not always desirable, but it makes sense for my case). For example, I'd like to write:
public static Wrapper<string> Load() {
return "";
}
I'm able to do this by adding the following to my Wrapper class:
public static implicit operator Wrapper<T>(T val) {
return new Wrapper<T>(val);
}
Unfortunately, this fails when I attempt to convert an IEnumerable
, complete code here (and at ideone):
public class Test {
public static void Main() {
string x = "";
Wrapper<string> xx = x;
string[] y = new[] { "" };
Wrapper<string[]> yy = y;
IEnumerable<string> z = new[] { "" };
Wrapper<IEnumerable<string>> zz = z; // (!)
}
}
public sealed class Wrapper<T> {
private readonly object _value;
public Wrapper(T value) {
this._value = value;
}
public static implicit operator Wrapper<T>(T val) { return new Wrapper<T>(val); }
}
The compilation error I get is:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<string>' to '...Wrapper<System.Collections.Generic.IEnumerable<string>>'
What exactly is going on, and how can I fix it?