From 0f4d1d08c4dc5a2220780d0bed2b02c5a135510c Mon Sep 17 00:00:00 2001 From: Michele Bastione Date: Tue, 7 Oct 2025 23:38:44 +0200 Subject: [PATCH] Added custom exception for indexers being treated as properties during serialization Mirrors #884 on the maintenance branch --- .../MiniExcelNotSerializableException.cs | 15 +++++++++++++++ src/MiniExcel/Reflection/Property.cs | 9 ++++++++- tests/MiniExcelTests/MiniExcelIssueTests.cs | 18 ++++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src/MiniExcel/Exceptions/MiniExcelNotSerializableException.cs diff --git a/src/MiniExcel/Exceptions/MiniExcelNotSerializableException.cs b/src/MiniExcel/Exceptions/MiniExcelNotSerializableException.cs new file mode 100644 index 00000000..f86f82cf --- /dev/null +++ b/src/MiniExcel/Exceptions/MiniExcelNotSerializableException.cs @@ -0,0 +1,15 @@ +using System; +using System.Reflection; + +namespace MiniExcelLibs.Exceptions +{ + public class MiniExcelNotSerializableException : InvalidOperationException + { + public MemberInfo Member { get; } + + public MiniExcelNotSerializableException(string message, MemberInfo member) : base(message) + { + Member = member; + } + } +} diff --git a/src/MiniExcel/Reflection/Property.cs b/src/MiniExcel/Reflection/Property.cs index 2156402e..61cfef96 100644 --- a/src/MiniExcel/Reflection/Property.cs +++ b/src/MiniExcel/Reflection/Property.cs @@ -2,6 +2,7 @@ using System.Collections.Concurrent; using System.Linq; using System.Reflection; +using MiniExcelLibs.Exceptions; namespace MiniExcelLibs { @@ -18,7 +19,13 @@ public Property(PropertyInfo property) { Name = property.Name; Info = property; - + + if (property.GetIndexParameters().Length != 0) + { + const string msg = "Types containing indexers cannot be serialized. Please remove them or decorate them with MiniExcelIgnoreAttribute."; + throw new MiniExcelNotSerializableException(msg, property); + } + if (property.CanRead) { CanRead = true; diff --git a/tests/MiniExcelTests/MiniExcelIssueTests.cs b/tests/MiniExcelTests/MiniExcelIssueTests.cs index a4be971d..1cdc95c9 100644 --- a/tests/MiniExcelTests/MiniExcelIssueTests.cs +++ b/tests/MiniExcelTests/MiniExcelIssueTests.cs @@ -4719,4 +4719,22 @@ public void TestIssue876() MiniExcel.SaveAs(outputPath.ToString(), sheets); }); } + + private class Issue880 + { + public string Test { get; set; } + public string this[int i] => ""; + } + + [Fact] + public void TestIssue880_ShouldThrowNotSerializableException() + { + Issue880[] toExport = [new() { Test = "test" }]; + + Assert.Throws(() => + { + using var ms = new MemoryStream(); + ms.SaveAs(toExport); + }); + } } \ No newline at end of file