diff --git a/src/CsvHelper/CsvReader.cs b/src/CsvHelper/CsvReader.cs index 3fa74c2a0..d9a1402f6 100644 --- a/src/CsvHelper/CsvReader.cs +++ b/src/CsvHelper/CsvReader.cs @@ -891,11 +891,12 @@ record = read(); } } - /// - public virtual IEnumerable GetRecords(T anonymousTypeDefinition) - { - if (anonymousTypeDefinition == null) - { + /// + /// Thrown when the reader has been disposed. + public virtual IEnumerable GetRecords(T anonymousTypeDefinition) + { + if (anonymousTypeDefinition == null) + { throw new ArgumentNullException(nameof(anonymousTypeDefinition)); } @@ -907,11 +908,12 @@ public virtual IEnumerable GetRecords(T anonymousTypeDefinition) return GetRecords(); } - /// - public virtual IEnumerable GetRecords(Type type) - { - if (disposed) - { + /// + /// Thrown when the reader has been disposed. + public virtual IEnumerable GetRecords(Type type) + { + if (disposed) + { throw new ObjectDisposedException(nameof(CsvReader), "GetRecords() returns an IEnumerable that yields records. This means that the method isn't actually called until " + "you try and access the values. e.g. .ToList() Did you create CsvReader inside a using block and are now trying to access " + diff --git a/tests/CsvHelper.Tests/Reading/YieldTests.cs b/tests/CsvHelper.Tests/Reading/YieldTests.cs index 72fa702f8..15cac6a0a 100644 --- a/tests/CsvHelper.Tests/Reading/YieldTests.cs +++ b/tests/CsvHelper.Tests/Reading/YieldTests.cs @@ -52,6 +52,25 @@ public void GetRecords_Disposed_ThrowsObjectDisposedExceptionTest() Assert.Throws(() => records.ToList()); } + [Fact] + public void GetRecordsAnonymousType_Disposed_ThrowsObjectDisposedExceptionTest() + { + var parserMock = new ParserMock + { + new[] { "Id", "Name" }, + new[] { "1", "one" }, + null + }; + + IEnumerable records; + using (var csv = new CsvReader(parserMock)) + { + records = csv.GetRecords(new { Id = 0, Name = string.Empty }).Cast(); + } + + Assert.Throws(() => records.ToList()); + } + [Fact] public void EnumerateRecords_Disposed_ThrowsObjectDisposedExceptionTest() {