I've been searching high and low for a TypeConverter for Types and only found private or internal implementations.
It wasn't a hard task, but I think that the .NET Framework should provide one out of the box.
Here is the one I wrote:
/// <summary>
/// Provides a type converter to convert <see cref="T:System.Type"/> objects to and from various other representations.
/// </summary>
public class TypeTypeConverter : System.ComponentModel.TypeConverter
{
/// <summary>
/// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
/// </summary>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"></see> that provides a format context.</param>
/// <param name="sourceType">A <see cref="T:System.Type"></see> that represents the type you want to convert from.</param>
/// <returns>
/// true if this converter can perform the conversion; otherwise, false.
/// </returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return ((sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType));
}
/// <summary>
/// Converts from.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="culture">The culture.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
Type type = Type.GetType((string)value);
if (type == null)
{
throw new ArgumentException("Type not found.", "value");
}
return type;
}
return base.ConvertFrom(context, culture, value);
}
/// <summary>
/// Returns whether this converter can convert the object to the specified type, using the specified context.
/// </summary>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"></see> that provides a format context.</param>
/// <param name="destinationType">A <see cref="T:System.Type"></see> that represents the type you want to convert to.</param>
/// <returns>
/// true if this converter can perform the conversion; otherwise, false.
/// </returns>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return ((destinationType == typeof(string)) || base.CanConvertTo(context, destinationType));
}
/// <summary>
/// Converts to.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="culture">The culture.</param>
/// <param name="value">The value.</param>
/// <param name="destinationType">Type of the destination.</param>
/// <returns></returns>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType != typeof(string))
{
return base.ConvertTo(context, culture, value, destinationType);
}
return ((Type)value).AssemblyQualifiedName;
}
}