Skip to content
Sergey Morenko edited this page Apr 12, 2015 · 3 revisions

TinyMapper supports TypeConverter

The sample shows how to map SourceClass to TargetClass:

public class TargetClass
{
	public string FullName { get; set; }
}

public class SourceClass
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
}

1 Create custom type converter

public sealed class SourceClassConverter : TypeConverter
{
	public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
	{
		return destinationType == typeof(TargetClass);
	}

	public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
	{
		var concreteValue = (SourceClass)value;
		var result = new TargetClass
		{
			FullName = string.Format("{0} {1}", concreteValue.FirstName, concreteValue.LastName)
		};
		return result;
	}
}

Here's additional sample

2 Register the type converter

Thru attribute

[TypeConverter(typeof(SourceClassConverter))]
public class SourceClass
{
	public string FirstName { get; set; }
	public string LastName { get; set; }
}

or code

TypeDescriptor.AddAttributes(typeof(SourceClass), new TypeConverterAttribute(typeof(SourceClassConverter)));

3 The last

TinyMapper.Bind<SourceClass, TargetClass>();
var source = new SourceClass
{
	FirstName = "John",
	LastName = "Doe"
};

var result = TinyMapper.Map<TargetClass>(source);