Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit cacb438

Browse files
committed
Add support for mapping BCL types directly
1 parent 1a85598 commit cacb438

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/ServiceStack.Text/AutoMappingUtils.cs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,16 @@ public static class AutoMappingUtils
2121
{
2222
public static T ConvertTo<T>(this object from)
2323
{
24+
if (from.GetType() == typeof(T))
25+
{
26+
return (T)from;
27+
}
28+
29+
if (from.GetType().IsValueType)
30+
{
31+
return (T)Convert.ChangeType(from, typeof(T));
32+
}
33+
2434
if (typeof(IEnumerable).IsAssignableFromType(typeof(T)))
2535
{
2636
var listResult = TranslateListWithElements.TryTranslateCollections(
@@ -750,7 +760,7 @@ public static PropertyGetterDelegate CreateTypeConverter(Type fromType, Type toT
750760
}
751761
}
752762

753-
internal class TypeConverter<From, To>
763+
internal class TypeConverter<From, To>
754764
{
755765
static TypeConverter()
756766
{

tests/ServiceStack.Text.Tests/AutoMappingTests.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,16 @@ public void Does_translate_to_inherited_propeties()
303303
Assert.That(to.Car.Age, Is.EqualTo(user.Car.Age));
304304
}
305305

306+
[Test]
307+
public void Can_convert_BclTypes()
308+
{
309+
Assert.That("from".ConvertTo<string>(), Is.EqualTo("from"));
310+
Assert.That(1.ConvertTo<long>(), Is.EqualTo(1L));
311+
Assert.That(2L.ConvertTo<int>(), Is.EqualTo(2));
312+
Assert.That(3.3d.ConvertTo<float>(), Is.EqualTo(3.3f));
313+
Assert.That(4.4d.ConvertTo<decimal>(), Is.EqualTo(4.4m));
314+
}
315+
306316
[Test]
307317
public void Does_coerce_from_BclTypes_to_strings()
308318
{

0 commit comments

Comments
 (0)