Making my own type castable to string?

  • Thread starter Thread starter Kenneth Baltrinic
  • Start date Start date
K

Kenneth Baltrinic

I am implementing a class that routinely needs to be cast to and from a
string. I would love for some way to make the compiler realize that my
class can be cast to and from a string. Implementing a TypeConverter seems
like it is designed to do this kind of thing but it doesn't actually do it,
apparently. I have implemented a type convert for my class, applied the
[TypeConverter...] attribute to my class but any attempt to do
(string)VarOfMyClass or (MyClass)StringVar won't compile.

Is this something that just can't be done?

--Ken
 
Kenneth said:
Is this something that just can't be done?

Try something like this:

public static implicit operator string(MyType rh)
{
// if the variable is already a string, skip the ToString call;
return rh.SomeVariable.ToString();
}

That's from memory so the signature may be off. Make sure and double check
it. As for explicit versus implicit, that's pretty much a stylistic issue.
However, if there's any possibility that casting can throw an exception,
the docs recommend you go with an explicit cast.

Last but not least, you could always just override ToString(). I guess it
all depends on just how interoperable you need your type to be with the
string class.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
 
Back
Top