Given the class:
public class Foo
{
public string Name { get; set; }
}
Is it possible to have a Foo instance created from a string through Convert.ChangeType:
Type type = typeof(Foo);
object value = "one";
value = System.Convert.ChangeType(value, type);
This is how a 3rd party API is attempting to rebuild objects. Someone mentioned this is possible with implicit operators, but from my understanding that will let me do the following, not create the object:
Foo foo = new Foo() { Name = "one" };
string fooAsString = foo; // implicit conversion -- no cast needed
Is there a way to create the object this way? Also, I do have the ability to change the Convert.ChangeType if there is another way to do this.
Update:
The reason I am asking is because it throws and exception:
Invalid cast from ‘System.String’ to
‘JibbaJabba+Foo’.
and adding the operator did not resolve the issue.
According to the MSDN documentation:
Looking at theIConvertibleinterface, it has aToTypemethod. 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
stringto aFoo. Since thestringtype (obviously) does not define a conversion toFooin itsIConvertibleimplementation, 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.ChangeTypein Reflector. It’s long; I won’t reproduce it here. But basically it’s doing as the documentation says: it only works if:valueparameter is a non-null instance of a type that implementsIConvertible, or:valueparameter and theconversionTypeparameter 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 usesToTypeas a fallback.So, we need to look at the
stringtype’s implementation ofToType.Sadly, it is one unfortunate line:
What does
DefaultToTypedo? Exactly the same thing asChangeType(minus theToTypefallback, 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.ChangeTypebehind 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:Converter<string, T>orFunc<string, T>delegate parameter, as suggested by Ben Voigt in a comment.TypeConverterparameterIParser<T>Anyway, best of luck.