Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implicitly casting a generic<T> back to T

If I write a generic class like class MyGeneric<T> is it possible to write an implicit cast to type T, so I can do stuff like:

public class MyGeneric<T>
{
...
}

public class GenericProperties
{
   public MyGeneric<string> MyGenericString {get;set;}

   public void UseMyGeneric()
   {
       string sTest = MyGenericString;
       MyGenericString = "this is a test";
   }
}

Is it possible to do that by overloading operators? I know it could be done if my class wasn't a generic...

like image 648
Jeremy Avatar asked Jan 06 '10 00:01

Jeremy


3 Answers

yep..but don't over-do it, this tends to confuse people. i would only use it for wrapper types.

class Wrapper<T>
{
    public T Value {get; private set;}
    public Wrapper(T val) {Value = val;}

    public static implicit operator T(Wrapper<T> wrapper) {return wrapper.Value;}
    public static implicit operator Wrapper<T>(T val) {return new Wrapper<T>(val);}
}



var intWrapper = new Wrapper<int>(7);
var usingIt = 7 * intWrapper; //49

Wrapper<int> someWrapper = 9; //woohoo
like image 163
dan Avatar answered Oct 22 '22 16:10

dan


Well, yes, but for the love of zombie jesus do NOT do that. It's really confusing. You're slightly misunderstanding the purpose of generics, I think. It's not used to "turn" a class into that type, it's used to have that type (MyGenericString) be 'aware' of the type you want, for various purposes (typically those are collection-based purposes).

like image 36
Noon Silk Avatar answered Oct 22 '22 16:10

Noon Silk


As others have said, that is legal but dangerous. There are many pitfalls you can fall into. For example, suppose you defined a user-defined conversion operator between C<T> and T. Then you say

C<object> c = new C<object>("hello");
object o = (object) c;

What happens? does your user-defined conversion run or not? No, because c is already an object.

Like I said, there are crazy situations you can get into when you try to define generic conversion operators; do not do it unless you have a deep and detailed understanding of section 10.10.3 of the specification.

like image 21
Eric Lippert Avatar answered Oct 22 '22 16:10

Eric Lippert