Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Init field only on first execution #631

Merged
merged 2 commits into from
Oct 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}
}
}