c# - implicit operator on generic types -


is there wrong using implicit operator following:

//linqpad c# program example void main() {     var testobject = new myclass<int>() { value = 1 };      var add = 10 + testobject; //implicit conversion int here     add.dump(); // 11 }  class myclass<t> {     public t value { get; set; }     public static implicit operator t (myclass<t> myclasstoconvert)     {         return myclasstoconvert.value;     } } 

i thinking treat instance of object value type way, seeing i've never seen example of thought maybe there reason not point out?

in actual code thinking of doing part of data abstraction layer, return objects information describing underlying data, allow logic code treat value type when needs know value, , @ same time keep nice , type safe generics.

if of following true:

  • all possible values of myclass<t> type (including null if it’s not value type!) map valid value of t

  • the implicit operator never throws (not null!)

  • the implicit conversion makes semantic sense , not confusing client programmer

then there nothing wrong this. of course could of these 3 things, bad design. in particular, implicit operator throws can hard debug because place called doesn’t being called.

for example, consider t? has no implicit conversion t (where t is, of course, value type). if there such implicit operator, have throw when t? null, there no obvious value convert null make sense any value type t.


let me give example had trouble debugging issue implicit operator threw:

public string foo() {     return some_condition ? getsomething() : null; } 

here, getsomething returned of type wrote has user-defined implicit conversion string. made absolutely sure getsomething never return null, , yet got nullreferenceexception! why? because above code not equivalent to

return some_condition ? (string)getsomething() : (string)null; 

but to

return (string)(some_condition ? getsomething() : (something)null); 

now can see null came from!


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -