According to the MSDN documentation:
For the conversion to succeed, value
must implement the IConvertible
interface, because the method simply
wraps a call to an appropriate
IConvertible method. The method
requires that conversion of value to
conversionType be supported.
Looking at the IConvertible
interface, it has a ToType
method. You could try that, maybe? (Disclaimer: I haven't. It's just a thought.)
Edit: In your case, it seems that you want to convert from a string
to a Foo
. Since the string
type (obviously) does not define a conversion to Foo
in its IConvertible
implementation, I believe you're out of luck.
Update: I don't want to suggest that this is how you should always approach this sort of problem, but...
I took a look at the code for Convert.ChangeType
in Reflector. It's long; I won't reproduce it here. But basically it's doing as the documentation says: it only works if:
- The
value
parameter is a non-null instance of a type that implements IConvertible
, or:
- The type of the
value
parameter and the conversionType
parameter are the same (so: Convert.ChangeType(myFoo, typeof(Foo))
would also work, though it'd be pretty useless).
Then, it cycles through all the types supported by IConvertible
(which obviously does not include any user-defined types) and ultimately uses ToType
as a fallback.
So, we need to look at the string
type's implementation of ToType
.
Sadly, it is one unfortunate line:
return Convert.DefaultToType(this, type, provider);
What does DefaultToType
do? Exactly the same thing as ChangeType
(minus the ToType
fallback, obviously to avoid infinite recursion).
So this just simply isn't going to work.
If you're absolutely tied to this 3rd party library that's using Convert.ChangeType
behind the scenes, I would recommend contacting the library's developer and asking them to extend their API in some way that will allow you to accomplish what you're trying to accomplish. Some possiblities might be:
- Accepting an optional
Converter<string, T>
or Func<string, T>
delegate parameter, as suggested by Ben Voigt in a comment.
- Accepting a
TypeConverter
parameter
- Accepting a parameter of some type that implements an interface like
IParser<T>
Anyway, best of luck.