// 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.ObjectModel; namespace Microsoft.Net.Http.Headers { // List allows 'null' values to be added. This is not what we want so we use a custom Collection derived // type to throw if 'null' gets added. Collection internally uses List which comes at some cost. In addition // Collection.Add() calls List.InsertItem() which is an O(n) operation (compared to O(1) for List.Add()). // This type is only used for very small collections (1-2 items) to keep the impact of using Collection small. internal class ObjectCollection : Collection where T : class { private static readonly Action DefaultValidator = CheckNotNull; private Action _validator; public ObjectCollection() : this(DefaultValidator) { } public ObjectCollection(Action validator) { _validator = validator; } protected override void InsertItem(int index, T item) { if (_validator != null) { _validator(item); } base.InsertItem(index, item); } protected override void SetItem(int index, T item) { if (_validator != null) { _validator(item); } base.SetItem(index, item); } private static void CheckNotNull(T item) { // null values cannot be added to the collection. if (item == null) { throw new ArgumentNullException(nameof(item)); } } } }