c# - How do I do a nullable type constriant? -


let have following desire, simplify iconvertible's allow me call them using generic type parameter. plan creating generic converter , storing them on static property of static generic class. here code generate delegates::

static class iconvertiblehelper<t> t : struct, iconvertible {     public static readonly converter<iconvertible, t> converter;     public static readonly converter<iconvertible, t?> nullableconverter;     static iconvertiblehelper()     {         type type = typeof(t).isenum ? enum.getunderlyingtype(typeof(t)) : typeof(t);         converter = delegate.createdelegate(typeof(converter<iconvertible, t>), typeof(convert).getmethod("to" + type.name,new type[]{typeof(object)})) converter<iconvertible, t>;         nullableconverter = obj => obj == null ? default(t?) : (t?)converter(obj);     } } 

as aside, there small side effect of adding supports enum's inherit iconvertible , apparently conversion underylingtype enum implicit , required return type of delegate.

now, hard part done, want add extension methods:

 public static class iconvertiblehelper  {    public static t to<t>(this iconvertible convertible) t:struct,iconvertible    {     return iconvertiblehelper<t>.converter(convertible);    }    public static t? to<t?>(this iconvertible convertible) t : struct, iconvertible    {       return iconvertiblehelper<t>.nullableconverter(convertible);    }  } 

the first extension method fine, , works! second extension not compile @ all. can use following rather lame work around:

 public static t? tonullable<t>(this iconvertible convertible) t : struct, iconvertible  {   return iconvertiblehelper<t>.nullableconverter(convertible);  } 

but we're stuck requiring call different signature convert nullable value types. poorer workaround (for usability reasons,imo), use out or ref parameter return, , right 2 methods. technically allows type inference magic occur, makes calling simple little extension method more annoying.

sorry not allowed have nullable type within angle brackets isn't allowed. know lame, how compile works today. couldn't put concrete nullable type there either, example "bool?"

this requires either change method name or add parameters. sorry know not hopping not easy around compiler itself. tonullable workaround solution any.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -