Skip to content

Commit c1a9771

Browse files
BBreidenBoris Breidenbach
and
Boris Breidenbach
authored
Init field only on first execution (#631)
* Init field only on first execution * Test demonstrating issue #629 Co-authored-by: Boris Breidenbach <[email protected]>
1 parent 3703828 commit c1a9771

File tree

2 files changed

+40
-9
lines changed

2 files changed

+40
-9
lines changed

src/System.Linq.Dynamic.Core/DynamicClass.cs

+13-9
Original file line numberDiff line numberDiff line change
@@ -18,24 +18,28 @@ namespace System.Linq.Dynamic.Core;
1818
/// </summary>
1919
public abstract class DynamicClass : DynamicObject
2020
{
21-
private readonly Dictionary<string, object?> _propertiesDictionary = new();
21+
private Dictionary<string, object?>? _propertiesDictionary = null;
2222

2323
private Dictionary<string, object?> Properties
2424
{
2525
get
2626
{
27-
foreach (PropertyInfo pi in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
27+
if (_propertiesDictionary == null)
2828
{
29-
int parameters = pi.GetIndexParameters().Length;
30-
if (parameters > 0)
29+
_propertiesDictionary = new();
30+
foreach (PropertyInfo pi in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
3131
{
32-
// The property is an indexer, skip this.
33-
continue;
32+
int parameters = pi.GetIndexParameters().Length;
33+
if (parameters > 0)
34+
{
35+
// The property is an indexer, skip this.
36+
continue;
37+
}
38+
39+
_propertiesDictionary.Add(pi.Name, pi.GetValue(this, null));
3440
}
35-
36-
_propertiesDictionary.Add(pi.Name, pi.GetValue(this, null));
3741
}
38-
42+
3943
return _propertiesDictionary;
4044
}
4145
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using System.Collections.Generic;
2+
using FluentAssertions;
3+
using Xunit;
4+
5+
namespace System.Linq.Dynamic.Core.Tests
6+
{
7+
public class DynamicClassTest
8+
{
9+
[Fact]
10+
public void GetPropertiesWorks()
11+
{
12+
// Arrange
13+
var range = new List<object>
14+
{
15+
new { FieldName = "TestFieldName", Value = 3.14159 }
16+
};
17+
18+
// Act
19+
var rangeResult = range.AsQueryable().Select("new(FieldName as FieldName)").ToDynamicList();
20+
var item = rangeResult.FirstOrDefault();
21+
22+
var call = () => item.GetDynamicMemberNames();
23+
call.Should().NotThrow();
24+
call.Should().NotThrow();
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)