Fix IDE0090: Simplify new expression part 4.4 (#14258)

https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090
This commit is contained in:
xtqqczze
2020-11-26 10:38:27 +05:00
committed by GitHub
parent b5fc2f34e4
commit 2f6d0ac610
22 changed files with 105 additions and 105 deletions
@@ -20,7 +20,7 @@ namespace Microsoft.PowerShell.Commands
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097109", RemotingCapability = RemotingCapability.None)]
public class AddMemberCommand : PSCmdlet
{
private static readonly object s_notSpecified = new object();
private static readonly object s_notSpecified = new();
private static bool HasBeenSpecified(object obj)
{
@@ -221,7 +221,7 @@ namespace Microsoft.PowerShell.Commands
{
if (!HasBeenSpecified(_value1))
{
Collection<FieldDescription> fdc = new Collection<FieldDescription>();
Collection<FieldDescription> fdc = new();
fdc.Add(new FieldDescription("Value"));
string prompt = StringUtil.Format(AddMember.Value1Prompt, _memberType);
Dictionary<string, PSObject> result = this.Host.UI.Prompt(prompt, null, fdc);
@@ -531,9 +531,9 @@ namespace Microsoft.PowerShell.Commands
private ErrorRecord NewError(string errorId, string resourceId, object targetObject, params object[] args)
{
ErrorDetails details = new ErrorDetails(this.GetType().GetTypeInfo().Assembly,
ErrorDetails details = new(this.GetType().GetTypeInfo().Assembly,
"Microsoft.PowerShell.Commands.Utility.resources.AddMember", resourceId, args);
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new InvalidOperationException(details.Message),
errorId,
ErrorCategory.InvalidOperation,
@@ -153,7 +153,7 @@ namespace Microsoft.PowerShell.Commands
string[] pathValue = value;
List<string> resolvedPaths = new List<string>();
List<string> resolvedPaths = new();
// Verify that the paths are resolved and valid
foreach (string path in pathValue)
@@ -198,7 +198,7 @@ namespace Microsoft.PowerShell.Commands
return;
}
List<string> resolvedPaths = new List<string>();
List<string> resolvedPaths = new();
foreach (string path in value)
{
string literalPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
@@ -230,7 +230,7 @@ namespace Microsoft.PowerShell.Commands
// Throw an error if it is an unrecognized extension
default:
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new Exception(
StringUtil.Format(AddTypeStrings.FileExtensionNotSupported, currentExtension)),
"EXTENSION_NOT_SUPPORTED",
@@ -248,7 +248,7 @@ namespace Microsoft.PowerShell.Commands
else if (!string.Equals(activeExtension, currentExtension, StringComparison.OrdinalIgnoreCase))
{
// All files must have the same extension otherwise throw.
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new Exception(
StringUtil.Format(AddTypeStrings.MultipleExtensionsNotSupported)),
"MULTIPLE_EXTENSION_NOT_SUPPORTED",
@@ -327,7 +327,7 @@ namespace Microsoft.PowerShell.Commands
// Try to resolve the path
ProviderInfo provider = null;
Collection<string> newPaths = new Collection<string>();
Collection<string> newPaths = new();
try
{
@@ -336,7 +336,7 @@ namespace Microsoft.PowerShell.Commands
// Ignore the ItemNotFound -- we handle it.
catch (ItemNotFoundException) { }
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new Exception(
StringUtil.Format(AddTypeStrings.OutputAssemblyDidNotResolve, _outputAssembly)),
"INVALID_OUTPUT_ASSEMBLY",
@@ -520,7 +520,7 @@ namespace Microsoft.PowerShell.Commands
// Generate the code for the using statements
private string GetUsingSet(Language language)
{
StringBuilder usingNamespaceSet = new StringBuilder();
StringBuilder usingNamespaceSet = new();
switch (language)
{
@@ -578,7 +578,7 @@ namespace Microsoft.PowerShell.Commands
// assembly type without an output assembly
if (string.IsNullOrEmpty(_outputAssembly) && this.MyInvocation.BoundParameters.ContainsKey(nameof(OutputType)))
{
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new Exception(
string.Format(
CultureInfo.CurrentCulture,
@@ -630,21 +630,21 @@ namespace Microsoft.PowerShell.Commands
private static readonly string s_frameworkFolder = PathType.GetDirectoryName(typeof(object).Assembly.Location);
// These assemblies are always automatically added to ReferencedAssemblies.
private static readonly Lazy<PortableExecutableReference[]> s_autoReferencedAssemblies = new Lazy<PortableExecutableReference[]>(InitAutoIncludedRefAssemblies);
private static readonly Lazy<PortableExecutableReference[]> s_autoReferencedAssemblies = new(InitAutoIncludedRefAssemblies);
// A HashSet of assembly names to be ignored if they are specified in '-ReferencedAssemblies'
private static readonly Lazy<HashSet<string>> s_refAssemblyNamesToIgnore = new Lazy<HashSet<string>>(InitRefAssemblyNamesToIgnore);
private static readonly Lazy<HashSet<string>> s_refAssemblyNamesToIgnore = new(InitRefAssemblyNamesToIgnore);
// These assemblies are used, when ReferencedAssemblies parameter is not specified.
private static readonly Lazy<IEnumerable<PortableExecutableReference>> s_defaultAssemblies = new Lazy<IEnumerable<PortableExecutableReference>>(InitDefaultRefAssemblies);
private static readonly Lazy<IEnumerable<PortableExecutableReference>> s_defaultAssemblies = new(InitDefaultRefAssemblies);
private bool InMemory { get { return string.IsNullOrEmpty(_outputAssembly); } }
// These dictionaries prevent reloading already loaded and unchanged code.
// We don't worry about unbounded growing of the cache because in .Net Core 2.0 we can not unload assemblies.
// TODO: review if we will be able to unload assemblies after migrating to .Net Core 2.1.
private static readonly HashSet<string> s_sourceTypesCache = new HashSet<string>();
private static readonly Dictionary<int, Assembly> s_sourceAssemblyCache = new Dictionary<int, Assembly>();
private static readonly HashSet<string> s_sourceTypesCache = new();
private static readonly Dictionary<int, Assembly> s_sourceAssemblyCache = new();
private static readonly string s_defaultSdkDirectory = Utils.DefaultPowerShellAppBase;
@@ -995,7 +995,7 @@ namespace Microsoft.PowerShell.Commands
}
SourceText sourceText;
List<SyntaxTree> syntaxTrees = new List<SyntaxTree>();
List<SyntaxTree> syntaxTrees = new();
switch (ParameterSetName)
{
@@ -1074,12 +1074,12 @@ namespace Microsoft.PowerShell.Commands
private void CheckDuplicateTypes(Compilation compilation, out ConcurrentBag<string> newTypes)
{
AllNamedTypeSymbolsVisitor visitor = new AllNamedTypeSymbolsVisitor();
AllNamedTypeSymbolsVisitor visitor = new();
visitor.Visit(compilation.Assembly.GlobalNamespace);
foreach (var symbolName in visitor.DuplicateSymbols)
{
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new Exception(
string.Format(AddTypeStrings.TypeAlreadyExists, symbolName)),
"TYPE_ALREADY_EXISTS",
@@ -1090,7 +1090,7 @@ namespace Microsoft.PowerShell.Commands
if (!visitor.DuplicateSymbols.IsEmpty)
{
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new InvalidOperationException(AddTypeStrings.CompilerErrors),
"COMPILER_ERRORS",
ErrorCategory.InvalidData,
@@ -1106,8 +1106,8 @@ namespace Microsoft.PowerShell.Commands
// Visit symbols in all namespaces and collect duplicates.
private class AllNamedTypeSymbolsVisitor : SymbolVisitor
{
public readonly ConcurrentBag<string> DuplicateSymbols = new ConcurrentBag<string>();
public readonly ConcurrentBag<string> UniqueSymbols = new ConcurrentBag<string>();
public readonly ConcurrentBag<string> DuplicateSymbols = new();
public readonly ConcurrentBag<string> UniqueSymbols = new();
public override void VisitNamespace(INamespaceSymbol symbol)
{
@@ -1243,7 +1243,7 @@ namespace Microsoft.PowerShell.Commands
}
else
{
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new Exception(errorText),
"SOURCE_CODE_ERROR",
ErrorCategory.InvalidData,
@@ -1255,7 +1255,7 @@ namespace Microsoft.PowerShell.Commands
if (IsError)
{
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new InvalidOperationException(AddTypeStrings.CompilerErrors),
"COMPILER_ERRORS",
ErrorCategory.InvalidData,
@@ -1288,7 +1288,7 @@ namespace Microsoft.PowerShell.Commands
var errorLineString = textLines[errorLineNumber].ToString();
var errorPosition = lineSpan.StartLinePosition.Character;
StringBuilder sb = new StringBuilder(diagnisticMessage.Length + errorLineString.Length * 2 + 4);
StringBuilder sb = new(diagnisticMessage.Length + errorLineString.Length * 2 + 4);
sb.AppendLine(diagnisticMessage);
sb.AppendLine(errorLineString);
@@ -1314,7 +1314,7 @@ namespace Microsoft.PowerShell.Commands
private static int SyntaxTreeArrayGetHashCode(IEnumerable<SyntaxTree> sts)
{
// We use our extension method EnumerableExtensions.SequenceGetHashCode<T>().
List<int> stHashes = new List<int>();
List<int> stHashes = new();
foreach (var st in sts)
{
stHashes.Add(SyntaxTreeGetHashCode(st));
@@ -101,10 +101,10 @@ namespace Microsoft.PowerShell.Commands
private List<OrderByPropertyEntry> _referenceEntries;
private readonly List<OrderByPropertyEntry> _referenceEntryBacklog
= new List<OrderByPropertyEntry>();
= new();
private readonly List<OrderByPropertyEntry> _differenceEntryBacklog
= new List<OrderByPropertyEntry>();
= new();
private OrderByProperty _orderByProperty = null;
private OrderByPropertyComparer _comparer = null;
@@ -256,7 +256,7 @@ namespace Microsoft.PowerShell.Commands
if (_comparer != null)
return;
List<PSObject> referenceObjectList = new List<PSObject>(ReferenceObject);
List<PSObject> referenceObjectList = new(ReferenceObject);
_orderByProperty = new OrderByProperty(
this, referenceObjectList, Property, true, _cultureInfo, CaseSensitive);
Diagnostics.Assert(_orderByProperty.Comparer != null, "no comparer");
@@ -327,7 +327,7 @@ namespace Microsoft.PowerShell.Commands
mshobj = new PSObject();
if (Property == null || Property.Length == 0)
{
PSNoteProperty inputNote = new PSNoteProperty(
PSNoteProperty inputNote = new(
InputObjectPropertyName, entry.inputObject);
mshobj.Properties.Add(inputNote);
}
@@ -348,7 +348,7 @@ namespace Microsoft.PowerShell.Commands
object prop = hash[FormatParameterDefinitionKeys.ExpressionEntryKey];
Diagnostics.Assert(prop != null, "null prop");
string propName = prop.ToString();
PSNoteProperty propertyNote = new PSNoteProperty(
PSNoteProperty propertyNote = new(
propName,
entry.orderValues[i].PropertyValue);
try
@@ -364,7 +364,7 @@ namespace Microsoft.PowerShell.Commands
}
mshobj.Properties.Remove(SideIndicatorPropertyName);
PSNoteProperty sideNote = new PSNoteProperty(
PSNoteProperty sideNote = new(
SideIndicatorPropertyName, sideIndicator);
mshobj.Properties.Add(sideNote);
WriteObject(mshobj);
@@ -411,7 +411,7 @@ namespace Microsoft.PowerShell.Commands
InitComparer();
}
List<PSObject> differenceList = new List<PSObject>(DifferenceObject);
List<PSObject> differenceList = new(DifferenceObject);
List<OrderByPropertyEntry> differenceEntries =
OrderByProperty.CreateOrderMatrix(
this, differenceList, _orderByProperty.MshParameterList);
@@ -459,7 +459,7 @@ namespace Microsoft.PowerShell.Commands
return;
}
List<PSObject> differenceList = new List<PSObject>(DifferenceObject);
List<PSObject> differenceList = new(DifferenceObject);
_orderByProperty = new OrderByProperty(
this, differenceList, Property, true, _cultureInfo, CaseSensitive);
List<OrderByPropertyEntry> differenceEntries =
@@ -92,7 +92,7 @@ namespace Microsoft.PowerShell.Commands
private static ErrorRecord BuildOutOfRangeErrorRecord(object val, string errorId)
{
string msg = StringUtil.Format(HostStrings.InvalidColorErrorTemplate, val.ToString());
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException("value", val, msg);
ArgumentOutOfRangeException e = new("value", val, msg);
return new ErrorRecord(e, errorId, ErrorCategory.InvalidArgument, null);
}
#endregion helper
@@ -57,9 +57,9 @@ namespace Microsoft.PowerShell.Commands
private static List<string> GetApplicableAccessRights(int accessMask, AccessRightTypeNames? typeName)
{
List<Type> typesToExamine = new List<Type>();
List<string> foundAccessRightNames = new List<string>();
HashSet<int> foundAccessRightValues = new HashSet<int>();
List<Type> typesToExamine = new();
List<string> foundAccessRightNames = new();
HashSet<int> foundAccessRightValues = new();
if (typeName != null)
{
@@ -121,10 +121,10 @@ namespace Microsoft.PowerShell.Commands
return Array.Empty<string>();
}
List<string> aceStringList = new List<string>(acl.Count);
List<string> aceStringList = new(acl.Count);
foreach (CommonAce ace in acl)
{
StringBuilder aceString = new StringBuilder();
StringBuilder aceString = new();
string ntAccount = ConvertToNTAccount(ace.SecurityIdentifier);
aceString.Append($"{ntAccount}: {ace.AceQualifier}");
@@ -47,7 +47,7 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
protected override void ProcessRecord()
{
Hashtable result = new Hashtable(StringComparer.OrdinalIgnoreCase);
Hashtable result = new(StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrEmpty(_stringData))
{
@@ -106,7 +106,7 @@ namespace Microsoft.PowerShell.Commands
else
{
string errorMessage = StringUtil.Format(ConvertMarkdownStrings.InvalidInputObjectType, baseObj.GetType());
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new InvalidDataException(errorMessage),
"InvalidInputObject",
ErrorCategory.InvalidData,
@@ -150,7 +150,7 @@ namespace Microsoft.PowerShell.Commands
try
{
using (StreamReader reader = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)))
using (StreamReader reader = new(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
string mdContent = await reader.ReadToEndAsync();
return mdContent;
@@ -189,7 +189,7 @@ namespace Microsoft.PowerShell.Commands
{
ProviderInfo provider = null;
PSDriveInfo drive = null;
List<string> resolvedPaths = new List<string>();
List<string> resolvedPaths = new();
try
{
@@ -216,7 +216,7 @@ namespace Microsoft.PowerShell.Commands
if (!provider.Name.Equals("FileSystem", StringComparison.OrdinalIgnoreCase))
{
string errorMessage = StringUtil.Format(ConvertMarkdownStrings.FileSystemPathsOnly, path);
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new ArgumentException(),
"OnlyFileSystemPathsSupported",
ErrorCategory.InvalidArgument,
@@ -340,9 +340,9 @@ namespace Microsoft.PowerShell.Commands
/// <returns></returns>
private List<MshParameter> ProcessParameter(object[] properties)
{
TerminatingErrorContext invocationContext = new TerminatingErrorContext(this);
TerminatingErrorContext invocationContext = new(this);
ParameterProcessor processor =
new ParameterProcessor(new ConvertHTMLExpressionParameterDefinition());
new(new ConvertHTMLExpressionParameterDefinition());
if (properties == null)
{
properties = new object[] { "*" };
@@ -394,7 +394,7 @@ namespace Microsoft.PowerShell.Commands
string alignment,
string width)
{
Hashtable ht = new Hashtable();
Hashtable ht = new();
if (label != null)
{
ht.Add(ConvertHTMLParameterDefinitionKeys.LabelEntryKey, label);
@@ -444,8 +444,8 @@ namespace Microsoft.PowerShell.Commands
// ValidateNotNullOrEmpty attribute is not working for System.Uri datatype, so handling it here
if ((_cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim())))
{
ArgumentException ex = new ArgumentException(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri"));
ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri");
ArgumentException ex = new(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri"));
ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri");
ThrowTerminatingError(er);
}
@@ -480,7 +480,7 @@ namespace Microsoft.PowerShell.Commands
if (_metaSpecified)
{
List<string> useditems = new List<string>();
List<string> useditems = new();
foreach (string s in _meta.Keys)
{
if (!useditems.Contains(s))
@@ -503,7 +503,7 @@ namespace Microsoft.PowerShell.Commands
default:
MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
string Message = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]);
WarningRecord record = new WarningRecord(Message);
WarningRecord record = new(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
@@ -549,7 +549,7 @@ namespace Microsoft.PowerShell.Commands
/// <param name="mshParams"></param>
private void WriteColumns(List<MshParameter> mshParams)
{
StringBuilder COLTag = new StringBuilder();
StringBuilder COLTag = new();
COLTag.Append("<colgroup>");
foreach (MshParameter p in mshParams)
@@ -587,7 +587,7 @@ namespace Microsoft.PowerShell.Commands
{
foreach (MshParameter p in _resolvedNameMshParameters)
{
StringBuilder Listtag = new StringBuilder();
StringBuilder Listtag = new();
Listtag.Append("<tr><td>");
// for writing the property name
@@ -713,7 +713,7 @@ namespace Microsoft.PowerShell.Commands
{
WriteColumns(_resolvedNameMshParameters);
StringBuilder THtag = new StringBuilder("<tr>");
StringBuilder THtag = new("<tr>");
// write the table header
WriteTableHeader(THtag, _resolvedNameMshParameters);
@@ -726,7 +726,7 @@ namespace Microsoft.PowerShell.Commands
// if the As parameter is Table, write the property values
if (_as.Equals("Table", StringComparison.OrdinalIgnoreCase))
{
StringBuilder TRtag = new StringBuilder("<tr>");
StringBuilder TRtag = new("<tr>");
// write the table row
WriteTableRow(TRtag, _resolvedNameMshParameters);
@@ -28,7 +28,7 @@ namespace Microsoft.PowerShell.Commands
/// </param>
internal Collection<string> ParseCsv(string csv)
{
Collection<string> result = new Collection<string>();
Collection<string> result = new();
string tempString = string.Empty;
csv = csv.Trim();
if (csv.Length == 0 || csv[0] == '#')
@@ -108,15 +108,15 @@ namespace Microsoft.PowerShell.Commands
{
if (this.MyInvocation.BoundParameters.ContainsKey(nameof(QuoteFields)) && this.MyInvocation.BoundParameters.ContainsKey(nameof(UseQuotes)))
{
InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyQuoteFieldsAndUseQuotes);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyQuoteFieldsAndUseQuotes", ErrorCategory.InvalidData, null);
InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyQuoteFieldsAndUseQuotes);
ErrorRecord errorRecord = new(exception, "CannotSpecifyQuoteFieldsAndUseQuotes", ErrorCategory.InvalidData, null);
this.ThrowTerminatingError(errorRecord);
}
if (this.MyInvocation.BoundParameters.ContainsKey(nameof(IncludeTypeInformation)) && this.MyInvocation.BoundParameters.ContainsKey(nameof(NoTypeInformation)))
{
InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyIncludeTypeInformationAndNoTypeInformation);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyIncludeTypeInformationAndNoTypeInformation", ErrorCategory.InvalidData, null);
InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyIncludeTypeInformationAndNoTypeInformation);
ErrorRecord errorRecord = new(exception, "CannotSpecifyIncludeTypeInformationAndNoTypeInformation", ErrorCategory.InvalidData, null);
this.ThrowTerminatingError(errorRecord);
}
@@ -258,8 +258,8 @@ namespace Microsoft.PowerShell.Commands
// Validate that they don't provide both Path and LiteralPath, but have provided at least one.
if (!(_specifiedPath ^ _isLiteralPath))
{
InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null);
InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyPathAndLiteralPath);
ErrorRecord errorRecord = new(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null);
this.ThrowTerminatingError(errorRecord);
}
@@ -371,7 +371,7 @@ namespace Microsoft.PowerShell.Commands
using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, Encoding, _isLiteralPath))
{
ImportCsvHelper readingHelper = new ImportCsvHelper(
ImportCsvHelper readingHelper = new(
this, this.Delimiter, null /* header */, null /* typeName */, streamReader);
readingHelper.ReadHeader();
_preexistingPropertyNames = readingHelper.Header;
@@ -446,7 +446,7 @@ namespace Microsoft.PowerShell.Commands
throw new InvalidOperationException(CsvCommandStrings.ReconcilePreexistingPropertyNamesMethodShouldOnlyGetCalledWhenPreexistingPropertyNamesHaveBeenReadSuccessfully);
}
HashSet<string> appendedPropertyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
HashSet<string> appendedPropertyNames = new(StringComparer.OrdinalIgnoreCase);
foreach (string appendedPropertyName in _propertyNames)
{
appendedPropertyNames.Add(appendedPropertyName);
@@ -463,8 +463,8 @@ namespace Microsoft.PowerShell.Commands
CsvCommandStrings.CannotAppendCsvWithMismatchedPropertyNames,
preexistingPropertyName,
this.Path);
InvalidOperationException exception = new InvalidOperationException(errorMessage);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotAppendCsvWithMismatchedPropertyNames", ErrorCategory.InvalidData, preexistingPropertyName);
InvalidOperationException exception = new(errorMessage);
ErrorRecord errorRecord = new(exception, "CannotAppendCsvWithMismatchedPropertyNames", ErrorCategory.InvalidData, preexistingPropertyName);
this.ThrowTerminatingError(errorRecord);
}
}
@@ -644,8 +644,8 @@ namespace Microsoft.PowerShell.Commands
// Validate that they don't provide both Path and LiteralPath, but have provided at least one.
if (!(_specifiedPath ^ _isLiteralPath))
{
InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null);
InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyPathAndLiteralPath);
ErrorRecord errorRecord = new(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null);
this.ThrowTerminatingError(errorRecord);
}
@@ -655,7 +655,7 @@ namespace Microsoft.PowerShell.Commands
{
using (StreamReader streamReader = PathUtils.OpenStreamReader(this, path, this.Encoding, _isLiteralPath))
{
ImportCsvHelper helper = new ImportCsvHelper(this, Delimiter, Header, null /* typeName */, streamReader);
ImportCsvHelper helper = new(this, Delimiter, Header, null /* typeName */, streamReader);
try
{
@@ -663,7 +663,7 @@ namespace Microsoft.PowerShell.Commands
}
catch (ExtendedTypeSystemException exception)
{
ErrorRecord errorRecord = new ErrorRecord(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null);
ErrorRecord errorRecord = new(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null);
this.ThrowTerminatingError(errorRecord);
}
}
@@ -833,10 +833,10 @@ namespace Microsoft.PowerShell.Commands
{
foreach (PSObject inputObject in InputObject)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(inputObject.ToString())))
using (StreamReader streamReader = new StreamReader(memoryStream, System.Text.Encoding.Unicode))
using (MemoryStream memoryStream = new(Encoding.Unicode.GetBytes(inputObject.ToString())))
using (StreamReader streamReader = new(memoryStream, System.Text.Encoding.Unicode))
{
ImportCsvHelper helper = new ImportCsvHelper(this, Delimiter, Header, _typeName, streamReader);
ImportCsvHelper helper = new(this, Delimiter, Header, _typeName, streamReader);
try
{
@@ -844,7 +844,7 @@ namespace Microsoft.PowerShell.Commands
}
catch (ExtendedTypeSystemException exception)
{
ErrorRecord errorRecord = new ErrorRecord(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null);
ErrorRecord errorRecord = new(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null);
this.ThrowTerminatingError(errorRecord);
}
@@ -1384,7 +1384,7 @@ namespace Microsoft.PowerShell.Commands
}
else
{
HashSet<string> headers = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
HashSet<string> headers = new(StringComparer.OrdinalIgnoreCase);
foreach (string currentHeader in names)
{
if (!string.IsNullOrEmpty(currentHeader))
@@ -1402,7 +1402,7 @@ namespace Microsoft.PowerShell.Commands
ExtendedTypeSystem.MemberAlreadyPresent,
currentHeader);
ExtendedTypeSystemException exception = new ExtendedTypeSystemException(memberAlreadyPresentMsg);
ExtendedTypeSystemException exception = new(memberAlreadyPresentMsg);
throw exception;
}
}
@@ -1636,7 +1636,7 @@ namespace Microsoft.PowerShell.Commands
/// </param>
private void ReadTillNextDelimiter(StringBuilder current, ref bool endOfRecord, bool eatTrailingBlanks)
{
StringBuilder temp = new StringBuilder();
StringBuilder temp = new();
// Did we see any non-whitespace character
bool nonWhiteSpace = false;
@@ -1684,7 +1684,7 @@ namespace Microsoft.PowerShell.Commands
private PSObject BuildMshobject(string type, IList<string> names, List<string> values, char delimiter, bool preValidated = false)
{
PSObject result = new PSObject(names.Count);
PSObject result = new(names.Count);
char delimiterlocal = delimiter;
int unspecifiedNameIndex = 1;
for (int i = 0; i <= names.Count - 1; i++)
@@ -741,7 +741,7 @@ namespace System.Management.Automation
Dbg.Assert(depth >= 0, "depth should be greater or equal to zero");
if (source.GetSerializationMethod(null) == SerializationMethod.SpecificProperties)
{
PSMemberInfoInternalCollection<PSPropertyInfo> specificProperties = new PSMemberInfoInternalCollection<PSPropertyInfo>();
PSMemberInfoInternalCollection<PSPropertyInfo> specificProperties = new();
foreach (string propertyName in source.GetSpecificPropertiesToSerialize(null))
{
PSPropertyInfo property = source.Properties[propertyName];
@@ -43,7 +43,7 @@ namespace Microsoft.PowerShell.Commands
// Debugging to persist until Ctrl+C or Debugger 'Exit' stops cmdlet.
private bool _debugging;
private readonly ManualResetEventSlim _newRunningScriptEvent = new ManualResetEventSlim(true);
private readonly ManualResetEventSlim _newRunningScriptEvent = new(true);
private RunspaceAvailability _previousRunspaceAvailability = RunspaceAvailability.None;
#endregion
@@ -291,7 +291,7 @@ namespace Microsoft.PowerShell.Commands
}
catch (Exception ex)
{
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, Debugger.PersistDebugPreferenceFailure, processName), ex),
fullyQualifiedErrorId,
ErrorCategory.InvalidOperation,
@@ -244,7 +244,7 @@ namespace Microsoft.PowerShell.Commands
// that doesn't exist and they are not globbing.
ItemNotFoundException itemNotFound =
new ItemNotFoundException(
new(
aliasName,
"AliasNotFound",
SessionStateStrings.AliasNotFound);
@@ -310,7 +310,7 @@ namespace Microsoft.PowerShell.Commands
/// <summary>
/// Holds all the matching aliases for writing to the file.
/// </summary>
private readonly Collection<AliasInfo> _matchingAliases = new Collection<AliasInfo>();
private readonly Collection<AliasInfo> _matchingAliases = new();
private static string GetAliasLine(AliasInfo alias, string formatString)
{
@@ -406,7 +406,7 @@ namespace Microsoft.PowerShell.Commands
{
string message = StringUtil.Format(AliasCommandStrings.ExportAliasFileOpenFailed, pathWithError, e.Message);
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
e,
"FileOpenFailure",
ErrorCategory.OpenError,
@@ -224,7 +224,7 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
private static List<Breakpoint> Filter<T>(List<Breakpoint> input, T[] filter, FilterSelector<T> selector)
{
List<Breakpoint> output = new List<Breakpoint>();
List<Breakpoint> output = new();
for (int i = 0; i < input.Count; i++)
{
@@ -118,7 +118,7 @@ namespace Microsoft.PowerShell.Commands
_excludes,
WildcardOptions.IgnoreCase);
List<AliasInfo> results = new List<AliasInfo>();
List<AliasInfo> results = new();
foreach (KeyValuePair<string, AliasInfo> tableEntry in aliasTable)
{
if (parametersetname.Equals("Definition", StringComparison.OrdinalIgnoreCase))
@@ -192,8 +192,8 @@ namespace Microsoft.PowerShell.Commands
// Need to write an error if the user tries to get an alias
// tat doesn't exist and they are not globbing.
ItemNotFoundException itemNotFound = new ItemNotFoundException(StringUtil.Format(AliasCommandStrings.NoAliasFound, displayString, value));
ErrorRecord er = new ErrorRecord(itemNotFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value);
ItemNotFoundException itemNotFound = new(StringUtil.Format(AliasCommandStrings.NoAliasFound, displayString, value));
ErrorRecord er = new(itemNotFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value);
WriteError(er);
}
}
@@ -368,15 +368,15 @@ namespace Microsoft.PowerShell.Commands
else
{
// output DateTime object wrapped in an PSObject with DisplayHint attached
PSObject outputObj = new PSObject(dateToUse);
PSNoteProperty note = new PSNoteProperty("DisplayHint", DisplayHint);
PSObject outputObj = new(dateToUse);
PSNoteProperty note = new("DisplayHint", DisplayHint);
outputObj.Properties.Add(note);
WriteObject(outputObj);
}
}
private static readonly DateTime s_epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static readonly DateTime s_epoch = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// This is more an implementation of the UNIX strftime.
@@ -384,7 +384,7 @@ namespace Microsoft.PowerShell.Commands
private string UFormatDateString(DateTime dateTime)
{
int offset = 0;
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
// folks may include the "+" as part of the format string
if (UFormat[0] == '+')
@@ -124,7 +124,7 @@ namespace Microsoft.PowerShell.Commands
error = EventingStrings.EventIdentifierNotFound;
}
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new ArgumentException(string.Format(System.Globalization.CultureInfo.CurrentCulture, error, identifier)),
"INVALID_SOURCE_IDENTIFIER",
ErrorCategory.InvalidArgument,
@@ -67,7 +67,7 @@ namespace Microsoft.PowerShell.Commands
// Go through all the received events and write them to the output
// pipeline
List<PSEventSubscriber> subscribers = new List<PSEventSubscriber>(Events.Subscribers);
List<PSEventSubscriber> subscribers = new(Events.Subscribers);
foreach (PSEventSubscriber subscriber in subscribers)
{
// If they specified a event identifier and we don't match, continue
@@ -118,7 +118,7 @@ namespace Microsoft.PowerShell.Commands
error = EventingStrings.EventSubscriptionNotFound;
}
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new ArgumentException(string.Format(System.Globalization.CultureInfo.CurrentCulture, error, identifier)),
"INVALID_SOURCE_IDENTIFIER",
ErrorCategory.InvalidArgument,
@@ -83,7 +83,7 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
protected override void ProcessRecord()
{
List<string> pathsToProcess = new List<string>();
List<string> pathsToProcess = new();
ProviderInfo provider = null;
switch (ParameterSetName)
@@ -104,7 +104,7 @@ namespace Microsoft.PowerShell.Commands
{
if (!WildcardPattern.ContainsWildcardCharacters(path))
{
ErrorRecord errorRecord = new ErrorRecord(e,
ErrorRecord errorRecord = new(e,
"FileNotFound",
ErrorCategory.ObjectNotFound,
path);
@@ -211,7 +211,7 @@ namespace Microsoft.PowerShell.Commands
/// </summary>
private void WriteHashResult(string Algorithm, string hash, string path)
{
FileHashInfo result = new FileHashInfo();
FileHashInfo result = new();
result.Algorithm = Algorithm;
result.Hash = hash;
result.Path = path;
@@ -131,7 +131,7 @@ namespace Microsoft.PowerShell.Commands
private MshMemberMatchOptions _matchOptions = MshMemberMatchOptions.None;
private readonly HybridDictionary _typesAlreadyDisplayed = new HybridDictionary();
private readonly HybridDictionary _typesAlreadyDisplayed = new();
/// <summary>
/// This method implements the ProcessRecord method for get-member command.
@@ -271,7 +271,7 @@ namespace Microsoft.PowerShell.Commands
{
if (_typesAlreadyDisplayed.Count == 0)
{
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new InvalidOperationException(GetMember.NoObjectSpecified),
"NoObjectInGetMember",
ErrorCategory.CloseError,
@@ -95,7 +95,7 @@ namespace Microsoft.PowerShell.Commands
throw PSTraceSource.NewArgumentNullException("max");
}
ErrorRecord errorRecord = new ErrorRecord(
ErrorRecord errorRecord = new(
new ArgumentException(string.Format(
CultureInfo.InvariantCulture, GetRandomCommandStrings.MinGreaterThanOrEqualMax, minValue, maxValue)),
"MinGreaterThanOrEqualMax",
@@ -109,10 +109,10 @@ namespace Microsoft.PowerShell.Commands
#region Random generator state
private static readonly ReaderWriterLockSlim s_runspaceGeneratorMapLock = new ReaderWriterLockSlim();
private static readonly ReaderWriterLockSlim s_runspaceGeneratorMapLock = new();
// 1-to-1 mapping of runspaces and random number generators
private static readonly Dictionary<Guid, PolymorphicRandomNumberGenerator> s_runspaceGeneratorMap = new Dictionary<Guid, PolymorphicRandomNumberGenerator>();
private static readonly Dictionary<Guid, PolymorphicRandomNumberGenerator> s_runspaceGeneratorMap = new();
private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e)
{