diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 2e733802fa..df96aba17a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -668,14 +668,26 @@ namespace Microsoft.PowerShell.Commands /// private static IEnumerable InitDefaultRefAssemblies() { - // netcoreapp3.0 currently comes with 148 reference assemblies (maybe more in future), so we use a capacity of '150'. - var defaultRefAssemblies = new List(150); + // Define number of reference assemblies distributed with PowerShell. + // This number is accurate as of PowerShell v7.1.0-preview.1 built with .NET v5.0.100-preview.1.20155.7 + const int numberOfPowershellRefAssemblies = 151; + + const int capacity = numberOfPowershellRefAssemblies + 1; + var defaultRefAssemblies = new List(capacity); foreach (string file in Directory.EnumerateFiles(s_netcoreAppRefFolder, "*.dll", SearchOption.TopDirectoryOnly)) { defaultRefAssemblies.Add(MetadataReference.CreateFromFile(file)); } + + // Add System.Management.Automation.dll defaultRefAssemblies.Add(MetadataReference.CreateFromFile(typeof(PSObject).Assembly.Location)); + + // We want to avoid reallocating the internal array, so we assert if the list capacity has increased. + Diagnostics.Assert( + defaultRefAssemblies.Capacity <= capacity, + $"defaultRefAssemblies was resized because of insufficient initial capacity! A capacity of {defaultRefAssemblies.Count} is required."); + return defaultRefAssemblies; }