c# - Implicitly converting a generic to a wrapper -
i'd automatically wrap value in generic container on return (i aware not desirable, makes sense case). example, i'd write:
public static wrapper<string> load() { return ""; }
i'm able adding following wrapper class:
public static implicit operator wrapper<t>(t val) { return new wrapper<t>(val); }
unfortunately, fails when attempt convert 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 is:
cannot implicitly convert type 'system.collections.generic.ienumerable<string>' '...wrapper<system.collections.generic.ienumerable<string>>'
what going on, , how can fix it?
the reason part of c# spec, noted in answer:
a class or struct permitted declare conversion source type s target type t provided of following true:
- ...
- neither s nor t
object
or interface-type.and
user-defined conversions not allowed convert or interface-types. in particular, restriction ensures no user-defined transformations occur when converting interface-type, , conversion interface-type succeeds if object being converted implements specified interface-type.
your implicit conversion works when used differently, in following code:
using system; using system.collections.generic; public class wrapper<t> { public t val { get; private set; } public wrapper(t val) { val = val; } public static implicit operator wrapper<t>(t val) { return new wrapper<t>(val); } } public class test { public static wrapper<ienumerable<int>> getit() { // array typed int[], not ienumerable<int>, // implicit operator can used. return new int[] { 1, 2, 3 }; } public static void main() { // prints 1, 2, 3 foreach (var in getit().val) { console.writeline(i); } } }
the specific issue you're running because store array in ienumerable<string>
local variable before returning it. it's type of variable passed implicit operator matters: because source type s
ienumerable<int>
on local variable, operator can't used. int[]
isn't interface, works.
Comments
Post a Comment