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...
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
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With