Skip to content

Commit

Permalink
Init field only on first execution (#631)
Browse files Browse the repository at this point in the history
* Init field only on first execution

* Test demonstrating issue #629

Co-authored-by: Boris Breidenbach <boris.breidenbach@aquantec.de>
  • Loading branch information
BBreiden and Boris Breidenbach authored Oct 23, 2022
1 parent 3703828 commit c1a9771
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 9 deletions.
22 changes: 13 additions & 9 deletions src/System.Linq.Dynamic.Core/DynamicClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,28 @@ namespace System.Linq.Dynamic.Core;
/// </summary>
public abstract class DynamicClass : DynamicObject
{
private readonly Dictionary<string, object?> _propertiesDictionary = new();
private Dictionary<string, object?>? _propertiesDictionary = null;

private Dictionary<string, object?> Properties
{
get
{
foreach (PropertyInfo pi in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
if (_propertiesDictionary == null)
{
int parameters = pi.GetIndexParameters().Length;
if (parameters > 0)
_propertiesDictionary = new();
foreach (PropertyInfo pi in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
// The property is an indexer, skip this.
continue;
int parameters = pi.GetIndexParameters().Length;
if (parameters > 0)
{
// The property is an indexer, skip this.
continue;
}

_propertiesDictionary.Add(pi.Name, pi.GetValue(this, null));
}

_propertiesDictionary.Add(pi.Name, pi.GetValue(this, null));
}

return _propertiesDictionary;
}
}
Expand Down
27 changes: 27 additions & 0 deletions test/System.Linq.Dynamic.Core.Tests.Net6/DynamicClassTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System.Collections.Generic;
using FluentAssertions;
using Xunit;

namespace System.Linq.Dynamic.Core.Tests
{
public class DynamicClassTest
{
[Fact]
public void GetPropertiesWorks()
{
// Arrange
var range = new List<object>
{
new { FieldName = "TestFieldName", Value = 3.14159 }
};

// Act
var rangeResult = range.AsQueryable().Select("new(FieldName as FieldName)").ToDynamicList();
var item = rangeResult.FirstOrDefault();

var call = () => item.GetDynamicMemberNames();
call.Should().NotThrow();
call.Should().NotThrow();
}
}
}

0 comments on commit c1a9771

Please sign in to comment.