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

Commit

Permalink
Add support for converting between covariant collections
Browse files Browse the repository at this point in the history
  • Loading branch information
mythz committed Aug 2, 2015
1 parent deecbc0 commit 3c7724e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/ServiceStack.Text/TranslateListWithElements.cs
Expand Up @@ -96,6 +96,15 @@ public static object TryTranslateCollections(Type fromPropertyType, Type toPrope
fromValue, toPropertyType, varArgs.Args1[0]);
}

var fromElType = fromPropertyType.GetCollectionType();
var toElType = toPropertyType.GetCollectionType();

if (fromElType == null || toElType == null)
return null;

if (fromElType == typeof(object) || toElType.IsAssignableFromType(fromElType))
return TranslateToGenericICollectionCache(fromValue, toPropertyType, toElType);

return null;
}

Expand Down Expand Up @@ -176,21 +185,21 @@ public static IList TranslateToIList(IList fromList, Type toInstanceOfType)
if (toInstanceOfType.IsArray)
{
var result = TranslateToGenericICollection(
(ICollection<T>)fromList, typeof(List<T>));
(IEnumerable)fromList, typeof(List<T>));
return result.ToArray();
}

return TranslateToGenericICollection(
(ICollection<T>)fromList, toInstanceOfType);
(IEnumerable)fromList, toInstanceOfType);
}

public static ICollection<T> TranslateToGenericICollection(
ICollection<T> fromList, Type toInstanceOfType)
IEnumerable fromList, Type toInstanceOfType)
{
var to = (ICollection<T>)CreateInstance(toInstanceOfType);
foreach (var item in fromList)
{
to.Add(item);
to.Add((T)item);
}
return to;
}
Expand Down
24 changes: 24 additions & 0 deletions tests/ServiceStack.Text.Tests/AutoMappingTests.cs
Expand Up @@ -598,6 +598,30 @@ public void Does_convert_from_ValueType_to_strings()

Assert.That(new DateTime(2001, 01, 01).ConvertTo<string>(), Is.EqualTo("2001-01-01"));
}

[Test]
public void Can_convert_from_List_object()
{
var from = 3.Times(i => (object)new Car { Age = i, Name = "Name" + i });
var to = (List<Car>)TranslateListWithElements.TryTranslateCollections(
typeof(List<object>), typeof(List<Car>), from);

Assert.That(to.Count, Is.EqualTo(3));
Assert.That(to[0].Age, Is.EqualTo(0));
Assert.That(to[0].Name, Is.EqualTo("Name0"));
}

[Test]
public void Can_convert_from_List_SubType()
{
var from = 3.Times(i => new SubCar { Age = i, Name = "Name" + i });
var to = (List<Car>)TranslateListWithElements.TryTranslateCollections(
typeof(List<SubCar>), typeof(List<Car>), from);

Assert.That(to.Count, Is.EqualTo(3));
Assert.That(to[0].Age, Is.EqualTo(0));
Assert.That(to[0].Name, Is.EqualTo("Name0"));
}
}

public class Test
Expand Down

0 comments on commit 3c7724e

Please sign in to comment.