From 5b1b8bcb8be2fb86619a9c7c5d9f000911c623f4 Mon Sep 17 00:00:00 2001 From: Steven Maglio Date: Mon, 11 Nov 2019 08:25:37 -0800 Subject: [PATCH] Adding null-conditional operator on IEnumerable.GetEnumerator() (#16947) --- src/Http/Http/src/Internal/ItemsDictionary.cs | 4 +- .../test/Internal/ItemsDictionaryTests.cs | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 src/Http/Http/test/Internal/ItemsDictionaryTests.cs diff --git a/src/Http/Http/src/Internal/ItemsDictionary.cs b/src/Http/Http/src/Internal/ItemsDictionary.cs index 5dd44f6887..3ca7ae95e1 100644 --- a/src/Http/Http/src/Internal/ItemsDictionary.cs +++ b/src/Http/Http/src/Internal/ItemsDictionary.cs @@ -101,7 +101,7 @@ namespace Microsoft.AspNetCore.Http EmptyDictionary.Collection.CopyTo(array, arrayIndex); } - _items.CopyTo(array, arrayIndex); + _items?.CopyTo(array, arrayIndex); } int ICollection>.Count => _items?.Count ?? 0; @@ -133,7 +133,7 @@ namespace Microsoft.AspNetCore.Http IEnumerator> IEnumerable>.GetEnumerator() => _items?.GetEnumerator() ?? EmptyEnumerator.Instance; - IEnumerator IEnumerable.GetEnumerator() => _items.GetEnumerator() ?? EmptyEnumerator.Instance; + IEnumerator IEnumerable.GetEnumerator() => _items?.GetEnumerator() ?? EmptyEnumerator.Instance; private class EmptyEnumerator : IEnumerator> { diff --git a/src/Http/Http/test/Internal/ItemsDictionaryTests.cs b/src/Http/Http/test/Internal/ItemsDictionaryTests.cs new file mode 100644 index 0000000000..d8319c1c43 --- /dev/null +++ b/src/Http/Http/test/Internal/ItemsDictionaryTests.cs @@ -0,0 +1,41 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.IO.Pipelines; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.Primitives; +using Xunit; + +namespace Microsoft.AspNetCore.Http +{ + public class ItemsDictionaryTests + { + [Fact] + public void GetEnumerator_ShouldResolveWithoutNullReferenceException() + { + // Arrange + var dict = new ItemsDictionary(); + + // Act and Assert + IEnumerable en = (IEnumerable) dict; + Assert.NotNull(en.GetEnumerator()); + } + + [Fact] + public void CopyTo_ShouldCopyItemsWithoutNullReferenceException() { + // Arrange + var dict = new ItemsDictionary(); + var pairs = new KeyValuePair[] { new KeyValuePair("first", "value") }; + + // Act and Assert + ICollection> cl = (ICollection>) dict; + cl.CopyTo(pairs, 0); + } + } +}