Skip to content

Commit b65e99c

Browse files
Merge pull request #100 from DanielStout5/FixAnonymousTypeWrapperCast
Fix AnonymousTypeWrapper cast failing on lists of structs
2 parents ac0b735 + d6ca867 commit b65e99c

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

RazorEngineCore.Tests/TestCompileAndRun.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,24 @@ public async Task TestCompileAndRun_DynamicModel_PlainAsync()
157157
Assert.AreEqual("Hello Alex", actual);
158158
}
159159

160+
public struct Item
161+
{
162+
public string Name { get; set; }
163+
}
164+
165+
[TestMethod]
166+
public void TestCompileAndRun_StructList()
167+
{
168+
var eng = new RazorEngine();
169+
var model = new
170+
{
171+
Items = new[] { new Item { Name = "Bob" }, new Item { Name = "Alice" } }
172+
};
173+
var temp = eng.Compile("@foreach(var item in Model.Items) { @item.Name }");
174+
var result = temp.Run(model);
175+
Assert.AreEqual("BobAlice", result);
176+
}
177+
160178
[TestMethod]
161179
public void TestCompileAndRun_DynamicModel_Nested()
162180
{

RazorEngineCore/AnonymousTypeWrapper.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,6 @@ public override bool TryGetMember(GetMemberBinder binder, out object result)
3939
result = new AnonymousTypeWrapper(result);
4040
}
4141

42-
bool isEnumerable = typeof(IEnumerable).IsAssignableFrom(type);
43-
4442
if (result is IDictionary dictionary)
4543
{
4644
List<object> keys = new List<object>();
@@ -58,9 +56,9 @@ public override bool TryGetMember(GetMemberBinder binder, out object result)
5856
}
5957
}
6058
}
61-
else if (isEnumerable && !(result is string))
59+
else if (result is IEnumerable enumer && !(result is string))
6260
{
63-
result = ((IEnumerable<object>)result)
61+
result = enumer.Cast<object>()
6462
.Select(e =>
6563
{
6664
if (e.IsAnonymous())

0 commit comments

Comments
 (0)