Given the class:
public class Foo
{
public string Name { get; set; }
}
Is it possible to have a Foo instance created from a string thro
An implicit operator won't work here? If Foo is a class you can modify then I've used something like this in the past, which also allows you to compare Foo instances to a string.
public class Foo
{
public string Name { get; set; }
public static implicit operator Foo(string value)
{
return new Foo { Name = value };
}
}
...
Foo foo = "fooTest";
Console.WriteLine("Foo name: {0}", foo.Name);
...
Edit: If you must use ChangeType then as far as I know you're out of luck. If you can modify the API to use a TypeConverter, you can use something like the following.
...
Type type = typeof(Foo);
object value = "one";
var converter = TypeDescriptor.GetConverter(type);
if (converter.CanConvertFrom(value.GetType()))
{
object newObject = converter.ConvertFrom(value);
Console.WriteLine("Foo value: {0}", newObject.ToString());
}
...
public class FooConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
var name = value as string;
if (name != null)
return new Foo { Name = name };
else
return base.ConvertFrom(context, culture, value);
}
}
[TypeConverter(typeof(FooConverter))]
public class Foo
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}