diff --git a/src/System.Linq.Dynamic.Core/DynamicClass.cs b/src/System.Linq.Dynamic.Core/DynamicClass.cs index e8651bd8..4498e4e8 100644 --- a/src/System.Linq.Dynamic.Core/DynamicClass.cs +++ b/src/System.Linq.Dynamic.Core/DynamicClass.cs @@ -18,24 +18,28 @@ namespace System.Linq.Dynamic.Core; /// public abstract class DynamicClass : DynamicObject { - private readonly Dictionary _propertiesDictionary = new(); + private Dictionary? _propertiesDictionary = null; private Dictionary 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; } } diff --git a/test/System.Linq.Dynamic.Core.Tests.Net6/DynamicClassTest.cs b/test/System.Linq.Dynamic.Core.Tests.Net6/DynamicClassTest.cs new file mode 100644 index 00000000..44e6b7ec --- /dev/null +++ b/test/System.Linq.Dynamic.Core.Tests.Net6/DynamicClassTest.cs @@ -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 + { + 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(); + } + } +} \ No newline at end of file