diff --git a/.globalconfig b/.globalconfig index 2c16bbfdc27..a368b21e0c1 100644 --- a/.globalconfig +++ b/.globalconfig @@ -782,7 +782,7 @@ dotnet_diagnostic.IDE0017.severity = silent dotnet_diagnostic.IDE0018.severity = silent # IDE0019: InlineAsTypeCheck -dotnet_diagnostic.IDE0019.severity = silent +dotnet_diagnostic.IDE0019.severity = warning # IDE0020: InlineIsTypeCheck dotnet_diagnostic.IDE0020.severity = silent diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs index 6a74a252959..d6a0dd3c805 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs @@ -348,16 +348,14 @@ protected virtual void SubscribeToCimSessionProxyEvent(CimSessionProxy proxy) /// protected object GetBaseObject(object value) { - PSObject psObject = value as PSObject; - if (psObject == null) + if (value is not PSObject psObject) { return value; } else { object baseObject = psObject.BaseObject; - var arrayObject = baseObject as object[]; - if (arrayObject == null) + if (baseObject is not object[] arrayObject) { return baseObject; } @@ -384,8 +382,7 @@ protected object GetBaseObject(object value) /// The object. protected object GetReferenceOrReferenceArrayObject(object value, ref CimType referenceType) { - PSReference cimReference = value as PSReference; - if (cimReference != null) + if (value is PSReference cimReference) { object baseObject = GetBaseObject(cimReference.Value); if (!(baseObject is CimInstance cimInstance)) @@ -398,8 +395,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re } else { - object[] cimReferenceArray = value as object[]; - if (cimReferenceArray == null) + if (value is not object[] cimReferenceArray) { return null; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs index 8e2973f49ae..b1e3667406a 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs @@ -285,8 +285,7 @@ protected static string GetQuery(CimBaseCommand cmdlet) internal static bool IsClassNameQuerySet(CimBaseCommand cmdlet) { DebugHelper.WriteLogEx(); - GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand; - if (cmd != null) + if (cmdlet is GetCimInstanceCommand cmd) { if (cmd.QueryDialect != null || cmd.SelectProperties != null || cmd.Filter != null) { @@ -300,8 +299,7 @@ internal static bool IsClassNameQuerySet(CimBaseCommand cmdlet) protected static string CreateQuery(CimBaseCommand cmdlet) { DebugHelper.WriteLogEx(); - GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand; - if (cmd != null) + if (cmdlet is GetCimInstanceCommand cmd) { StringBuilder propertyList = new StringBuilder(); if (cmd.SelectProperties == null) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index 198c86e96af..f8cf387cb8a 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -237,13 +237,11 @@ private void NewSubscriptionResultHandler(object src, CimSubscriptionEventArgs a if (temp != null) { // raise the event - CimSubscriptionResultEventArgs resultArgs = args as CimSubscriptionResultEventArgs; - if (resultArgs != null) + if (args is CimSubscriptionResultEventArgs resultArgs) temp(this, new CimIndicationEventInstanceEventArgs(resultArgs.Result)); else { - CimSubscriptionExceptionEventArgs exceptionArgs = args as CimSubscriptionExceptionEventArgs; - if (exceptionArgs != null) + if (args is CimSubscriptionExceptionEventArgs exceptionArgs) temp(this, new CimIndicationEventExceptionEventArgs(exceptionArgs.Exception)); } } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs index 14c57c87888..56c8b3c6cc6 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs @@ -180,8 +180,7 @@ internal void GetCimInstance(CimInstance cimInstance, XOperationContextBase cont { DebugHelper.WriteLogEx(); - CimNewCimInstanceContext newCimInstanceContext = context as CimNewCimInstanceContext; - if (newCimInstanceContext == null) + if (context is not CimNewCimInstanceContext newCimInstanceContext) { DebugHelper.WriteLog("Invalid (null) CimNewCimInstanceContext", 1); return; @@ -296,8 +295,7 @@ private CimInstance CreateCimInstance( DebugHelper.WriteLog("Create and add new property to ciminstance: name = {0}; value = {1}; flags = {2}", 5, propertyName, propertyValue, flag); - PSReference cimReference = propertyValue as PSReference; - if (cimReference != null) + if (propertyValue is PSReference cimReference) { CimProperty newProperty = CimProperty.Create(propertyName, GetBaseObject(cimReference.Value), CimType.Reference, flag); cimInstance.CimInstanceProperties.Add(newProperty); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index ed547444adc..ca99c6ac967 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -216,8 +216,7 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio } // NOTES: should move after this.Disposed, but need to log the exception - CimWriteError cimWriteError = actionArgs.Action as CimWriteError; - if (cimWriteError != null) + if (actionArgs.Action is CimWriteError cimWriteError) { this.exception = cimWriteError.Exception; if (!this.ackedEvent.IsSet) @@ -239,11 +238,9 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio DebugHelper.WriteLog("Got an exception: {0}", 2, exception); } - CimWriteResultObject cimWriteResultObject = actionArgs.Action as CimWriteResultObject; - if (cimWriteResultObject != null) + if (actionArgs.Action is CimWriteResultObject cimWriteResultObject) { - CimSubscriptionResult result = cimWriteResultObject.Result as CimSubscriptionResult; - if (result != null) + if (cimWriteResultObject.Result is CimSubscriptionResult result) { EventHandler temp = this.OnNewSubscriptionResult; if (temp != null) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs index 3dd51d289aa..4c415711f04 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs @@ -437,8 +437,7 @@ public override void OnNext(CimMethodResultBase value) string resultObjectPSType = null; PSObject resultObject = null; - CimMethodResult methodResult = value as CimMethodResult; - if (methodResult != null) + if (value is CimMethodResult methodResult) { resultObjectPSType = PSTypeCimMethodResult; resultObject = new PSObject(); @@ -449,8 +448,7 @@ public override void OnNext(CimMethodResultBase value) } else { - CimMethodStreamedResult methodStreamedResult = value as CimMethodStreamedResult; - if (methodStreamedResult != null) + if (value is CimMethodStreamedResult methodStreamedResult) { resultObjectPSType = PSTypeCimMethodStreamedResult; resultObject = new PSObject(); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs index 9d367877a4c..3ca2c52c7df 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs @@ -39,14 +39,12 @@ internal static ErrorRecord ErrorRecordFromAnyException( { Debug.Assert(inner != null, "Caller should verify inner != null"); - CimException cimException = inner as CimException; - if (cimException != null) + if (inner is CimException cimException) { return CreateFromCimException(context, cimException, cimResultContext); } - var containsErrorRecord = inner as IContainsErrorRecord; - if (containsErrorRecord != null) + if (inner is IContainsErrorRecord containsErrorRecord) { return InitializeErrorRecord(context, exception: inner, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs index 5605ff658f6..8e768e0d6ac 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs @@ -231,8 +231,7 @@ public override void WriteObject(object sendToPipeline, XOperationContextBase co if (sendToPipeline is CimInstance) { - CimSetCimInstanceContext setContext = context as CimSetCimInstanceContext; - if (setContext != null) + if (context is CimSetCimInstanceContext setContext) { if (string.Equals(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase) || string.Equals(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs index ec761587b64..67bf50dce31 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs @@ -273,8 +273,7 @@ private static void newSubscriber_Unsubscribed( { DebugHelper.WriteLogEx(); - CimIndicationWatcher watcher = sender as CimIndicationWatcher; - if (watcher != null) + if (sender is CimIndicationWatcher watcher) { watcher.Stop(); } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index 09ac6153a52..3c36b74b512 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -1282,8 +1282,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession // // Build xpath for // - Hashtable suppresshash = hash[hashkey_supress_lc] as Hashtable; - if (suppresshash != null) + if (hash[hashkey_supress_lc] is Hashtable suppresshash) { xpathStringSuppress = BuildXPathFromHashTable(suppresshash); } @@ -1350,8 +1349,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession private string HandleEventIdHashValue(object value) { StringBuilder ret = new StringBuilder(); - Array idsArray = value as Array; - if (idsArray != null) + if (value is Array idsArray) { ret.Append('('); for (int i = 0; i < idsArray.Length; i++) @@ -1380,8 +1378,7 @@ private string HandleEventIdHashValue(object value) private string HandleLevelHashValue(object value) { StringBuilder ret = new StringBuilder(); - Array levelsArray = value as Array; - if (levelsArray != null) + if (value is Array levelsArray) { ret.Append('('); for (int i = 0; i < levelsArray.Length; i++) @@ -1412,8 +1409,7 @@ private string HandleKeywordHashValue(object value) Int64 keywordsMask = 0; Int64 keywordLong = 0; - Array keywordArray = value as Array; - if (keywordArray != null) + if (value is Array keywordArray) { foreach (object keyword in keywordArray) { @@ -1568,8 +1564,7 @@ private string HandleEndTimeHashValue(object value, Hashtable hash) private string HandleDataHashValue(object value) { StringBuilder ret = new StringBuilder(); - Array dataArray = value as Array; - if (dataArray != null) + if (value is Array dataArray) { ret.Append('('); for (int i = 0; i < dataArray.Length; i++) @@ -1599,8 +1594,7 @@ private string HandleDataHashValue(object value) private string HandleNamedDataHashValue(string key, object value) { StringBuilder ret = new StringBuilder(); - Array dataArray = value as Array; - if (dataArray != null) + if (value is Array dataArray) { ret.Append('('); for (int i = 0; i < dataArray.Length; i++) @@ -1847,8 +1841,7 @@ private void CheckHashTablesForNullValues() } else { - Array eltArray = value as Array; - if (eltArray != null) + if (value is Array eltArray) { foreach (object elt in eltArray) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index 24b142a5081..dbf45090884 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -492,8 +492,7 @@ private IEnumerable GetSessionsToActAgainst(QueryBuilder queryBuilder) return this.Session; } - var sessionBoundQueryBuilder = queryBuilder as ISessionBoundQueryBuilder; - if (sessionBoundQueryBuilder != null) + if (queryBuilder is ISessionBoundQueryBuilder sessionBoundQueryBuilder) { TSession sessionOfTheQueryBuilder = sessionBoundQueryBuilder.GetTargetSession(); if (sessionOfTheQueryBuilder != null) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index 092103d6fe7..d74b66bb8aa 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -104,16 +104,14 @@ internal static CimJobException CreateFromAnyException( Dbg.Assert(jobContext != null, "Caller should verify jobContext != null"); Dbg.Assert(inner != null, "Caller should verify inner != null"); - CimException cimException = inner as CimException; - if (cimException != null) + if (inner is CimException cimException) { return CreateFromCimException(jobDescription, jobContext, cimException); } string message = BuildErrorMessage(jobDescription, jobContext, inner.Message); CimJobException cimJobException = new CimJobException(message, inner); - var containsErrorRecord = inner as IContainsErrorRecord; - if (containsErrorRecord != null) + if (inner is IContainsErrorRecord containsErrorRecord) { cimJobException.InitializeErrorRecord( jobContext, @@ -362,8 +360,7 @@ internal bool IsTerminatingError { get { - var cimException = this.InnerException as CimException; - if ((cimException == null) || (cimException.ErrorData == null)) + if ((this.InnerException is not CimException cimException) || (cimException.ErrorData == null)) { return false; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs index 990c31c73a5..194a89365eb 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs @@ -66,8 +66,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m methodParameter.Value = dotNetValue; cmdletOutput.Add(methodParameter.Name, methodParameter); - var cimInstances = dotNetValue as CimInstance[]; - if (cimInstances != null) + if (dotNetValue is CimInstance[] cimInstances) { foreach (var instance in cimInstances) { @@ -75,8 +74,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m } } - var cimInstance = dotNetValue as CimInstance; - if (cimInstance != null) + if (dotNetValue is CimInstance cimInstance) { CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session); } @@ -191,15 +189,13 @@ public override void OnNext(CimMethodResultBase item) this.ExceptionSafeWrapper( delegate { - var methodResult = item as CimMethodResult; - if (methodResult != null) + if (item is CimMethodResult methodResult) { this.OnNext(methodResult); return; } - var streamedResult = item as CimMethodStreamedResult; - if (streamedResult != null) + if (item is CimMethodStreamedResult streamedResult) { this.OnNext(streamedResult); return; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs index 73b8d0f3015..b9283207538 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs @@ -53,8 +53,7 @@ private static int GetNumberOfSessions(InvocationInfo invocationInfo) int maxNumberOfSessionsIndicatedByCimInstanceArguments = 1; foreach (object cmdletArgument in invocationInfo.BoundParameters.Values) { - CimInstance[] array = cmdletArgument as CimInstance[]; - if (array != null) + if (cmdletArgument is CimInstance[] array) { int numberOfSessionsAssociatedWithArgument = array .Select(CimCmdletAdapter.GetSessionOfOriginFromCimInstance) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs index 3e885cf60ce..d3ed3221117 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs @@ -629,8 +629,7 @@ internal void ReportJobFailure(IContainsErrorRecord exception) } else { - CimJobException cje = exception as CimJobException; - if ((cje != null) && (cje.IsTerminatingError)) + if ((exception is CimJobException cje) && (cje.IsTerminatingError)) { terminatingErrorTracker.MarkSessionAsTerminated(this.JobContext.Session, out sessionWasAlreadyTerminated); isThisTerminatingError = true; @@ -1019,8 +1018,7 @@ internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance) internal static void AddShowComputerNameMarker(PSObject pso) { - PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo; - if (psShowComputerNameProperty != null) + if (pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] is PSPropertyInfo psShowComputerNameProperty) { psShowComputerNameProperty.Value = true; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs index 4159cc07685..95d64acec40 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs @@ -36,8 +36,7 @@ public NotFoundError(string propertyName, object propertyValue, bool wildcardsEn if (wildcardsEnabled) { - var propertyValueAsString = propertyValue as string; - if ((propertyValueAsString != null) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString))) + if ((propertyValue is string propertyValueAsString) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString))) { this.ErrorMessageGenerator = (queryDescription, className) => GetErrorMessageForNotFound_ForWildcard(this.PropertyName, this.PropertyValue, className); @@ -466,8 +465,7 @@ protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object } else { - string expectedPropertyValueAsString = cimTypedExpectedPropertyValue as string; - if (expectedPropertyValueAsString != null && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString)) + if (cimTypedExpectedPropertyValue is string expectedPropertyValueAsString && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString)) { return BehaviorOnNoMatch.SilentlyContinue; } @@ -504,8 +502,7 @@ private static bool NonWildcardEqual(string propertyName, object actualPropertyV actualPropertyValue = actualPropertyValue.ToString(); } - var expectedPropertyValueAsString = expectedPropertyValue as string; - if (expectedPropertyValueAsString != null) + if (expectedPropertyValue is string expectedPropertyValueAsString) { var actualPropertyValueAsString = (string)actualPropertyValue; return actualPropertyValueAsString.Equals(expectedPropertyValueAsString, StringComparison.OrdinalIgnoreCase); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index e19a135749a..f34b0ab046d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -913,8 +913,7 @@ internal bool DoStartService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner == null + if (e.InnerException is not Win32Exception eInner || NativeMethods.ERROR_SERVICE_ALREADY_RUNNING != eInner.NativeErrorCode) { exception = e; @@ -1030,9 +1029,7 @@ internal List DoStopService(ServiceController serviceControll } catch (InvalidOperationException e) { - Win32Exception eInner = - e.InnerException as Win32Exception; - if (eInner == null + if (e.InnerException is not Win32Exception eInner || NativeMethods.ERROR_SERVICE_NOT_ACTIVE != eInner.NativeErrorCode) { exception = e; @@ -1127,8 +1124,7 @@ internal bool DoPauseService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner != null + if (e.InnerException is Win32Exception eInner && NativeMethods.ERROR_SERVICE_NOT_ACTIVE == eInner.NativeErrorCode) { serviceNotRunning = true; @@ -1208,8 +1204,7 @@ internal bool DoResumeService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner != null + if (e.InnerException is Win32Exception eInner && NativeMethods.ERROR_SERVICE_NOT_ACTIVE == eInner.NativeErrorCode) { serviceNotRunning = true; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs index 4fda5a09dd8..337f7eff451 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -557,9 +557,8 @@ private sealed class ValidateNotePropertyNameAttribute : ValidateArgumentsAttrib { protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { - string notePropertyName = arguments as string; PSMemberTypes memberType; - if (notePropertyName != null && LanguagePrimitives.TryConvertTo(notePropertyName, out memberType)) + if (arguments is string notePropertyName && LanguagePrimitives.TryConvertTo(notePropertyName, out memberType)) { switch (memberType) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs index e118aeaf41b..cf77bdfd33e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs @@ -505,9 +505,8 @@ protected override void BeginProcessing() MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; string Message = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]); WarningRecord record = new WarningRecord(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -556,16 +555,14 @@ private void WriteColumns(List mshParams) foreach (MshParameter p in mshParams) { COLTag.Append(" reader = sender as PipelineReader; - if (reader != null && reader.IsOpen) + if (sender is PipelineReader reader && reader.IsOpen) { WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Output); } @@ -449,8 +447,7 @@ private void HandlePipelineOutputDataReady(object sender, EventArgs e) private void HandlePipelineErrorDataReady(object sender, EventArgs e) { - PipelineReader reader = sender as PipelineReader; - if (reader != null && reader.IsOpen) + if (sender is PipelineReader reader && reader.IsOpen) { WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Error); } @@ -537,8 +534,7 @@ private void EnableHostDebugger(Runspace runspace, bool enabled) // Only enable and disable the host's runspace if we are in process attach mode. if (_debugger is ServerRemoteDebugger) { - LocalRunspace localRunspace = runspace as LocalRunspace; - if ((localRunspace != null) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null)) + if ((runspace is LocalRunspace localRunspace) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null)) { try { @@ -551,8 +547,7 @@ private void EnableHostDebugger(Runspace runspace, bool enabled) private void SetLocalMode(System.Management.Automation.Debugger debugger, bool localMode) { - ServerRemoteDebugger remoteDebugger = debugger as ServerRemoteDebugger; - if (remoteDebugger != null) + if (debugger is ServerRemoteDebugger remoteDebugger) { remoteDebugger.LocalDebugMode = localMode; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs index 3db37f3528e..974188c2f74 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs @@ -33,15 +33,13 @@ internal override object GetValue(PSObject liveObject) // The live object has the liveObjectPropertyName property. object liveObjectValue = propertyInfo.Value; - ICollection collectionValue = liveObjectValue as ICollection; - if (collectionValue != null) + if (liveObjectValue is ICollection collectionValue) { liveObjectValue = _parentCmdlet.ConvertToString(PSObjectHelper.AsPSObject(propertyInfo.Value)); } else { - PSObject psObjectValue = liveObjectValue as PSObject; - if (psObjectValue != null) + if (liveObjectValue is PSObject psObjectValue) { // Since PSObject implements IComparable there is a need to verify if its BaseObject actually implements IComparable. if (psObjectValue.BaseObject is IComparable) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs index e5c418044fe..b2c92c4be1e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs @@ -180,8 +180,7 @@ protected override void ProcessRecord() return; } - IDictionary dictionary = InputObject.BaseObject as IDictionary; - if (dictionary != null) + if (InputObject.BaseObject is IDictionary dictionary) { // Dictionaries should be enumerated through because the pipeline does not enumerate through them. foreach (DictionaryEntry entry in dictionary) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs index 446b2f2568f..7ae61e353f7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -80,8 +80,7 @@ internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] t catch (TargetInvocationException ex) { // Verify if this is an error loading the System.Core dll. - FileNotFoundException fileNotFoundEx = ex.InnerException as FileNotFoundException; - if (fileNotFoundEx != null && fileNotFoundEx.FileName.Contains("System.Core")) + if (ex.InnerException is FileNotFoundException fileNotFoundEx && fileNotFoundEx.FileName.Contains("System.Core")) { _parentCmdlet.ThrowTerminatingError( new ErrorRecord(new InvalidOperationException( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index dc967889e69..e9610745c97 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -69,8 +69,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod if (token != null) { - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { if (displayName == null) { @@ -101,8 +100,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod } else { - TextToken tt = token as TextToken; - if (tt != null) + if (token is TextToken tt) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs index 70967aa897b..d935c0297b0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs @@ -140,22 +140,19 @@ protected override void ProcessRecord() PSControl control; - var tableControlBody = definition.mainControl as TableControlBody; - if (tableControlBody != null) + if (definition.mainControl is TableControlBody tableControlBody) { control = new TableControl(tableControlBody, definition); } else { - var listControlBody = definition.mainControl as ListControlBody; - if (listControlBody != null) + if (definition.mainControl is ListControlBody listControlBody) { control = new ListControl(listControlBody, definition); } else { - var wideControlBody = definition.mainControl as WideControlBody; - if (wideControlBody != null) + if (definition.mainControl is WideControlBody wideControlBody) { control = new WideControl(wideControlBody, definition); if (writeOldWay) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index 2789aaafe61..36910cbdf26 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -231,8 +231,7 @@ protected override void ProcessRecord() { if (!Force) { - PSMethod memberAsPSMethod = member as PSMethod; - if ((memberAsPSMethod != null) && (memberAsPSMethod.IsSpecial)) + if ((member is PSMethod memberAsPSMethod) && (memberAsPSMethod.IsSpecial)) { continue; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 4aa59024439..c009cf49f56 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -729,8 +729,7 @@ private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeExcepti // // handle recognized types of exceptions first // - RemoteException remoteException = runtimeException as RemoteException; - if ((remoteException != null) && (remoteException.SerializedRemoteException != null)) + if ((runtimeException is RemoteException remoteException) && (remoteException.SerializedRemoteException != null)) { if (Deserializer.IsInstanceOfType(remoteException.SerializedRemoteException, typeof(CommandNotFoundException))) { @@ -1580,8 +1579,7 @@ private PowerShell BuildPowerShellForGetFormatData() powerShell.AddParameter("TypeName", this.FormatTypeName); // For remote PS version 5.1 and greater, we need to include the new -PowerShellVersion parameter - RemoteRunspace remoteRunspace = Session.Runspace as RemoteRunspace; - if ((remoteRunspace != null) && (remoteRunspace.ServerVersion != null) && + if ((Session.Runspace is RemoteRunspace remoteRunspace) && (remoteRunspace.ServerVersion != null) && (remoteRunspace.ServerVersion >= new Version(5, 1))) { powerShell.AddParameter("PowerShellVersion", PSVersionInfo.PSVersion); @@ -1947,20 +1945,17 @@ internal ImplicitRemotingCodeGenerator( /// Connection URI associated with the remote runspace. private string GetConnectionString() { - WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (connectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo connectionInfo) { return connectionInfo.ConnectionUri.ToString(); } - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { return vmConnectionInfo.ComputerName; } - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { return containerConnectionInfo.ComputerName; } @@ -2249,8 +2244,7 @@ private string GenerateNewPSSessionOption() { StringBuilder result = new StringBuilder("& $script:NewPSSessionOption "); - RunspaceConnectionInfo runspaceConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as RunspaceConnectionInfo; - if (runspaceConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is RunspaceConnectionInfo runspaceConnectionInfo) { result.AppendFormat(null, "-Culture '{0}' ", CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.Culture.ToString())); result.AppendFormat(null, "-UICulture '{0}' ", CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.UICulture.ToString())); @@ -2261,22 +2255,28 @@ private string GenerateNewPSSessionOption() result.AppendFormat(null, "-OperationTimeOut {0} ", runspaceConnectionInfo.OperationTimeout); } - WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo) { - if (!wsmanConnectionInfo.UseCompression) { result.Append("-NoCompression "); } + if (!wsmanConnectionInfo.UseCompression) + { result.Append("-NoCompression "); } - if (wsmanConnectionInfo.NoEncryption) { result.Append("-NoEncryption "); } + if (wsmanConnectionInfo.NoEncryption) + { result.Append("-NoEncryption "); } - if (wsmanConnectionInfo.NoMachineProfile) { result.Append("-NoMachineProfile "); } + if (wsmanConnectionInfo.NoMachineProfile) + { result.Append("-NoMachineProfile "); } - if (wsmanConnectionInfo.UseUTF16) { result.Append("-UseUTF16 "); } + if (wsmanConnectionInfo.UseUTF16) + { result.Append("-UseUTF16 "); } - if (wsmanConnectionInfo.SkipCACheck) { result.Append("-SkipCACheck "); } + if (wsmanConnectionInfo.SkipCACheck) + { result.Append("-SkipCACheck "); } - if (wsmanConnectionInfo.SkipCNCheck) { result.Append("-SkipCNCheck "); } + if (wsmanConnectionInfo.SkipCNCheck) + { result.Append("-SkipCNCheck "); } - if (wsmanConnectionInfo.SkipRevocationCheck) { result.Append("-SkipRevocationCheck "); } + if (wsmanConnectionInfo.SkipRevocationCheck) + { result.Append("-SkipRevocationCheck "); } if (wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.HasValue) { @@ -2521,8 +2521,7 @@ private string GenerateReimportingOfModules() private string GenerateNewRunspaceExpression() { - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { string vmConfigurationName = vmConnectionInfo.ConfigurationName; return string.Format( @@ -2534,8 +2533,7 @@ private string GenerateNewRunspaceExpression() } else { - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { string containerConfigurationName = containerConnectionInfo.ContainerProc.ConfigurationName; return string.Format( @@ -2577,19 +2575,16 @@ private string GenerateNewRunspaceExpression() /// private string GenerateConnectionStringForNewRunspace() { - WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (connectionInfo == null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is not WSManConnectionInfo connectionInfo) { - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { return string.Format(CultureInfo.InvariantCulture, VMIdParameterTemplate, CodeGeneration.EscapeSingleQuotedStringContent(vmConnectionInfo.VMGuid.ToString())); } - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { return string.Format(CultureInfo.InvariantCulture, ContainerIdParameterTemplate, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index 8e28c630e17..ca29fae4ae2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -169,8 +169,7 @@ private static bool CheckIsText(string contentType) { if (contentTypeKey != null) { - string extension = contentTypeKey.GetValue("Extension") as string; - if (extension != null) + if (contentTypeKey.GetValue("Extension") is string extension) { using (RegistryKey extensionKey = Registry.ClassesRoot.OpenSubKey(extension)) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 0809b686e1b..c3ca35d2cd6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1210,8 +1210,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) object content = Body; // make sure we're using the base object of the body, not the PSObject wrapper - PSObject psBody = Body as PSObject; - if (psBody != null) + if (Body is PSObject psBody) { content = psBody.BaseObject; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index 70c5721dbc1..a43ef2df9b2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -186,8 +186,7 @@ private void SetResponse(HttpResponseMessage response, Stream contentStream) BaseResponse = response; - MemoryStream ms = contentStream as MemoryStream; - if (ms != null) + if (contentStream is MemoryStream ms) { _rawContentStream = ms; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index 7e5a4ba6d63..db9cdd1d13a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -590,15 +590,13 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso } else { - IDictionary dict = obj as IDictionary; - if (dict != null) + if (obj is IDictionary dict) { rv = ProcessDictionary(dict, currentDepth, in context); } else { - IEnumerable enumerable = obj as IEnumerable; - if (enumerable != null) + if (obj is IEnumerable enumerable) { rv = ProcessEnumerable(enumerable, currentDepth, in context); } @@ -645,9 +643,8 @@ private static object AddPsProperties(object psObj, object obj, int depth, bool } bool wasDictionary = true; - IDictionary dict = obj as IDictionary; - if (dict == null) + if (obj is not IDictionary dict) { wasDictionary = false; dict = new Dictionary(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs index 6f374336da5..7e0df55ff87 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -33,15 +33,13 @@ protected override void ProcessRecord() // so we create the DebugRecord here and fill it up with the appropriate InvocationInfo; // then, we call the command runtime directly and pass this record to WriteDebug(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { DebugRecord record = new DebugRecord(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -81,15 +79,13 @@ protected override void ProcessRecord() // so we create the VerboseRecord here and fill it up with the appropriate InvocationInfo; // then, we call the command runtime directly and pass this record to WriteVerbose(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { VerboseRecord record = new VerboseRecord(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -129,15 +125,13 @@ protected override void ProcessRecord() // so we create the WarningRecord here and fill it up with the appropriate InvocationInfo; // then, we call the command runtime directly and pass this record to WriteWarning(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { WarningRecord record = new WarningRecord(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -367,8 +361,7 @@ protected override void ProcessRecord() // 2005/07/14-913791 "write-error output is confusing and misleading" // set InvocationInfo to the script not the command - InvocationInfo myInvocation = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (myInvocation != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo myInvocation) { errorRecord.SetInvocationInfo(myInvocation); errorRecord.PreserveInvocationInfoOnce = true; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index 7c2f2e44bf9..56a27ba2aad 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -52,9 +52,7 @@ private string ProcessObject(object o) { if (o != null) { - string s = o as string; - IEnumerable enumerable = null; - if (s != null) + if (o is string s) { // strings are IEnumerable, so we special case them if (s.Length > 0) @@ -62,7 +60,7 @@ private string ProcessObject(object o) return s; } } - else if ((enumerable = o as IEnumerable) != null) + else if (o is IEnumerable enumerable) { // unroll enumerables, including arrays. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 0e86cdbfa18..5f05efe481e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -763,12 +763,10 @@ internal void Import() while (!_deserializer.Done() && count < first) { object result = _deserializer.Deserialize(); - PSObject psObject = result as PSObject; - if (psObject != null) + if (result is PSObject psObject) { - ICollection c = psObject.BaseObject as ICollection; - if (c != null) + if (psObject.BaseObject is ICollection c) { foreach (object o in c) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index f6677752a91..5a547e54112 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -521,8 +521,7 @@ public override int Write(object obj, bool enumerateCollection) private static ErrorRecord ConvertToErrorRecord(object obj) { ErrorRecord result = null; - PSObject mshobj = obj as PSObject; - if (mshobj != null) + if (obj is PSObject mshobj) { object baseObject = mshobj.BaseObject; if (baseObject is not PSCustomObject) @@ -531,8 +530,7 @@ private static ErrorRecord ConvertToErrorRecord(object obj) } } - ErrorRecord errorRecordResult = obj as ErrorRecord; - if (errorRecordResult != null) + if (obj is ErrorRecord errorRecordResult) { result = errorRecordResult; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 3a1986b1226..f0537f9578f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -2051,9 +2051,8 @@ private void ReportException(Exception e, Executor exec) // NTRAID#Windows OS Bugs-1143621-2005/04/08-sburns - IContainsErrorRecord icer = e as IContainsErrorRecord; - if (icer != null) + if (e is IContainsErrorRecord icer) { error = icer.ErrorRecord; } @@ -2110,8 +2109,7 @@ private void ReportExceptionFallback(Exception e, string header) // See if the exception has an error record attached to it... ErrorRecord er = null; - IContainsErrorRecord icer = e as IContainsErrorRecord; - if (icer != null) + if (e is IContainsErrorRecord icer) er = icer.ErrorRecord; if (e is PSRemotingTransportException) @@ -2632,8 +2630,7 @@ e is RemoteException || internal void BlockCommandOutput() { - RemotePipeline rCmdPipeline = _parent.runningCmd as RemotePipeline; - if (rCmdPipeline != null) + if (_parent.runningCmd is RemotePipeline rCmdPipeline) { rCmdPipeline.DrainIncomingData(); rCmdPipeline.SuspendIncomingData(); @@ -2646,8 +2643,7 @@ internal void BlockCommandOutput() internal void ResumeCommandOutput() { - RemotePipeline rCmdPipeline = _parent.runningCmd as RemotePipeline; - if (rCmdPipeline != null) + if (_parent.runningCmd is RemotePipeline rCmdPipeline) { rCmdPipeline.ResumeIncomingData(); } @@ -2737,8 +2733,7 @@ private bool IsIncompleteParseException(Exception e) } // If it is remote exception ferret out the real exception. - RemoteException remoteException = e as RemoteException; - if (remoteException == null || remoteException.ErrorRecord == null) + if (e is not RemoteException remoteException || remoteException.ErrorRecord == null) { return false; } @@ -2797,8 +2792,7 @@ private string EvaluatePrompt() // Check for the pushed runspace scenario. if (_isRunspacePushed) { - RemoteRunspace remoteRunspace = _parent.Runspace as RemoteRunspace; - if (remoteRunspace != null) + if (_parent.Runspace is RemoteRunspace remoteRunspace) { promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); } @@ -2834,8 +2828,7 @@ private string EvaluateDebugPrompt() string promptString = (prompt != null) ? (prompt.BaseObject as string) : null; if (promptString != null) { - RemoteRunspace remoteRunspace = _parent.Runspace as RemoteRunspace; - if (remoteRunspace != null) + if (_parent.Runspace is RemoteRunspace remoteRunspace) { promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index 722bd19effb..f125e5fd7a4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -363,8 +363,7 @@ public override } catch (HostException e) { - Win32Exception win32exception = e.InnerException as Win32Exception; - if (win32exception != null && + if (e.InnerException is Win32Exception win32exception && win32exception.NativeErrorCode == 0x57) { throw PSTraceSource.NewArgumentOutOfRangeException("value", value, diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs index 306cd38b717..557f02fb88a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -109,8 +109,7 @@ private void ErrorObjectStreamHandler(object sender, EventArgs e) private void AsyncPipelineFailureHandler(Exception ex) { ErrorRecord er = null; - IContainsErrorRecord cer = ex as IContainsErrorRecord; - if (cer != null) + if (ex is IContainsErrorRecord cer) { er = cer.ErrorRecord; // Exception inside the error record is ParentContainsErrorRecordException which @@ -504,8 +503,7 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception // And convert the base object into a string. We can't use the proxied // ToString() on the PSObject because there is no default runspace // available. - PSObject msho = streamResults[0] as PSObject; - if (msho != null) + if (streamResults[0] is PSObject msho) result = msho.BaseObject.ToString(); else result = streamResults[0].ToString(); @@ -607,8 +605,7 @@ private void Cancel() internal void BlockCommandOutput() { - RemotePipeline remotePipeline = _pipeline as RemotePipeline; - if (remotePipeline != null) + if (_pipeline is RemotePipeline remotePipeline) { // Waits until queued data is handled. remotePipeline.DrainIncomingData(); @@ -620,8 +617,7 @@ internal void BlockCommandOutput() internal void ResumeCommandOutput() { - RemotePipeline remotePipeline = _pipeline as RemotePipeline; - if (remotePipeline != null) + if (_pipeline is RemotePipeline remotePipeline) { // Resumes data flow. remotePipeline.ResumeIncomingData(); diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index 072e6935624..87cc31774d2 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -291,8 +291,7 @@ to fill the passed in ETW data descriptor. { dataDescriptor->Reserved = 0; - string sRet = data as string; - if (sRet != null) + if (data is string sRet) { dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return sRet; diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs index 7fa42b31424..1a71a07e12d 100644 --- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -293,8 +293,7 @@ public static AuthorizationRuleCollection GetAccess(PSObject instance) // Get DACL AuthorizationRuleCollection dacl; - CommonObjectSecurity cos = sd as CommonObjectSecurity; - if (cos != null) + if (sd is CommonObjectSecurity cos) { dacl = cos.GetAccessRules(true, true, typeof(NTAccount)); } @@ -331,8 +330,7 @@ public static AuthorizationRuleCollection GetAudit(PSObject instance) } AuthorizationRuleCollection sacl; - CommonObjectSecurity cos = sd as CommonObjectSecurity; - if (cos != null) + if (sd is CommonObjectSecurity cos) { sacl = cos.GetAuditRules(true, true, typeof(NTAccount)); } @@ -1334,14 +1332,13 @@ protected override void ProcessRecord() if (methodInfo != null) { - CommonSecurityDescriptor aclCommonSD = _securityDescriptor as CommonSecurityDescriptor; string sddl; if (aclObjectSecurity != null) { sddl = aclObjectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All); } - else if (aclCommonSD != null) + else if (_securityDescriptor is CommonSecurityDescriptor aclCommonSD) { sddl = aclCommonSD.GetSddlForm(AccessControlSections.All); } diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index e60b817d4ec..8a6f908e699 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -726,9 +726,7 @@ protected override void RemoveItem( if (DynamicParameters != null) { - ProviderRemoveItemDynamicParameters dp = - DynamicParameters as ProviderRemoveItemDynamicParameters; - if (dp != null) + if (DynamicParameters is ProviderRemoveItemDynamicParameters dp) { if (dp.DeleteKey) { @@ -888,9 +886,8 @@ protected override void MoveItem( object store = GetItemAtPath(destination, false, out isDestContainer); X509Certificate2 certificate = cert as X509Certificate2; - X509NativeStore certstore = store as X509NativeStore; - if (certstore != null) + if (store is X509NativeStore certstore) { certstore.Open(true); @@ -1071,15 +1068,13 @@ protected override bool HasChildItems(string path) if ((item != null) && isContainer) { - X509StoreLocation storeLocation = item as X509StoreLocation; - if (storeLocation != null) + if (item is X509StoreLocation storeLocation) { result = storeLocation.StoreNames.Count > 0; } else { - X509NativeStore store = item as X509NativeStore; - if (store != null) + if (item is X509NativeStore store) { store.Open(IncludeArchivedCerts()); IntPtr certContext = store.GetFirstCert(); @@ -1262,15 +1257,13 @@ protected override void GetItem(string path) return; } - X509StoreLocation storeLocation = item as X509StoreLocation; - if (storeLocation != null) // store location + if (item is X509StoreLocation storeLocation) // store location { WriteItemObject(item, path, isContainer); } else // store { - X509NativeStore store = item as X509NativeStore; - if (store != null) + if (item is X509NativeStore store) { // create X509Store X509Store outStore = new X509Store( @@ -2658,9 +2651,7 @@ private CertificateFilterInfo GetFilter() if (DynamicParameters != null) { - CertificateProviderDynamicParameters dp = - DynamicParameters as CertificateProviderDynamicParameters; - if (dp != null) + if (DynamicParameters is CertificateProviderDynamicParameters dp) { if (dp.CodeSigningCert) { @@ -3325,8 +3316,7 @@ public EnhancedKeyUsageProperty(X509Certificate2 cert) // Filter to the OID for EKU if (extension.Oid.Value == "2.5.29.37") { - X509EnhancedKeyUsageExtension ext = extension as X509EnhancedKeyUsageExtension; - if (ext != null) + if (extension is X509EnhancedKeyUsageExtension ext) { OidCollection oids = ext.EnhancedKeyUsages; foreach (Oid oid in oids) diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index ed7c2d7771c..fcc3988f088 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -1023,9 +1023,7 @@ protected override void SetItem(string path, object value) { if (WSManStringLiterals.ConfigRunAsUserName.Equals(ChildName, StringComparison.OrdinalIgnoreCase)) { - PSCredential runAsCredentials = value as PSCredential; - - if (runAsCredentials != null) + if (value is PSCredential runAsCredentials) { // UserName value = runAsCredentials.UserName; @@ -1301,8 +1299,7 @@ protected override void SetItem(string path, object value) } } - WSManProviderSetItemDynamicParameters dynParams = DynamicParameters as WSManProviderSetItemDynamicParameters; - if (dynParams != null) + if (DynamicParameters is WSManProviderSetItemDynamicParameters dynParams) { if (dynParams.Concatenate) { @@ -1965,9 +1962,8 @@ protected override object NewItemDynamicParameters(string path, string itemTypeN private void NewItemCreateComputerConnection(string Name) { helper = new WSManHelper(this); - WSManProviderNewItemComputerParameters dynParams = DynamicParameters as WSManProviderNewItemComputerParameters; string parametersetName = "ComputerName"; - if (dynParams != null) + if (DynamicParameters is WSManProviderNewItemComputerParameters dynParams) { if (dynParams.ConnectionURI != null) { @@ -2064,8 +2060,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h // to create a new plugin if (path.EndsWith(strPathChk, StringComparison.OrdinalIgnoreCase)) { - WSManProviderNewItemPluginParameters niParams = DynamicParameters as WSManProviderNewItemPluginParameters; - if (niParams != null) + if (DynamicParameters is WSManProviderNewItemPluginParameters niParams) { if (string.IsNullOrEmpty(niParams.File)) { @@ -2155,8 +2150,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h strPathChk += WSManStringLiterals.containerResources; if (path.EndsWith(strPathChk, StringComparison.OrdinalIgnoreCase)) { - WSManProviderNewItemResourceParameters niParams = DynamicParameters as WSManProviderNewItemResourceParameters; - if (niParams != null) + if (DynamicParameters is WSManProviderNewItemResourceParameters niParams) { mshObj.Properties.Add(new PSNoteProperty("Resource", niParams.ResourceUri)); mshObj.Properties.Add(new PSNoteProperty("Capability", niParams.Capability)); @@ -5193,10 +5187,9 @@ private object ValidateAndGetUserObject(string configurationName, object value) /// Value to append. private string GetStringFromSecureString(object propertyValue) { - SecureString value = propertyValue as SecureString; string passwordValueToAdd = string.Empty; - if (value != null) + if (propertyValue is SecureString value) { IntPtr ptr = Marshal.SecureStringToBSTR(value); passwordValueToAdd = Marshal.PtrToStringAuto(ptr); diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 1d6ff12f270..1745a9ec1cc 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -1941,8 +1941,7 @@ private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatem object evalResultObject; if (IsConstantValueVisitor.IsConstant(pair.Item1, out evalResultObject, forAttribute: false, forRequires: false)) { - var presentName = evalResultObject as string; - if (presentName != null) + if (evalResultObject is string presentName) { if (mandatoryPropertiesNames.Remove(presentName) && mandatoryPropertiesNames.Count == 0) { @@ -2305,8 +2304,7 @@ internal static string GenerateMofForAst(TypeDefinitionAst typeAst) internal static string MapTypeNameToMofType(ITypeName typeName, string memberName, string className, out bool isArrayType, out string embeddedInstanceType, List embeddedInstanceTypes, ref string[] enumNames) { TypeName propTypeName; - var arrayTypeName = typeName as ArrayTypeName; - if (arrayTypeName != null) + if (typeName is ArrayTypeName arrayTypeName) { isArrayType = true; propTypeName = arrayTypeName.ElementType as TypeName; @@ -2369,15 +2367,13 @@ private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder s while (bases.Count > 0) { var b = bases.Dequeue(); - var tc = b as TypeConstraintAst; - if (tc != null) + if (b is TypeConstraintAst tc) { b = tc.TypeName.GetReflectionType(); if (b == null) { - var td = tc.TypeName as TypeName; - if (td != null && td._typeDefinitionAst != null) + if (tc.TypeName is TypeName td && td._typeDefinitionAst != null) { ProcessMembers(sb, embeddedInstanceTypes, td._typeDefinitionAst, className); foreach (var b1 in td._typeDefinitionAst.BaseTypes) @@ -2419,8 +2415,7 @@ private static bool GetResourceMethodsLineNumber(TypeDefinitionAst typeDefinitio methodsLinePosition = new Dictionary(); foreach (var member in typeDefinitionAst.Members) { - var functionMemberAst = member as FunctionMemberAst; - if (functionMemberAst != null) + if (member is FunctionMemberAst functionMemberAst) { if (functionMemberAst.Name.Equals(getMethodName, StringComparison.OrdinalIgnoreCase)) { @@ -2500,9 +2495,7 @@ private static void ProcessMembers(StringBuilder sb, List embeddedInstan { foreach (var member in typeDefinitionAst.Members) { - var property = member as PropertyMemberAst; - - if (property == null || property.IsStatic || + if (member is not PropertyMemberAst property || property.IsStatic || property.Attributes.All(a => a.TypeName.GetReflectionAttributeType() != typeof(DscPropertyAttribute))) { continue; @@ -2607,13 +2600,13 @@ private static bool GetResourceDefinitionsFromModule(string fileName, out IEnume resourceDefinitions = ast.FindAll(n => { - var typeAst = n as TypeDefinitionAst; - if (typeAst != null) + if (n is TypeDefinitionAst typeAst) { for (int i = 0; i < typeAst.Attributes.Count; i++) { var a = typeAst.Attributes[i]; - if (a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute)) return true; + if (a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute)) + return true; } } @@ -2679,8 +2672,7 @@ private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo m { if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase)) { - var dscResourceAttribute = attr.GetAttribute() as DscResourceAttribute; - if (dscResourceAttribute != null) + if (attr.GetAttribute() is DscResourceAttribute dscResourceAttribute) { runAsBehavior = dscResourceAttribute.RunAsCredential; } @@ -2917,8 +2909,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable bool needComma = false; foreach (var attr in customAttributes) { - var dscProperty = attr as DscPropertyAttribute; - if (dscProperty != null) + if (attr is DscPropertyAttribute dscProperty) { if (dscProperty.Key) { @@ -2941,8 +2932,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable continue; } - var validateSet = attr as ValidateSetAttribute; - if (validateSet != null) + if (attr is ValidateSetAttribute validateSet) { bool valueMapComma = false; StringBuilder sbValues = new StringBuilder(", Values{"); diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs index 736381e9479..31b1f6021b7 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs @@ -176,15 +176,13 @@ internal override object Verify(object val, // need to check the type: // it can be a string or a script block - ScriptBlock sb = val as ScriptBlock; - if (sb != null) + if (val is ScriptBlock sb) { PSPropertyExpression ex = new PSPropertyExpression(sb); return ex; } - string s = val as string; - if (s != null) + if (val is string s) { if (string.IsNullOrEmpty(s)) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index c958cf3c064..a5b82a55dee 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -135,9 +135,8 @@ private bool ProcessObject(PSObject so) } // no need for formatting, just process the object - FormatStartData formatStart = o as FormatStartData; - if (formatStart != null) + if (o is FormatStartData formatStart) { // get autosize flag from object // turn on group caching @@ -149,8 +148,7 @@ private bool ProcessObject(PSObject so) else { // If the format info doesn't define column widths, then auto-size based on the first ten elements - TableHeaderInfo headerInfo = formatStart.shapeInfo as TableHeaderInfo; - if ((headerInfo != null) && + if ((formatStart.shapeInfo is TableHeaderInfo headerInfo) && (headerInfo.tableColumnInfoList.Count > 0) && (headerInfo.tableColumnInfoList[0].width == 0)) { @@ -262,8 +260,7 @@ private enum PreprocessingState { raw, processed, error } /// Whether the object needs to be shunted to preprocessing. private bool NeedsPreprocessing(object o) { - FormatEntryData fed = o as FormatEntryData; - if (fed != null) + if (o is FormatEntryData fed) { // we got an already pre-processed object if (!fed.outOfBand) @@ -326,8 +323,7 @@ private void ValidateCurrentFormattingState(FormattingState expectedFormattingSt // need to abort the command string violatingCommand = "format-*"; - StartData sdObj = obj as StartData; - if (sdObj != null) + if (obj is StartData sdObj) { if (sdObj.shapeInfo is WideViewHeaderInfo) { @@ -387,18 +383,16 @@ private FormatMessagesContextManager.OutputContext CreateOutputContext( FormatMessagesContextManager.OutputContext parentContext, FormatInfoData formatInfoData) { - FormatStartData formatStartData = formatInfoData as FormatStartData; // initialize the format context - if (formatStartData != null) + if (formatInfoData is FormatStartData formatStartData) { FormatOutputContext foc = new FormatOutputContext(parentContext, formatStartData); return foc; } - GroupStartData gsd = formatInfoData as GroupStartData; // we are starting a group, initialize the group context - if (gsd != null) + if (formatInfoData is GroupStartData gsd) { GroupOutputContext goc = null; @@ -541,8 +535,7 @@ private void ProcessPayload(FormatEntryData fed, FormatMessagesContextManager.Ou private void ProcessOutOfBandPayload(FormatEntryData fed) { // try if it is raw text - RawTextFormatEntry rte = fed.formatEntryInfo as RawTextFormatEntry; - if (rte != null) + if (fed.formatEntryInfo is RawTextFormatEntry rte) { if (fed.isHelpObject) { @@ -560,8 +553,7 @@ private void ProcessOutOfBandPayload(FormatEntryData fed) } // try if it is a complex entry - ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry; - if (cve != null && cve.formatValueList != null) + if (fed.formatEntryInfo is ComplexViewEntry cve && cve.formatValueList != null) { ComplexWriter complexWriter = new ComplexWriter(); @@ -571,8 +563,7 @@ private void ProcessOutOfBandPayload(FormatEntryData fed) return; } // try if it is a list view - ListViewEntry lve = fed.formatEntryInfo as ListViewEntry; - if (lve != null && lve.listViewFieldList != null) + if (fed.formatEntryInfo is ListViewEntry lve && lve.listViewFieldList != null) { ListWriter listWriter = new ListWriter(); @@ -624,9 +615,7 @@ private FormatOutputContext FormatContext { for (FormatMessagesContextManager.OutputContext oc = _ctxManager.ActiveOutputContext; oc != null; oc = oc.ParentContext) { - FormatOutputContext foc = oc as FormatOutputContext; - - if (foc != null) + if (oc is FormatOutputContext foc) return foc; } @@ -651,17 +640,15 @@ private void ProcessCachedGroup(FormatStartData formatStartData, List internal override void Initialize() { - TableFormattingHint tableHint = this.InnerCommand.RetrieveFormattingHint() as TableFormattingHint; int[] columnWidthsHint = null; // We expect that console width is less then 120. - if (tableHint != null) + if (this.InnerCommand.RetrieveFormattingHint() is TableFormattingHint tableHint) { columnWidthsHint = tableHint.columnWidths; } @@ -1203,12 +1189,11 @@ internal override void Initialize() int itemsPerRow = 2; // get the header info and the view hint - WideFormattingHint hint = this.InnerCommand.RetrieveFormattingHint() as WideFormattingHint; int columnsOnTheScreen = GetConsoleWindowWidth(this.InnerCommand._lo.ColumnNumber); // give a preference to the hint, if there - if (hint != null && hint.maxWidth > 0) + if (this.InnerCommand.RetrieveFormattingHint() is WideFormattingHint hint && hint.maxWidth > 0) { itemsPerRow = TableWriter.ComputeWideViewBestItemsPerRowFit(hint.maxWidth, columnsOnTheScreen); } @@ -1389,8 +1374,7 @@ internal override void Initialize() /// FormatEntryData to process. internal override void ProcessPayload(FormatEntryData fed) { - ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry; - if (cve == null || cve.formatValueList == null) + if (fed.formatEntryInfo is not ComplexViewEntry cve || cve.formatValueList == null) return; _writer.WriteObject(cve.formatValueList); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs index eaec4f7b31c..7d223e278b2 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs @@ -68,8 +68,7 @@ private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth) { foreach (object obj in fe.formatValueList) { - FormatEntry feChild = obj as FormatEntry; - if (feChild != null) + if (obj is FormatEntry feChild) { if (currentDepth < maxRecursionDepth) { @@ -98,15 +97,13 @@ private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth) continue; } - FormatTextField ftf = obj as FormatTextField; - if (ftf != null) + if (obj is FormatTextField ftf) { this.AddToBuffer(ftf.text); continue; } - FormatPropertyField fpf = obj as FormatPropertyField; - if (fpf != null) + if (obj is FormatPropertyField fpf) { this.AddToBuffer(fpf.propertyValue); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index 773eb9d3777..1305f89f5e2 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -386,8 +386,7 @@ private bool MatchNodeNameHelper(XmlNode n, string s, bool allowAttributes) if (match && !allowAttributes) { - XmlElement e = n as XmlElement; - if (e != null && e.Attributes.Count > 0) + if (n is XmlElement e && e.Attributes.Count > 0) { // Error at XPath {0} in file {1}: The XML Element {2} does not allow attributes. ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.AttributesNotAllowed, ComputeCurrentXPath(), FilePath, n.Name)); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs index d3290c18752..05014149a84 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs @@ -179,14 +179,12 @@ internal static CustomItemBase Create(FormatToken token) return new CustomItemNewline(); } - var textToken = token as TextToken; - if (textToken != null) + if (token is TextToken textToken) { return new CustomItemText { Text = textToken.text }; } - var frameToken = token as FrameToken; - if (frameToken != null) + if (token is FrameToken frameToken) { var frame = new CustomItemFrame { @@ -211,8 +209,7 @@ internal static CustomItemBase Create(FormatToken token) return frame; } - var cpt = token as CompoundPropertyToken; - if (cpt != null) + if (token is CompoundPropertyToken cpt) { var cie = new CustomItemExpression { EnumerateCollection = cpt.enumerateCollection }; @@ -234,8 +231,7 @@ internal static CustomItemBase Create(FormatToken token) return cie; } - var fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs index 6025acfff44..71ea209e91c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs @@ -319,8 +319,7 @@ internal ListControlEntryItem(ListControlItemDefinition definition) Label = definition.label.text; } - FieldPropertyToken fpt = definition.formatTokenList[0] as FieldPropertyToken; - if (fpt != null) + if (definition.formatTokenList[0] is FieldPropertyToken fpt) { if (fpt.fieldFormattingDirective.formatString != null) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs index b9d1e897068..9f22fcd5608 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs @@ -446,10 +446,9 @@ internal TableControlRow(TableRowDefinition rowdefinition) : this() foreach (TableRowItemDefinition itemdef in rowdefinition.rowItemDefinitionList) { - FieldPropertyToken fpt = itemdef.formatTokenList[0] as FieldPropertyToken; TableControlColumn column; - if (fpt != null) + if (itemdef.formatTokenList[0] is FieldPropertyToken fpt) { column = new TableControlColumn(fpt.expression.expressionValue, itemdef.alignment, fpt.expression.isScriptBlock, fpt.fieldFormattingDirective.formatString); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs index 05e3e79923b..1ca00966e62 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs @@ -205,8 +205,7 @@ internal WideControlEntryItem() internal WideControlEntryItem(WideControlEntryDefinition definition) : this() { - FieldPropertyToken fpt = definition.formatTokenList[0] as FieldPropertyToken; - if (fpt != null) + if (definition.formatTokenList[0] is FieldPropertyToken fpt) { DisplayEntry = new DisplayEntry(fpt.expression); FormatString = fpt.fieldFormattingDirective.formatString; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 9547ac1e072..6075ad1b47c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -143,9 +143,8 @@ private int ComputeBestMatch(AppliesTo appliesTo, PSObject currentObject) } int currentMatch = BestMatchIndexUndefined; - TypeReference tr = r as TypeReference; - if (tr != null) + if (r is TypeReference tr) { // we have a type currentMatch = MatchTypeIndex(tr.name, currentObject, ex); @@ -486,9 +485,8 @@ private static void TraceHelper(ViewDefinition vd, bool isMatched) foreach (TypeOrGroupReference togr in vd.appliesTo.referenceList) { StringBuilder sb = new StringBuilder(); - TypeReference tr = togr as TypeReference; sb.Append(isMatched ? "MATCH FOUND" : "NOT MATCH"); - if (tr != null) + if (togr is TypeReference tr) { sb.AppendFormat(CultureInfo.InvariantCulture, " {0} NAME: {1} TYPE: {2}", ControlBase.GetControlShapeName(vd.mainControl), vd.name, tr.name); @@ -593,8 +591,7 @@ internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo a foreach (TypeOrGroupReference r in appliesTo.referenceList) { // if it is a type reference, just add the type name - TypeReference tr = r as TypeReference; - if (tr != null) + if (r is TypeReference tr) { if (!allTypes.Contains(tr.name)) allTypes.Add(tr.name); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 3347cfcd6ad..22b0590bd47 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -1082,20 +1082,17 @@ private ComplexControlEntryDefinition LoadComplexControlEntryDefinitionFromObjec private FormatToken LoadFormatTokenFromObjectModel(CustomItemBase item, int viewIndex, string typeName) { - var newline = item as CustomItemNewline; - if (newline != null) + if (item is CustomItemNewline newline) { return new NewLineToken { count = newline.Count }; } - var text = item as CustomItemText; - if (text != null) + if (item is CustomItemText text) { return new TextToken { text = text.Text }; } - var expr = item as CustomItemExpression; - if (expr != null) + if (item is CustomItemExpression expr) { var cpt = new CompoundPropertyToken { enumerateCollection = expr.EnumerateCollection }; @@ -1763,9 +1760,8 @@ private TextToken LoadTextToken(XmlNode n) private bool LoadStringResourceReference(XmlNode n, out StringResourceReference resource) { resource = null; - XmlElement e = n as XmlElement; - if (e == null) + if (n is not XmlElement e) { // Error at XPath {0} in file {1}: Node should be an XmlElement. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NonXmlElementNode, ComputeCurrentXPath(), FilePath)); diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs index 5ccfada75fa..2ad8cc29fbf 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs @@ -63,8 +63,7 @@ internal OutputContext(OutputContext parentContextInStack) internal void Process(object o) { PacketInfoData formatData = o as PacketInfoData; - FormatEntryData fed = formatData as FormatEntryData; - if (fed != null) + if (formatData is FormatEntryData fed) { OutputContext ctx = null; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs index f29033e3c8d..82a7bf12815 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs @@ -143,8 +143,7 @@ private void InitializeAutoSize() // check if we have a view with autosize checked if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.mainControl != null) { - ControlBody controlBody = this.dataBaseInfo.view.mainControl as ControlBody; - if (controlBody != null && controlBody.autosize.HasValue) + if (this.dataBaseInfo.view.mainControl is ControlBody controlBody && controlBody.autosize.HasValue) { _autosize = controlBody.autosize.Value; } @@ -439,16 +438,14 @@ protected FormatPropertyField GenerateFormatPropertyField(List form if (formatTokenList.Count != 0) { FormatToken token = formatTokenList[0]; - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo); fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, ex, fpt.fieldFormattingDirective, out result); } else { - TextToken tt = token as TextToken; - if (tt != null) + if (token is TextToken tt) fpf.propertyValue = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs index 7b82b6972b2..f48976640ad 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs @@ -107,8 +107,7 @@ private bool ExecuteFormatControl(TraversalInfo level, ControlBase control, ComplexControlBody complexBody = null; // we might have a reference - ControlReference controlReference = control as ControlReference; - if (controlReference != null && controlReference.controlType == typeof(ComplexControlBody)) + if (control is ControlReference controlReference && controlReference.controlType == typeof(ComplexControlBody)) { // retrieve the reference complexBody = DisplayDataQuery.ResolveControlReference( @@ -205,8 +204,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, #region foreach loop foreach (FormatToken t in formatTokenList) { - TextToken tt = t as TextToken; - if (tt != null) + if (t is TextToken tt) { FormatTextField ftf = new FormatTextField(); ftf.text = _db.displayResourceManagerCache.GetTextTokenString(tt); @@ -214,8 +212,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, continue; } - var newline = t as NewLineToken; - if (newline != null) + if (t is NewLineToken newline) { for (int i = 0; i < newline.count; i++) { @@ -225,8 +222,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, continue; } - FrameToken ft = t as FrameToken; - if (ft != null) + if (t is FrameToken ft) { // instantiate a new entry and attach a frame info object FormatEntry feFrame = new FormatEntry(); @@ -244,9 +240,9 @@ private void ExecuteFormatTokenList(TraversalInfo level, fe.formatValueList.Add(feFrame); continue; } + #region CompoundPropertyToken - CompoundPropertyToken cpt = t as CompoundPropertyToken; - if (cpt != null) + if (t is CompoundPropertyToken cpt) { if (!EvaluateDisplayCondition(so, cpt.conditionToken)) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs index 2ded68cd510..31eb5f3cf0c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs @@ -114,8 +114,7 @@ private ListViewEntry GenerateListViewEntryFromDataBaseInfo(PSObject so, int enu // we try to fall back and see if we have an un-resolved PSPropertyExpression FormatToken token = listItem.formatTokenList[0]; - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo); @@ -124,8 +123,7 @@ private ListViewEntry GenerateListViewEntryFromDataBaseInfo(PSObject so, int enu } else { - TextToken tt = token as TextToken; - if (tt != null) + if (token is TextToken tt) // we had a text token, use it as a label (last resort...) lvf.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index ab4912c8838..bcb03b7002b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -187,15 +187,13 @@ private TableHeaderInfo GenerateTableHeaderInfoFromDataBaseInfo(PSObject so) token = rowItem.formatTokenList[0]; if (token != null) { - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { ci.label = fpt.expression.expressionValue; } else { - TextToken tt = token as TextToken; - if (tt != null) + if (token is TextToken tt) { ci.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs index 14ef93ca37e..7fab280ac12 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs @@ -646,8 +646,7 @@ private static ErrorRecord GenerateErrorRecord(FormattingError error) { ErrorRecord errorRecord = null; string msg = null; - PSPropertyExpressionError psPropertyExpressionError = error as PSPropertyExpressionError; - if (psPropertyExpressionError != null) + if (error is PSPropertyExpressionError psPropertyExpressionError) { errorRecord = new ErrorRecord( psPropertyExpressionError.result.Exception, @@ -660,8 +659,7 @@ private static ErrorRecord GenerateErrorRecord(FormattingError error) errorRecord.ErrorDetails = new ErrorDetails(msg); } - StringFormatError formattingError = error as StringFormatError; - if (formattingError != null) + if (error is StringFormatError formattingError) { errorRecord = new ErrorRecord( formattingError.exception, diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs index bb2c8ff93e7..68db554c0e3 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs @@ -385,8 +385,7 @@ internal void WriteCustomControl(CustomControl customControl) internal void WriteCustomItem(CustomItemBase item) { - var newline = item as CustomItemNewline; - if (newline != null) + if (item is CustomItemNewline newline) { for (int i = 0; i < newline.Count; i++) { @@ -396,15 +395,13 @@ internal void WriteCustomItem(CustomItemBase item) return; } - var text = item as CustomItemText; - if (text != null) + if (item is CustomItemText text) { _writer.WriteElementString("Text", text.Text); return; } - var expr = item as CustomItemExpression; - if (expr != null) + if (item is CustomItemExpression expr) { _writer.WriteStartElement("ExpressionBinding"); if (expr.EnumerateCollection) diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs index b9a7968a645..f75dddb09b6 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -30,8 +30,7 @@ internal FormatObjectDeserializer(TerminatingErrorContext errorContext) internal bool IsFormatInfoData(PSObject so) { - var fid = PSObject.Base(so) as FormatInfoData; - if (fid != null) + if (PSObject.Base(so) is FormatInfoData fid) { if (fid is FormatStartData || fid is FormatEndData || @@ -86,8 +85,7 @@ fid is GroupEndData || /// Deserialized object or null. internal object Deserialize(PSObject so) { - var fid = PSObject.Base(so) as FormatInfoData; - if (fid != null) + if (PSObject.Base(so) is FormatInfoData fid) { if (fid is FormatStartData || fid is FormatEndData || diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs index 11817de4ab2..63c0aceb8f5 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs @@ -43,8 +43,7 @@ internal OutputGroupQueue(FormattedObjectsCache.ProcessCachedGroupNotification c /// Objects the cache needs to return. It can be null. internal List Add(PacketInfoData o) { - FormatStartData fsd = o as FormatStartData; - if (fsd != null) + if (o is FormatStartData fsd) { // just cache the reference (used during the notification call) _formatStartData = fsd; @@ -120,9 +119,8 @@ private void UpdateObjectCount(PacketInfoData o) { // add only of it's not a control message // and it's not out of band - FormatEntryData fed = o as FormatEntryData; - if (fed == null || fed.outOfBand) + if (o is not FormatEntryData fed || fed.outOfBand) return; _currentObjectCount++; @@ -139,8 +137,7 @@ private void Notify() foreach (PacketInfoData x in _queue) { - FormatEntryData fed = x as FormatEntryData; - if (fed != null && fed.outOfBand) + if (x is FormatEntryData fed && fed.outOfBand) continue; validObjects.Add(x); diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs index b0d0a091fc0..f4214472a62 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs @@ -114,8 +114,7 @@ internal static PSPropertyExpressionResult GetDisplayName(PSObject target, PSPro /// Object to extract the IEnumerable from. internal static IEnumerable GetEnumerable(object obj) { - PSObject mshObj = obj as PSObject; - if (mshObj != null) + if (obj is PSObject mshObj) { obj = mshObj.BaseObject; } @@ -220,8 +219,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex IEnumerator enumerator = e.GetEnumerator(); if (enumerator != null) { - IBlockingEnumerator be = enumerator as IBlockingEnumerator; - if (be != null) + if (enumerator is IBlockingEnumerator be) { while (be.MoveNext(false)) { @@ -388,8 +386,7 @@ private static List GetDefaultPropertySet(PSMemberSet stan { if (standardMembersSet != null) { - PSPropertySet defaultDisplayPropertySet = standardMembersSet.Members[TypeTable.DefaultDisplayPropertySet] as PSPropertySet; - if (defaultDisplayPropertySet != null) + if (standardMembersSet.Members[TypeTable.DefaultDisplayPropertySet] is PSPropertySet defaultDisplayPropertySet) { List retVal = new List(); foreach (string prop in defaultDisplayPropertySet.ReferencedPropertyNames) @@ -427,8 +424,7 @@ private static PSPropertyExpression GetDefaultNameExpression(PSMemberSet standar { if (standardMembersSet != null) { - PSNoteProperty defaultDisplayProperty = standardMembersSet.Members[TypeTable.DefaultDisplayProperty] as PSNoteProperty; - if (defaultDisplayProperty != null) + if (standardMembersSet.Members[TypeTable.DefaultDisplayProperty] is PSNoteProperty defaultDisplayProperty) { string expressionString = defaultDisplayProperty.Value.ToString(); if (string.IsNullOrEmpty(expressionString)) diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index b9419c1ec0e..9416d327ded 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -215,8 +215,7 @@ public List ResolveNames(PSObject target, bool expand) foreach (PSMemberInfo member in members) { // it can be a property set - PSPropertySet propertySet = member as PSPropertySet; - if (propertySet != null) + if (member is PSPropertySet propertySet) { if (expand) { diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs index 2582a1e68db..727bcecbb26 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs @@ -70,9 +70,8 @@ protected override void BeginProcessing() ((OutputManagerInner)this.implementation).LineOutput = lineOutput; - MshCommandRuntime mrt = this.CommandRuntime as MshCommandRuntime; - if (mrt != null) + if (this.CommandRuntime is MshCommandRuntime mrt) { mrt.MergeUnclaimedPreviousErrorResults = true; } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index 81a4c33062f..bac0eab97f4 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -62,20 +62,17 @@ internal IEnumerable GetArgumentsOfType() where T : class continue; } - var objectInstance = methodParameter.Value as T; - if (objectInstance != null) + if (methodParameter.Value is T objectInstance) { result.Add(objectInstance); continue; } - var objectInstanceArray = methodParameter.Value as IEnumerable; - if (objectInstanceArray != null) + if (methodParameter.Value is IEnumerable objectInstanceArray) { foreach (object element in objectInstanceArray) { - var objectInstance2 = element as T; - if (objectInstance2 != null) + if (element is T objectInstance2) { result.Add(objectInstance2); } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index 289ad0c3a76..ae8a9e36fb9 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -42,15 +42,14 @@ internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, _classVersion = classVersion; _privateData = privateData; - var compiledScript = this.Cmdlet as PSScriptCmdlet; - if (compiledScript != null) + if (this.Cmdlet is PSScriptCmdlet compiledScript) { - compiledScript.StoppingEvent += delegate { this.StopProcessing(); }; + compiledScript.StoppingEvent += delegate + { this.StopProcessing(); }; compiledScript.DisposingEvent += delegate { - var disposable = this as IDisposable; - if (disposable != null) + if (this is IDisposable disposable) { disposable.Dispose(); } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index 3757319c9ab..3399965f196 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -100,14 +100,12 @@ internal ScriptWriter( } catch (InvalidOperationException e) { - XmlSchemaException schemaException = e.InnerException as XmlSchemaException; - if (schemaException != null) + if (e.InnerException is XmlSchemaException schemaException) { throw new XmlException(schemaException.Message, schemaException, schemaException.LineNumber, schemaException.LinePosition); } - XmlException xmlException = e.InnerException as XmlException; - if (xmlException != null) + if (e.InnerException is XmlException xmlException) { throw xmlException; } @@ -788,8 +786,7 @@ private void SetParameters(CommandMetadata commandMetadata, params Dictionary GetProperties(object baseObject) { // baseObject should never be null - CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance == null) + if (baseObject is not CimInstance cimInstance) { string msg = string.Format(CultureInfo.InvariantCulture, CimInstanceTypeAdapterResources.BaseObjectNotCimInstance, @@ -109,8 +108,7 @@ public override PSAdaptedProperty GetProperty(object baseObject, string property } // baseObject should never be null - CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance == null) + if (baseObject is not CimInstance cimInstance) { string msg = string.Format(CultureInfo.InvariantCulture, CimInstanceTypeAdapterResources.BaseObjectNotCimInstance, @@ -144,8 +142,7 @@ public override PSAdaptedProperty GetFirstPropertyOrDefault(object baseObject, M } // baseObject should never be null - CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance == null) + if (baseObject is not CimInstance cimInstance) { string msg = string.Format( CultureInfo.InvariantCulture, @@ -202,8 +199,7 @@ public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty) throw new ArgumentNullException(nameof(adaptedProperty)); } - CimProperty cimProperty = adaptedProperty.Tag as CimProperty; - if (cimProperty != null) + if (adaptedProperty.Tag is CimProperty cimProperty) { return CimTypeToTypeNameDisplayString(cimProperty.CimType); } @@ -227,8 +223,7 @@ public override object GetPropertyValue(PSAdaptedProperty adaptedProperty) throw new ArgumentNullException(nameof(adaptedProperty)); } - CimProperty cimProperty = adaptedProperty.Tag as CimProperty; - if (cimProperty != null) + if (adaptedProperty.Tag is CimProperty cimProperty) { return cimProperty.Value; } diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs index 0619a0fe87d..7791f8a2883 100644 --- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs +++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs @@ -61,8 +61,7 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b if (_convertTypes[i].Equals(typeof(System.Management.Automation.PSReference))) { object temp; - PSObject mshObject = result as PSObject; - if (mshObject != null) + if (result is PSObject mshObject) temp = mshObject.BaseObject; else temp = result; @@ -76,16 +75,14 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b else { object temp; - PSObject mshObject = result as PSObject; - if (mshObject != null) + if (result is PSObject mshObject) temp = mshObject.BaseObject; else temp = result; // If a non-ref type is expected but currently passed in is a ref, do an implicit dereference. - PSReference reference = temp as PSReference; - if (reference != null) + if (temp is PSReference reference) { result = reference.Value; } diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index cbe4a2b0dd7..fb90dad89f5 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -979,8 +979,7 @@ protected override void ValidateElement(object element) Metadata.ValidateNotNullFailure); } - var o = element as PSObject; - if (o != null) + if (element is PSObject o) { element = o.BaseObject; } diff --git a/src/System.Management.Automation/engine/COM/ComMethod.cs b/src/System.Management.Automation/engine/COM/ComMethod.cs index 39882a2cdb8..0a36bc8799e 100644 --- a/src/System.Management.Automation/engine/COM/ComMethod.cs +++ b/src/System.Management.Automation/engine/COM/ComMethod.cs @@ -106,8 +106,7 @@ internal object InvokeMethod(PSMethod method, object[] arguments) catch (TargetInvocationException te) { // First check if this is a severe exception. - var innerCom = te.InnerException as COMException; - if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) + if (te.InnerException is not COMException innerCom || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { string message = te.InnerException == null ? te.Message : te.InnerException.Message; throw new MethodInvocationException( diff --git a/src/System.Management.Automation/engine/COM/ComProperty.cs b/src/System.Management.Automation/engine/COM/ComProperty.cs index 9ac1a28656b..a14790b11b0 100644 --- a/src/System.Management.Automation/engine/COM/ComProperty.cs +++ b/src/System.Management.Automation/engine/COM/ComProperty.cs @@ -152,8 +152,7 @@ internal object GetValue(object target) } catch (TargetInvocationException te) { - var innerCom = te.InnerException as COMException; - if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) + if (te.InnerException is not COMException innerCom || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { throw; } @@ -196,8 +195,7 @@ internal object GetValue(object target, object[] arguments) } catch (TargetInvocationException te) { - var innerCom = te.InnerException as COMException; - if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) + if (te.InnerException is not COMException innerCom || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { throw; } @@ -230,8 +228,7 @@ internal void SetValue(object target, object setValue) } catch (TargetInvocationException te) { - var innerCom = te.InnerException as COMException; - if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) + if (te.InnerException is not COMException innerCom || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { throw; } @@ -279,8 +276,7 @@ internal void SetValue(object target, object setValue, object[] arguments) } catch (TargetInvocationException te) { - var innerCom = te.InnerException as COMException; - if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) + if (te.InnerException is not COMException innerCom || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { throw; } diff --git a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs index d3b4f70e1a0..4117898c586 100644 --- a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs +++ b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs @@ -146,8 +146,7 @@ private void Initialize() internal static ComTypeInfo GetDispatchTypeInfo(object comObject) { ComTypeInfo result = null; - IDispatch disp = comObject as IDispatch; - if (disp != null) + if (comObject is IDispatch disp) { COM.ITypeInfo typeinfo = null; disp.GetTypeInfo(0, 0, out typeinfo); diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index 43e255b1549..b538288f8fb 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -366,13 +366,11 @@ public override ReadOnlyCollection OutputType for (int i = 0; i < Arguments.Length - 1; i++) { - var arg = Arguments[i] as string; - if (arg != null && + if (Arguments[i] is string arg && (arg.Equals("-Path", StringComparison.OrdinalIgnoreCase) || (arg.Equals("-LiteralPath", StringComparison.OrdinalIgnoreCase)))) { - var path = Arguments[i + 1] as string; - if (path != null) + if (Arguments[i + 1] is string path) { Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, true, out provider); } diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index 7d31a72997c..ca1c4d73e8d 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -201,8 +201,7 @@ internal void BindCommandLineParameters(Collection arg /// internal void BindCommandLineParametersNoValidation(Collection arguments) { - var psCompiledScriptCmdlet = this.Command as PSScriptCmdlet; - if (psCompiledScriptCmdlet != null) + if (this.Command is PSScriptCmdlet psCompiledScriptCmdlet) { psCompiledScriptCmdlet.PrepareForBinding(this.CommandLineParameters); } @@ -402,8 +401,7 @@ private bool BindDefaultParameters(uint validParameterSetFlag, Dictionary events; - var cpc = RuntimeCallableWrapper as ComTypes.IConnectionPointContainer; - if (cpc == null) + if (RuntimeCallableWrapper is not ComTypes.IConnectionPointContainer cpc) { // No ICPC - this object does not support events events = ComTypeDesc.EmptyEvents; diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs index b340cf54967..fe480853631 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs @@ -28,8 +28,7 @@ public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, Dy ComMethodDesc method = null; // See if this is actually a property set - ComBinder.ComInvokeMemberBinder comInvokeBinder = binder as ComBinder.ComInvokeMemberBinder; - if ((comInvokeBinder != null) && (comInvokeBinder.IsPropertySet)) + if ((binder is ComBinder.ComInvokeMemberBinder comInvokeBinder) && (comInvokeBinder.IsPropertySet)) { DynamicMetaObject value = args[args.Length - 1]; diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index b2019ec90dd..7881a30f7ba 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -124,8 +124,7 @@ internal bool IsStopping { get { - MshCommandRuntime mcr = this.commandRuntime as MshCommandRuntime; - return (mcr != null && mcr.IsStopping); + return (this.commandRuntime is MshCommandRuntime mcr && mcr.IsStopping); } } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 8b124194881..49d563e81ea 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -163,8 +163,7 @@ public static CommandCompletion CompleteInput(string input, int cursorIndex, Has return CompleteInputInDebugger(input, cursorIndex, options, debugger); } - var remoteRunspace = powershell.Runspace as RemoteRunspace; - if (remoteRunspace != null) + if (powershell.Runspace is RemoteRunspace remoteRunspace) { // If the runspace is not available to run commands then exit here because nested commands are not // supported on remote runspaces. @@ -242,8 +241,7 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo return CompleteInputInDebugger(ast, tokens, cursorPosition, options, debugger); } - var remoteRunspace = powershell.Runspace as RemoteRunspace; - if (remoteRunspace != null) + if (powershell.Runspace is RemoteRunspace remoteRunspace) { // If the runspace is not available to run commands then exit here because nested commands are not // supported on remote runspaces. @@ -411,8 +409,7 @@ private static CommandCompletion ProcessCompleteInputCommand( if (output.Count == 1) { - var commandCompletion = output[0].BaseObject as CommandCompletion; - if (commandCompletion != null) + if (output[0].BaseObject is CommandCompletion commandCompletion) { return commandCompletion; } @@ -458,8 +455,7 @@ private static CommandCompletion CallScriptWithStringParameterSet(string input, if (results.Count == 1) { var result = PSObject.Base(results[0]); - var commandCompletion = result as CommandCompletion; - if (commandCompletion != null) + if (result is CommandCompletion commandCompletion) { return commandCompletion; } @@ -495,8 +491,7 @@ private static CommandCompletion CallScriptWithAstParameterSet(Ast ast, Token[] if (results.Count == 1) { var result = PSObject.Base(results[0]); - var commandCompletion = result as CommandCompletion; - if (commandCompletion != null) + if (result is CommandCompletion commandCompletion) { return commandCompletion; } @@ -660,8 +655,7 @@ private static List InvokeLegacyTabExpansion(PowerShell powers results = new List(); foreach (var oldResult in oldResults) { - var completionResult = PSObject.Base(oldResult) as CompletionResult; - if (completionResult == null) + if (PSObject.Base(oldResult) is not CompletionResult completionResult) { var oldResultStr = oldResult.ToString(); @@ -1113,14 +1107,12 @@ private static List PSv2FindMatches(PowerShellExecutio foreach (PSObject t in paths) { - var pathsArray = t.BaseObject as IList; - if (pathsArray != null && pathsArray.Count == 3) + if (t.BaseObject is IList pathsArray && pathsArray.Count == 3) { object objectPath = pathsArray[0]; - PSObject item = pathsArray[1] as PSObject; object convertedPath = pathsArray[1]; - if (objectPath == null || item == null || convertedPath == null) + if (objectPath == null || pathsArray[1] is not PSObject item || convertedPath == null) { continue; } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 9f4b3565115..1b9bb5a7c0a 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -228,8 +228,7 @@ private static bool CompleteAgainstSwitchFile(Ast lastAst, Token tokenBeforeCurs { Tuple fileConditionTuple; - var errorStatement = lastAst as ErrorStatementAst; - if (errorStatement != null && errorStatement.Flags != null && errorStatement.Kind != null && tokenBeforeCursor != null && + if (lastAst is ErrorStatementAst errorStatement && errorStatement.Flags != null && errorStatement.Kind != null && tokenBeforeCursor != null && errorStatement.Kind.Kind.Equals(TokenKind.Switch) && errorStatement.Flags.TryGetValue("file", out fileConditionTuple)) { // Handle "switch -file " @@ -277,8 +276,7 @@ private static bool CompleteAgainstStatementFlags(Ast scriptAst, Ast lastAst, To kind = TokenKind.Unknown; // Handle "switch -f" - var errorStatement = lastAst as ErrorStatementAst; - if (errorStatement != null && errorStatement.Kind != null) + if (lastAst is ErrorStatementAst errorStatement && errorStatement.Kind != null) { switch (errorStatement.Kind.Kind) { @@ -291,8 +289,7 @@ private static bool CompleteAgainstStatementFlags(Ast scriptAst, Ast lastAst, To } // Handle "switch -". Skip cases like "switch ($a) {} - " - var scriptBlockAst = scriptAst as ScriptBlockAst; - if (token != null && token.Kind == TokenKind.Minus && scriptBlockAst != null) + if (token != null && token.Kind == TokenKind.Minus && scriptAst is ScriptBlockAst scriptBlockAst) { var asts = AstSearcher.FindAll(scriptBlockAst, ast => IsCursorAfterExtent(token.Extent.StartScriptPosition, ast.Extent), searchNestedScriptBlocks: true); @@ -302,7 +299,8 @@ private static bool CompleteAgainstStatementFlags(Ast scriptAst, Ast lastAst, To while (last != null) { errorStatement = last as ErrorStatementAst; - if (errorStatement != null) { break; } + if (errorStatement != null) + { break; } last = last.Parent; } @@ -412,8 +410,7 @@ internal List GetResultHelper(CompletionContext completionCont break; completionContext.WordToComplete = tokenAtCursor.Text; - var cmdAst = lastAst.Parent as CommandAst; - if (lastAst is StringConstantExpressionAst && cmdAst != null && cmdAst.CommandElements.Count == 1) + if (lastAst is StringConstantExpressionAst && lastAst.Parent is CommandAst cmdAst && cmdAst.CommandElements.Count == 1) { result = CompleteFileNameAsCommand(completionContext); break; @@ -930,8 +927,7 @@ private List GetResultForHashtable(CompletionContext completio var lastAst = completionContext.RelatedAsts.Last(); HashtableAst tempHashtableAst = null; IScriptPosition cursor = completionContext.CursorPosition; - var hashTableAst = lastAst as HashtableAst; - if (hashTableAst != null) + if (lastAst is HashtableAst hashTableAst) { // Check if the cursor within the hashtable if (cursor.Offset < hashTableAst.Extent.EndOffset) @@ -1002,8 +998,7 @@ private bool CheckForPendingAssignment(HashtableAst hashTableAst) internal static TypeName FindTypeNameToComplete(ITypeName type, IScriptPosition cursor) { - var typeName = type as TypeName; - if (typeName != null) + if (type is TypeName typeName) { // If the cursor is at the start offset, it's not really inside, so return null. // If the cursor is at the end offset, it's not really inside, but it's just before the cursor, @@ -1013,8 +1008,7 @@ internal static TypeName FindTypeNameToComplete(ITypeName type, IScriptPosition : null; } - var genericTypeName = type as GenericTypeName; - if (genericTypeName != null) + if (type is GenericTypeName genericTypeName) { typeName = FindTypeNameToComplete(genericTypeName.TypeName, cursor); if (typeName != null) @@ -1029,8 +1023,7 @@ internal static TypeName FindTypeNameToComplete(ITypeName type, IScriptPosition return null; } - var arrayTypeName = type as ArrayTypeName; - if (arrayTypeName != null) + if (type is ArrayTypeName arrayTypeName) { return FindTypeNameToComplete(arrayTypeName.ElementType, cursor) ?? null; } @@ -1369,8 +1362,7 @@ private List GetResultForEnumPropertyValueOfDSCResource( var keyValuePairWithCursor = GetHashEntryContainsCursor(cursor, hashTableAst, isCursorInString); if (keyValuePairWithCursor != null) { - var propertyNameAst = keyValuePairWithCursor.Item1 as StringConstantExpressionAst; - if (propertyNameAst != null) + if (keyValuePairWithCursor.Item1 is StringConstantExpressionAst propertyNameAst) { DynamicKeywordProperty property; if (keywordAst.Keyword.Properties.TryGetValue(propertyNameAst.Value, out property)) @@ -1395,8 +1387,7 @@ private List GetResultForEnumPropertyValueOfDSCResource( // stringAst can be null in following case // DependsOn='[user]x',| // - var stringAst = expression as StringConstantExpressionAst; - if (stringAst != null && IsCursorOutsideOfExtent(cursor, expression.Extent)) + if (expression is StringConstantExpressionAst stringAst && IsCursorOutsideOfExtent(cursor, expression.Extent)) { existingValues.Add(stringAst.Value); } @@ -1461,8 +1452,7 @@ private List GetResultForEnumPropertyValueOfDSCResource( List allResources = new List(); foreach (var statementAst in namedBlockAst.Statements) { - var dynamicKeywordAst = statementAst as DynamicKeywordStatementAst; - if (dynamicKeywordAst != null && + if (statementAst is DynamicKeywordStatementAst dynamicKeywordAst && dynamicKeywordAst != keywordAst && !string.Equals(dynamicKeywordAst.Keyword.Keyword, @"Node", StringComparison.OrdinalIgnoreCase)) { @@ -1746,8 +1736,7 @@ private List GetResultForIdentifier(CompletionContext completi } else { - UsingStatementAst usingState = strConst.Parent as UsingStatementAst; - if (usingState != null) + if (strConst.Parent is UsingStatementAst usingState) { completionContext.ReplacementIndex = strConst.Extent.StartOffset; completionContext.ReplacementLength = strConst.Extent.EndOffset - replacementIndex; @@ -1831,8 +1820,7 @@ private List GetResultForIdentifier(CompletionContext completi } else { - var variableAst = cursorAst as VariableExpressionAst; - string fullPath = variableAst != null + string fullPath = cursorAst is VariableExpressionAst variableAst ? CompletionCompleters.CombineVariableWithPartialPath( variableAst: variableAst, extraText: tokenAtCursorText, @@ -1862,8 +1850,7 @@ private List GetResultForIdentifier(CompletionContext completi if (isQuotedString) { return result; } // Handle the StringExpandableToken; - var strToken = tokenAtCursor as StringExpandableToken; - if (strToken != null && strToken.NestedTokens != null && strConst != null) + if (tokenAtCursor is StringExpandableToken strToken && strToken.NestedTokens != null && strConst != null) { try { @@ -1967,10 +1954,9 @@ private List GetResultForIdentifier(CompletionContext completi { // Handle member completion with wildcard(wildcard is at the end): $a.p* var binaryExpressionAst = (BinaryExpressionAst)lastAst; - var memberExpressionAst = binaryExpressionAst.Left as MemberExpressionAst; var errorPosition = binaryExpressionAst.ErrorPosition; - if (memberExpressionAst != null && binaryExpressionAst.Operator == TokenKind.Multiply && + if (binaryExpressionAst.Left is MemberExpressionAst memberExpressionAst && binaryExpressionAst.Operator == TokenKind.Multiply && errorPosition.StartOffset == memberExpressionAst.Member.Extent.EndOffset) { isStatic = memberExpressionAst.Static; @@ -1983,8 +1969,7 @@ private List GetResultForIdentifier(CompletionContext completi completionContext.RelatedAsts.Remove(binaryExpressionAst); completionContext.RelatedAsts.Add(memberExpressionAst); - var memberAst = memberExpressionAst.Member as StringConstantExpressionAst; - if (memberAst != null) + if (memberExpressionAst.Member is StringConstantExpressionAst memberAst) { replacementIndex = memberAst.Extent.StartScriptPosition.Offset; replacementLength += memberAst.Extent.Text.Length; @@ -2037,11 +2022,9 @@ private List GetResultForIdentifier(CompletionContext completi } else if (tokenAtCursorText.IndexOfAny(Utils.Separators.Directory) == 0) { - var command = lastAst.Parent as CommandBaseAst; - if (command != null && command.Redirections.Count > 0) + if (lastAst.Parent is CommandBaseAst command && command.Redirections.Count > 0) { - var fileRedirection = command.Redirections[0] as FileRedirectionAst; - if (fileRedirection != null && + if (command.Redirections[0] is FileRedirectionAst fileRedirection && fileRedirection.Extent.EndLineNumber == lastAst.Extent.StartLineNumber && fileRedirection.Extent.EndColumnNumber == lastAst.Extent.StartColumnNumber) { @@ -2088,8 +2071,7 @@ private List GetResultForAttributeArgument(CompletionContext c Type attributeType = null; string argName = string.Empty; Ast argAst = completionContext.RelatedAsts.Find(ast => ast is NamedAttributeArgumentAst); - NamedAttributeArgumentAst namedArgAst = argAst as NamedAttributeArgumentAst; - if (argAst != null && namedArgAst != null) + if (argAst != null && argAst is NamedAttributeArgumentAst namedArgAst) { attributeType = ((AttributeAst)namedArgAst.Parent).TypeName.GetReflectionAttributeType(); argName = namedArgAst.ArgumentName; @@ -2099,8 +2081,7 @@ private List GetResultForAttributeArgument(CompletionContext c else { Ast astAtt = completionContext.RelatedAsts.Find(ast => ast is AttributeAst); - AttributeAst attAst = astAtt as AttributeAst; - if (astAtt != null && attAst != null) + if (astAtt != null && astAtt is AttributeAst attAst) { attributeType = attAst.TypeName.GetReflectionAttributeType(); } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index e7c8ea0be9a..f303116337c 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -213,8 +213,7 @@ internal static CompletionResult GetCommandNameCompletionResult(string name, obj { string syntax = name, listItem = name; - var commandInfo = command as CommandInfo; - if (commandInfo != null) + if (command is CommandInfo commandInfo) { try { @@ -279,11 +278,11 @@ internal static List MakeCommandsUnique(IEnumerable object baseObj = PSObject.Base(psobj); string name = null; - var commandInfo = baseObj as CommandInfo; - if (commandInfo != null) + if (baseObj is CommandInfo commandInfo) { // Skip the private commands - if (commandInfo.Visibility == SessionStateEntryVisibility.Private) { continue; } + if (commandInfo.Visibility == SessionStateEntryVisibility.Private) + { continue; } name = commandInfo.Name; if (includeModulePrefix && !string.IsNullOrEmpty(commandInfo.ModuleName)) @@ -303,7 +302,8 @@ internal static List MakeCommandsUnique(IEnumerable else { name = baseObj as string; - if (name == null) { continue; } + if (name == null) + { continue; } } object value; @@ -313,8 +313,7 @@ internal static List MakeCommandsUnique(IEnumerable } else { - var list = value as List; - if (list != null) + if (value is List list) { list.Add(baseObj); } @@ -329,8 +328,7 @@ internal static List MakeCommandsUnique(IEnumerable List endResults = null; foreach (var keyValuePair in commandTable) { - var commandList = keyValuePair.Value as List; - if (commandList != null) + if (keyValuePair.Value is List commandList) { if (endResults == null) { @@ -343,8 +341,7 @@ internal static List MakeCommandsUnique(IEnumerable string completionName = keyValuePair.Key; if (!includeModulePrefix) { - var commandInfo = commandList[0] as CommandInfo; - if (commandInfo != null && !string.IsNullOrEmpty(commandInfo.Prefix)) + if (commandList[0] is CommandInfo commandInfo && !string.IsNullOrEmpty(commandInfo.Prefix)) { Diagnostics.Assert(!string.IsNullOrEmpty(commandInfo.ModuleName), "the module name should exist if commandInfo.Prefix is not an empty string"); if (!ModuleCmdletBase.IsPrefixedCommand(commandInfo)) @@ -384,8 +381,7 @@ internal static List MakeCommandsUnique(IEnumerable string completionName = keyValuePair.Key; if (!includeModulePrefix) { - var commandInfo = keyValuePair.Value as CommandInfo; - if (commandInfo != null && !string.IsNullOrEmpty(commandInfo.Prefix)) + if (keyValuePair.Value is CommandInfo commandInfo && !string.IsNullOrEmpty(commandInfo.Prefix)) { Diagnostics.Assert(!string.IsNullOrEmpty(commandInfo.ModuleName), "the module name should exist if commandInfo.Prefix is not an empty string"); if (!ModuleCmdletBase.IsPrefixedCommand(commandInfo)) @@ -761,8 +757,7 @@ private static List GetParameterCompletionResults( { foreach (var attr in compiledAttributes) { - var pattr = attr as ParameterAttribute; - if (pattr != null && pattr.DontShow) + if (attr is ParameterAttribute pattr && pattr.DontShow) { showToUser = false; addCommonParameters = false; @@ -873,8 +868,7 @@ internal static List CompleteCommandArgument(CompletionContext secondToLastMemberAst = secondToLastAst as MemberExpressionAst; } - var partialPathAst = expressionAst as StringConstantExpressionAst; - if (partialPathAst != null && secondToLastAst != null && + if (expressionAst is StringConstantExpressionAst partialPathAst && secondToLastAst != null && partialPathAst.StringConstantType == StringConstantType.BareWord && secondToLastAst.Extent.EndLineNumber == partialPathAst.Extent.StartLineNumber && secondToLastAst.Extent.EndColumnNumber == partialPathAst.Extent.StartColumnNumber && @@ -882,8 +876,6 @@ internal static List CompleteCommandArgument(CompletionContext { var secondToLastStringConstantAst = secondToLastAst as StringConstantExpressionAst; var secondToLastExpandableStringAst = secondToLastAst as ExpandableStringExpressionAst; - var secondToLastArrayAst = secondToLastAst as ArrayLiteralAst; - var secondToLastParamAst = secondToLastAst as CommandParameterAst; if (secondToLastStringConstantAst != null || secondToLastExpandableStringAst != null) { @@ -897,7 +889,7 @@ internal static List CompleteCommandArgument(CompletionContext context.WordToComplete = fullPath; // context.CursorPosition = secondToLastAst.Extent.StartScriptPosition; } - else if (secondToLastArrayAst != null) + else if (secondToLastAst is ArrayLiteralAst secondToLastArrayAst) { // Handle cases like: dir -Path .\cd, 'a b'\new var lastArrayElement = secondToLastArrayAst.Elements.LastOrDefault(); @@ -911,7 +903,7 @@ internal static List CompleteCommandArgument(CompletionContext context.WordToComplete = fullPath; } } - else if (secondToLastParamAst != null) + else if (secondToLastAst is CommandParameterAst secondToLastParamAst) { // Handle cases like: dir -Path: .\cd, 'a b'\new || dir -Path: 'a b'\new var fullPath = ConcatenateStringPathArguments(secondToLastParamAst.Argument, partialPathAst.Value, context); @@ -925,8 +917,7 @@ internal static List CompleteCommandArgument(CompletionContext } else { - var arrayArgAst = secondToLastParamAst.Argument as ArrayLiteralAst; - if (arrayArgAst != null) + if (secondToLastParamAst.Argument is ArrayLiteralAst arrayArgAst) { var lastArrayElement = arrayArgAst.Elements.LastOrDefault(); fullPath = ConcatenateStringPathArguments(lastArrayElement, partialPathAst.Value, context); @@ -993,8 +984,7 @@ internal static List CompleteCommandArgument(CompletionContext } else { - var paramAst = lastAst as CommandParameterAst; - if (paramAst != null) + if (lastAst is CommandParameterAst paramAst) { commandAst = paramAst.Parent as CommandAst; } @@ -1029,8 +1019,7 @@ internal static List CompleteCommandArgument(CompletionContext if (expressionAst != null) { treatAsExpression = true; - var dashExp = expressionAst as StringConstantExpressionAst; - if (dashExp != null && dashExp.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) + if (expressionAst is StringConstantExpressionAst dashExp && dashExp.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) { // "-" is represented as StringConstantExpressionAst. Most likely the user is typing a // after it, so in the pseudo binder, we ignore it to avoid treating it as an argument. @@ -1341,8 +1330,7 @@ internal static List CompleteCommandArgument(CompletionContext internal static string ConcatenateStringPathArguments(CommandElementAst stringAst, string partialPath, CompletionContext completionContext) { - var constantPathAst = stringAst as StringConstantExpressionAst; - if (constantPathAst != null) + if (stringAst is StringConstantExpressionAst constantPathAst) { string quote = string.Empty; switch (constantPathAst.StringConstantType) @@ -1361,9 +1349,8 @@ internal static string ConcatenateStringPathArguments(CommandElementAst stringAs } else { - var expandablePathAst = stringAst as ExpandableStringExpressionAst; string fullPath = null; - if (expandablePathAst != null && + if (stringAst is ExpandableStringExpressionAst expandablePathAst && IsPathSafelyExpandable(expandableStringAst: expandablePathAst, extraText: partialPath, executionContext: completionContext.ExecutionContext, @@ -1836,8 +1823,7 @@ private static IEnumerable NativeCommandArgumentCompletion_InferType case AstParameterArgumentType.PipeObject: { - var pipelineAst = commandAst.Parent as PipelineAst; - if (pipelineAst != null) + if (commandAst.Parent is PipelineAst pipelineAst) { int i; for (i = 0; i < pipelineAst.PipelineElements.Count; i++) @@ -1867,8 +1853,7 @@ private static IEnumerable NativeCommandArgumentCompletion_InferType ExpressionAst argumentExpressionAst = argumentAst as ExpressionAst; if (argumentExpressionAst == null) { - CommandExpressionAst argumentCommandExpressionAst = argumentAst as CommandExpressionAst; - if (argumentCommandExpressionAst != null) + if (argumentAst is CommandExpressionAst argumentCommandExpressionAst) { argumentExpressionAst = argumentCommandExpressionAst.Expression; } @@ -1942,8 +1927,7 @@ internal static IList NativeCommandArgumentCompletion_ExtractSecondaryAr var argument = (ArrayLiteralAst)value.Argument; foreach (ExpressionAst entry in argument.Elements) { - var entryAsString = entry as StringConstantExpressionAst; - if (entryAsString != null) + if (entry is StringConstantExpressionAst entryAsString) { result.Add(entryAsString.Value); } @@ -1964,8 +1948,7 @@ internal static IList NativeCommandArgumentCompletion_ExtractSecondaryAr foreach (ExpressionAst entry in argument) { - var entryAsString = entry as StringConstantExpressionAst; - if (entryAsString != null) + if (entry is StringConstantExpressionAst entryAsString) { result.Add(entryAsString.Value); } @@ -2032,8 +2015,7 @@ private static void NativeCommandArgumentCompletion( { if (argumentCompleterAttribute.Type != null) { - var completer = Activator.CreateInstance(argumentCompleterAttribute.Type) as IArgumentCompleter; - if (completer != null) + if (Activator.CreateInstance(argumentCompleterAttribute.Type) is IArgumentCompleter completer) { var customResults = completer.CompleteArgument(commandName, parameterName, context.WordToComplete, commandAst, GetBoundArgumentsAsHashtable(context)); @@ -2347,11 +2329,9 @@ private static Hashtable GetBoundArgumentsAsHashtable(CompletionContext context) { foreach (var boundArgument in boundArguments) { - var astPair = boundArgument.Value as AstPair; - if (astPair != null) + if (boundArgument.Value is AstPair astPair) { - var parameterAst = astPair.Argument as CommandParameterAst; - var exprAst = parameterAst != null + var exprAst = astPair.Argument is CommandParameterAst parameterAst ? parameterAst.Argument : astPair.Argument as ExpressionAst; object value; @@ -2363,8 +2343,7 @@ private static Hashtable GetBoundArgumentsAsHashtable(CompletionContext context) continue; } - var switchPair = boundArgument.Value as SwitchPair; - if (switchPair != null) + if (boundArgument.Value is SwitchPair switchPair) { result[boundArgument.Key] = switchPair.Argument; continue; @@ -2389,8 +2368,7 @@ private static ScriptBlock GetCustomArgumentCompleter( var options = context.Options; if (options != null) { - var customCompleters = options[optionKey] as Hashtable; - if (customCompleters != null) + if (options[optionKey] is Hashtable customCompleters) { foreach (var key in keys) { @@ -2464,8 +2442,7 @@ private static bool InvokeScriptArgumentCompleter( foreach (var customResult in customResults) { - var resultAsCompletion = customResult.BaseObject as CompletionResult; - if (resultAsCompletion != null) + if (customResult.BaseObject is CompletionResult resultAsCompletion) { result.Add(resultAsCompletion); continue; @@ -3811,8 +3788,7 @@ private static void NativeCompletionMemberName(CompletionContext context, List CompleteFilename(CompletionContext if (psobjs.Count > 0) { dynamic firstObj = psobjs[0]; - var provider = firstObj.Provider as ProviderInfo; - isFileSystem = provider != null && + isFileSystem = firstObj.Provider is ProviderInfo provider && provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase); } @@ -4333,8 +4308,7 @@ internal static IEnumerable CompleteFilename(CompletionContext // 1. a PathInfo object -- results of Resolve-Path // 2. a FileSystemInfo Object -- results of Get-ChildItem // 3. a string -- the path results return by the direct .NET API invocation - var baseObjAsPathInfo = baseObj as PathInfo; - if (baseObjAsPathInfo != null) + if (baseObj is PathInfo baseObjAsPathInfo) { path = baseObjAsPathInfo.Path; providerPath = baseObjAsPathInfo.ProviderPath; @@ -4348,8 +4322,7 @@ internal static IEnumerable CompleteFilename(CompletionContext } else { - var baseObjAsString = baseObj as string; - if (baseObjAsString != null) + if (baseObj is string baseObjAsString) { // The target provider is the FileSystem providerPath = baseObjAsString; @@ -4593,8 +4566,7 @@ internal static List CompleteVariable(CompletionContext contex var colon = wordToComplete.IndexOf(':'); var lastAst = context.RelatedAsts?.Last(); - var variableAst = lastAst as VariableExpressionAst; - var prefix = variableAst != null && variableAst.Splatted ? "@" : "$"; + var prefix = lastAst is VariableExpressionAst variableAst && variableAst.Splatted ? "@" : "$"; // Look for variables in the input (e.g. parameters, etc.) before checking session state - these // variables might not exist in session state yet. @@ -4619,16 +4591,14 @@ internal static List CompleteVariable(CompletionContext contex Ast astTarget = null; string userPath = null; - VariableExpressionAst variableDefinitionAst = varAst.Item2 as VariableExpressionAst; - if (variableDefinitionAst != null) + if (varAst.Item2 is VariableExpressionAst variableDefinitionAst) { userPath = varAst.Item1; astTarget = varAst.Item2.Parent; } else { - CommandAst commandParameterAst = varAst.Item2 as CommandAst; - if (commandParameterAst != null) + if (varAst.Item2 is CommandAst commandParameterAst) { userPath = varAst.Item1; astTarget = varAst.Item2; @@ -4650,8 +4620,7 @@ internal static List CompleteVariable(CompletionContext contex while (ast != null) { - var parameterAst = ast as ParameterAst; - if (parameterAst != null) + if (ast is ParameterAst parameterAst) { var typeConstraint = parameterAst.Attributes.OfType().FirstOrDefault(); if (typeConstraint != null) @@ -4662,8 +4631,7 @@ internal static List CompleteVariable(CompletionContext contex break; } - var assignmentAst = ast.Parent as AssignmentStatementAst; - if (assignmentAst != null) + if (ast.Parent is AssignmentStatementAst assignmentAst) { if (assignmentAst.Left == ast) { @@ -4673,8 +4641,7 @@ internal static List CompleteVariable(CompletionContext contex break; } - var commandAst = ast as CommandAst; - if (commandAst != null) + if (ast is CommandAst commandAst) { PSTypeName discoveredType = AstTypeInference.InferTypeOf(ast, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval).FirstOrDefault(); if (discoveredType != null) @@ -4728,8 +4695,7 @@ internal static List CompleteVariable(CompletionContext contex if (!string.IsNullOrEmpty(name)) { var tooltip = name; - var variable = PSObject.Base(psobj) as PSVariable; - if (variable != null) + if (PSObject.Base(psobj) is PSVariable variable) { var value = variable.Value; if (value != null) @@ -4940,8 +4906,7 @@ internal static List CompleteComment(CompletionContext context if (psobjs != null && psobjs.Count == 1) { - var historyInfo = PSObject.Base(psobjs[0]) as HistoryInfo; - if (historyInfo != null) + if (PSObject.Base(psobjs[0]) is HistoryInfo historyInfo) { var commandLine = historyInfo.CommandLine; if (!string.IsNullOrEmpty(commandLine)) @@ -5016,10 +4981,9 @@ internal static List CompleteMember(CompletionContext context, var results = new List(); var lastAst = context.RelatedAsts.Last(); - var lastAstAsMemberExpr = lastAst as MemberExpressionAst; Ast memberNameCandidateAst = null; ExpressionAst targetExpr = null; - if (lastAstAsMemberExpr != null) + if (lastAst is MemberExpressionAst lastAstAsMemberExpr) { // If the cursor is not inside the member name in the member expression, assume // that the user had incomplete input, but the parser got lucky and succeeded parsing anyway. @@ -5035,10 +4999,9 @@ internal static List CompleteMember(CompletionContext context, memberNameCandidateAst = lastAst; } - var memberNameAst = memberNameCandidateAst as StringConstantExpressionAst; var memberName = "*"; - if (memberNameAst != null) + if (memberNameCandidateAst is StringConstantExpressionAst memberNameAst) { // Make sure to correctly handle: echo $foo. if (!memberNameAst.Value.Equals(".", StringComparison.OrdinalIgnoreCase) && !memberNameAst.Value.Equals("::", StringComparison.OrdinalIgnoreCase)) @@ -5052,8 +5015,7 @@ internal static List CompleteMember(CompletionContext context, return results; } - var commandAst = lastAst.Parent as CommandAst; - if (commandAst != null) + if (lastAst.Parent is CommandAst commandAst) { int i; for (i = commandAst.CommandElements.Count - 1; i >= 0; --i) @@ -5092,8 +5054,7 @@ internal static List CompleteMember(CompletionContext context, } else if (lastAst.Parent is BinaryExpressionAst && context.TokenAtCursor.Kind.Equals(TokenKind.Multiply)) { - var memberExprAst = ((BinaryExpressionAst)lastAst.Parent).Left as MemberExpressionAst; - if (memberExprAst != null) + if (((BinaryExpressionAst)lastAst.Parent).Left is MemberExpressionAst memberExprAst) { targetExpr = memberExprAst.Expression; if (memberExprAst.Member is StringConstantExpressionAst) @@ -5123,8 +5084,7 @@ internal static List CompleteMember(CompletionContext context, if (@static) { - var typeExpr = targetExpr as TypeExpressionAst; - if (typeExpr != null) + if (targetExpr is TypeExpressionAst typeExpr) { inferredTypes = new[] { new PSTypeName(typeExpr.TypeName) }; } @@ -5143,13 +5103,12 @@ internal static List CompleteMember(CompletionContext context, { // Handle special DSC collection variables to complete the extension methods 'Where' and 'ForEach' // e.g. Configuration foo { node $AllNodes. --> $AllNodes.Where( - var variableAst = targetExpr as VariableExpressionAst; - var memberExprAst = targetExpr as MemberExpressionAst; + bool shouldAddExtensionMethods = false; // We complete against extension methods 'Where' and 'ForEach' for the following DSC variables // $SelectedNodes, $AllNodes, $ConfigurationData.AllNodes - if (variableAst != null) + if (targetExpr is VariableExpressionAst variableAst) { // Handle $SelectedNodes and $AllNodes var variablePath = variableAst.VariablePath; @@ -5158,11 +5117,10 @@ internal static List CompleteMember(CompletionContext context, shouldAddExtensionMethods = true; } } - else if (memberExprAst != null) + else if (targetExpr is MemberExpressionAst memberExprAst) { // Handle $ConfigurationData.AllNodes - var member = memberExprAst.Member as StringConstantExpressionAst; - if (IsConfigurationDataVariable(memberExprAst.Expression) && member != null && + if (IsConfigurationDataVariable(memberExprAst.Expression) && memberExprAst.Member is StringConstantExpressionAst member && string.Equals("AllNodes", member.Value, StringComparison.OrdinalIgnoreCase) && IsInDscContext(memberExprAst)) { @@ -5219,8 +5177,7 @@ where pattern.IsMatch(member.Item1) /// private static bool IsConfigurationDataVariable(ExpressionAst targetExpr) { - var variableExpr = targetExpr as VariableExpressionAst; - if (variableExpr != null) + if (targetExpr is VariableExpressionAst variableExpr) { var varPath = variableExpr.VariablePath; if (varPath.IsVariable && @@ -5305,32 +5262,28 @@ private static void AddInferredMember(object member, WildcardPattern memberNameP getToolTip = () => ToStringCodeMethods.Type(fieldInfo.FieldType) + " " + memberName; } - var methodCacheEntry = member as DotNetAdapter.MethodCacheEntry; - if (methodCacheEntry != null) + if (member is DotNetAdapter.MethodCacheEntry methodCacheEntry) { memberName = methodCacheEntry[0].method.Name; isMethod = true; getToolTip = () => string.Join("\n", methodCacheEntry.methodInformationStructures.Select(m => m.methodDefinition)); } - var psMemberInfo = member as PSMemberInfo; - if (psMemberInfo != null) + if (member is PSMemberInfo psMemberInfo) { memberName = psMemberInfo.Name; isMethod = member is PSMethodInfo; getToolTip = psMemberInfo.ToString; } - var cimProperty = member as CimPropertyDeclaration; - if (cimProperty != null) + if (member is CimPropertyDeclaration cimProperty) { memberName = cimProperty.Name; isMethod = false; getToolTip = () => GetCimPropertyToString(cimProperty); } - var memberAst = member as MemberAst; - if (memberAst != null) + if (member is MemberAst memberAst) { memberName = memberAst is CompilerGeneratedMemberFunctionAst ? "new" : memberAst.Name; isMethod = memberAst is FunctionMemberAst || memberAst is CompilerGeneratedMemberFunctionAst; @@ -5379,8 +5332,7 @@ private static bool IsWriteablePropertyMember(object member) return propertyInfo.CanWrite; } - var psPropertyInfo = member as PSPropertyInfo; - if (psPropertyInfo != null) + if (member is PSPropertyInfo psPropertyInfo) { return psPropertyInfo.IsSettable; } @@ -5399,20 +5351,17 @@ internal static bool IsPropertyMember(object member) private static bool IsMemberHidden(object member) { - var psMemberInfo = member as PSMemberInfo; - if (psMemberInfo != null) + if (member is PSMemberInfo psMemberInfo) return psMemberInfo.IsHidden; var memberInfo = member as MemberInfo; if (memberInfo != null) return memberInfo.GetCustomAttributes(typeof(HiddenAttribute), false).Length > 0; - var propertyMemberAst = member as PropertyMemberAst; - if (propertyMemberAst != null) + if (member is PropertyMemberAst propertyMemberAst) return propertyMemberAst.IsHidden; - var functionMemberAst = member as FunctionMemberAst; - if (functionMemberAst != null) + if (member is FunctionMemberAst functionMemberAst) return functionMemberAst.IsHidden; return false; @@ -5420,11 +5369,9 @@ private static bool IsMemberHidden(object member) private static bool IsConstructor(object member) { - var psMethod = member as PSMethod; - if (psMethod != null) + if (member is PSMethod psMethod) { - var methodCacheEntry = psMethod.adapterData as DotNetAdapter.MethodCacheEntry; - if (methodCacheEntry != null) + if (psMethod.adapterData is DotNetAdapter.MethodCacheEntry methodCacheEntry) { return methodCacheEntry.methodInformationStructures[0].method.IsConstructor; } @@ -5737,8 +5684,7 @@ private static TypeCompletionMapping[][] InitializeTypeCache() bool typeAlreadyIncluded = entry.Completions.Any( item => { - var typeCompletion = item as TypeCompletion; - return typeCompletion != null && typeCompletion.Type == acceleratorType; + return item is TypeCompletion typeCompletion && typeCompletion.Type == acceleratorType; }); // If it's already included, skip it. @@ -6038,8 +5984,7 @@ private static string GetNamespaceToRemove(CompletionContext context, TypeComple return null; } - var typeCompletion = completion as TypeCompletion; - string typeNameSpace = typeCompletion != null + string typeNameSpace = completion is TypeCompletion typeCompletion ? typeCompletion.Type.Namespace : ((TypeCompletionInStringFormat)completion).Namespace; @@ -6232,9 +6177,8 @@ internal static List CompleteHashtableKeyForDynamicKeyword( int cursorOffset = completionContext.CursorPosition.Offset; foreach (var keyValueTuple in hashtableAst.KeyValuePairs) { - var propName = keyValueTuple.Item1 as StringConstantExpressionAst; // Exclude the property name at cursor - if (propName != null && propName.Extent.EndOffset != cursorOffset) + if (keyValueTuple.Item1 is StringConstantExpressionAst propName && propName.Extent.EndOffset != cursorOffset) { propertiesName.Add(propName.Value); } @@ -6283,8 +6227,7 @@ internal static List CompleteHashtableKeyForDynamicKeyword( internal static List CompleteHashtableKey(CompletionContext completionContext, HashtableAst hashtableAst) { - var typeAst = hashtableAst.Parent as ConvertExpressionAst; - if (typeAst != null) + if (hashtableAst.Parent is ConvertExpressionAst typeAst) { var result = new List(); CompleteMemberByInferredType( @@ -6326,8 +6269,7 @@ internal static List CompleteHashtableKey(CompletionContext co var ast = hashtableAst.Parent; // Handle completion for hashtable within DynamicKeyword statement - var dynamicKeywordStatementAst = ast as DynamicKeywordStatementAst; - if (dynamicKeywordStatementAst != null) + if (ast is DynamicKeywordStatementAst dynamicKeywordStatementAst) { return CompleteHashtableKeyForDynamicKeyword(completionContext, dynamicKeywordStatementAst, hashtableAst); } @@ -6342,8 +6284,7 @@ internal static List CompleteHashtableKey(CompletionContext co ast = ast.Parent; } - var commandAst = ast as CommandAst; - if (commandAst != null) + if (ast is CommandAst commandAst) { var binding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, null, bindingType: PseudoParameterBinder.BindingType.ArgumentCompletion); if (binding == null) @@ -6354,8 +6295,7 @@ internal static List CompleteHashtableKey(CompletionContext co string parameterName = null; foreach (var boundArg in binding.BoundArguments) { - var astPair = boundArg.Value as AstPair; - if (astPair != null) + if (boundArg.Value is AstPair astPair) { if (astPair.Argument == hashtableAst) { @@ -6366,8 +6306,7 @@ internal static List CompleteHashtableKey(CompletionContext co continue; } - var astArrayPair = boundArg.Value as AstArrayPair; - if (astArrayPair != null) + if (boundArg.Value is AstArrayPair astArrayPair) { if (astArrayPair.Argument.Contains(hashtableAst)) { @@ -6641,8 +6580,7 @@ internal static void CompleteMemberHelper( tooltip)); } - var dictionary = PSObject.Base(value) as IDictionary; - if (dictionary != null) + if (PSObject.Base(value) is IDictionary dictionary) { var pattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase); foreach (DictionaryEntry entry in dictionary) @@ -6786,9 +6724,8 @@ internal static bool IsAmpersandNeeded(CompletionContext context, bool defaultCh if (context.RelatedAsts != null && !string.IsNullOrEmpty(context.WordToComplete)) { var lastAst = context.RelatedAsts.Last(); - var parent = lastAst.Parent as CommandAst; - if (parent != null && parent.CommandElements.Count == 1 && + if (lastAst.Parent is CommandAst parent && parent.CommandElements.Count == 1 && ((!defaultChoice && parent.InvocationOperator == TokenKind.Unknown) || (defaultChoice && parent.InvocationOperator != TokenKind.Unknown))) { @@ -6807,28 +6744,20 @@ private class ItemPathComparer : IComparer { public int Compare(PSObject x, PSObject y) { - var xPathInfo = PSObject.Base(x) as PathInfo; - var xFileInfo = PSObject.Base(x) as IO.FileSystemInfo; - var xPathStr = PSObject.Base(x) as string; - - var yPathInfo = PSObject.Base(y) as PathInfo; - var yFileInfo = PSObject.Base(y) as IO.FileSystemInfo; - var yPathStr = PSObject.Base(y) as string; - string xPath = null, yPath = null; - if (xPathInfo != null) + if (PSObject.Base(x) is PathInfo xPathInfo) xPath = xPathInfo.ProviderPath; - else if (xFileInfo != null) + else if (PSObject.Base(x) is IO.FileSystemInfo xFileInfo) xPath = xFileInfo.FullName; - else if (xPathStr != null) + else if (PSObject.Base(x) is string xPathStr) xPath = xPathStr; - if (yPathInfo != null) + if (PSObject.Base(y) is PathInfo yPathInfo) yPath = yPathInfo.ProviderPath; - else if (yFileInfo != null) + else if (PSObject.Base(y) is IO.FileSystemInfo yFileInfo) yPath = yFileInfo.FullName; - else if (yPathStr != null) + else if (PSObject.Base(y) is string yPathStr) yPath = yPathStr; if (string.IsNullOrEmpty(xPath) || string.IsNullOrEmpty(yPath)) @@ -6848,11 +6777,9 @@ public int Compare(PSObject x, PSObject y) object xObj = PSObject.Base(x); object yObj = PSObject.Base(y); - var xCommandInfo = xObj as CommandInfo; - xName = xCommandInfo != null ? xCommandInfo.Name : xObj as string; + xName = xObj is CommandInfo xCommandInfo ? xCommandInfo.Name : xObj as string; - var yCommandInfo = yObj as CommandInfo; - yName = yCommandInfo != null ? yCommandInfo.Name : yObj as string; + yName = yObj is CommandInfo yCommandInfo ? yCommandInfo.Name : yObj as string; if (xName == null || yName == null) Diagnostics.Assert(false, "Base object of Command PSObject should be either CommandInfo or string"); diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index 2872066e74d..38c8d73703c 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -487,22 +487,19 @@ private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoB object constantValue = null; // This is a single argument - AstPair argumentAstPair = bindingInfo.BoundArguments[item.Key] as AstPair; - if (argumentAstPair != null) + if (bindingInfo.BoundArguments[item.Key] is AstPair argumentAstPair) { value = argumentAstPair.Argument; } // This is a parameter that took an argument, as well as ValueFromRemainingArguments. // Merge the arguments into a single fake argument. - AstArrayPair argumentAstArrayPair = bindingInfo.BoundArguments[item.Key] as AstArrayPair; - if (argumentAstArrayPair != null) + if (bindingInfo.BoundArguments[item.Key] is AstArrayPair argumentAstArrayPair) { List arguments = new List(); foreach (ExpressionAst expression in argumentAstArrayPair.Argument) { - ArrayLiteralAst expressionArray = expression as ArrayLiteralAst; - if (expressionArray != null) + if (expression is ArrayLiteralAst expressionArray) { foreach (ExpressionAst newExpression in expressionArray.Elements) { @@ -615,8 +612,7 @@ private void CreateBindingResultForSyntacticBind(CommandAst commandAst) continue; } - CommandParameterAst parameter = commandElement as CommandParameterAst; - if (parameter != null) + if (commandElement is CommandParameterAst parameter) { if (currentParameter != null) { @@ -752,8 +748,7 @@ internal set { _value = value; - ConstantExpressionAst constantValueAst = value as ConstantExpressionAst; - if (constantValueAst != null) + if (value is ConstantExpressionAst constantValueAst) { this.ConstantValue = constantValueAst.Value; } @@ -1210,8 +1205,7 @@ private bool PrepareCommandElements(ExecutionContext context) // Pre-processing the arguments -- command arguments for (commandIndex++; commandIndex < _commandElements.Count; commandIndex++) { - var parameter = _commandElements[commandIndex] as CommandParameterAst; - if (parameter != null) + if (_commandElements[commandIndex] is CommandParameterAst parameter) { if (argumentsToGetDynamicParameters != null) { @@ -1226,16 +1220,14 @@ private bool PrepareCommandElements(ExecutionContext context) } else { - var dash = _commandElements[commandIndex] as StringConstantExpressionAst; - if (dash != null && dash.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) + if (_commandElements[commandIndex] is StringConstantExpressionAst dash && dash.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) { // "-" is represented by StringConstantExpressionAst. Most likely the user type a tab here, // and we don't want it be treated as an argument continue; } - var expressionArgument = _commandElements[commandIndex] as ExpressionAst; - if (expressionArgument != null) + if (_commandElements[commandIndex] is ExpressionAst expressionArgument) { argumentsToGetDynamicParameters?.Add(expressionArgument.Extent.Text); diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index d1afb8b3b12..43a60c72bb5 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -368,8 +368,7 @@ public string ModuleName } else { - CmdletInfo cmdlet = this as CmdletInfo; - if (cmdlet != null && cmdlet.PSSnapIn != null) + if (this is CmdletInfo cmdlet && cmdlet.PSSnapIn != null) { moduleName = cmdlet.PSSnapInName; } @@ -486,8 +485,7 @@ private class GetMergedCommandParameterMetadataSafelyEventArgs : EventArgs private void OnGetMergedCommandParameterMetadataSafelyEventHandler(object sender, PSEventArgs args) { - var eventArgs = args.SourceEventArgs as GetMergedCommandParameterMetadataSafelyEventArgs; - if (eventArgs != null) + if (args.SourceEventArgs is GetMergedCommandParameterMetadataSafelyEventArgs eventArgs) { try { @@ -522,8 +520,7 @@ private void GetMergedCommandParameterMetadata(out MergedCommandParameterMetadat } else { - IScriptCommandInfo scriptCommand = this as IScriptCommandInfo; - processor = scriptCommand != null + processor = this is IScriptCommandInfo scriptCommand ? new CommandProcessor(scriptCommand, _context, useLocalScope: true, fromScriptFile: false, sessionState: scriptCommand.ScriptBlock.SessionStateInternal ?? Context.EngineSessionState) : new CommandProcessor((CmdletInfo)this, _context) { UseLocalScope = true }; @@ -824,8 +821,7 @@ public PSTypeName(ITypeName typeName) } else { - var t = typeName as TypeName; - if (t != null && t._typeDefinitionAst != null) + if (typeName is TypeName t && t._typeDefinitionAst != null) { TypeDefinitionAst = t._typeDefinitionAst; Name = TypeDefinitionAst.Name; diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index 3396aea65a6..1d021a7bf8b 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -115,21 +115,17 @@ public CommandMetadata(CommandInfo commandInfo, bool shouldGenerateCommonParamet throw PSTraceSource.NewNotSupportedException(); } } - - CmdletInfo cmdletInfo; - ExternalScriptInfo scriptInfo; - FunctionInfo funcInfo; - if ((cmdletInfo = commandInfo as CmdletInfo) != null) + if (commandInfo is CmdletInfo cmdletInfo) { Init(commandInfo.Name, cmdletInfo.FullName, cmdletInfo.ImplementingType, shouldGenerateCommonParameters); } - else if ((scriptInfo = commandInfo as ExternalScriptInfo) != null) + else if (commandInfo is ExternalScriptInfo scriptInfo) { // Accessing the script block property here reads and parses the script Init(scriptInfo.ScriptBlock, scriptInfo.Path, shouldGenerateCommonParameters); _wrappedCommandType = CommandTypes.ExternalScript; } - else if ((funcInfo = commandInfo as FunctionInfo) != null) + else if (commandInfo is FunctionInfo funcInfo) { Init(funcInfo.ScriptBlock, funcInfo.Name, shouldGenerateCommonParameters); _wrappedCommandType = commandInfo.CommandType; @@ -693,8 +689,7 @@ private void ConstructCmdletMetadataUsingReflection() foreach (Attribute attribute in customAttributes) { - CmdletAttribute cmdletAttribute = attribute as CmdletAttribute; - if (cmdletAttribute != null) + if (attribute is CmdletAttribute cmdletAttribute) { ProcessCmdletAttribute(cmdletAttribute); this.Name = cmdletAttribute.VerbName + "-" + cmdletAttribute.NounName; @@ -751,8 +746,7 @@ private void ProcessCmdletAttribute(CmdletCommonMetadataAttribute attribute) _remotingCapability = attribute.RemotingCapability; // Check to see if the cmdlet uses positional binding - var cmdletBindingAttribute = attribute as CmdletBindingAttribute; - if (cmdletBindingAttribute != null) + if (attribute is CmdletBindingAttribute cmdletBindingAttribute) { PositionalBinding = cmdletBindingAttribute.PositionalBinding; } diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index 3671638e120..bf56468d98d 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -107,8 +107,7 @@ internal ParameterBinderController NewParameterBinderController(InternalCommand } ParameterBinderBase parameterBinder; - IScriptCommandInfo scriptCommandInfo = CommandInfo as IScriptCommandInfo; - if (scriptCommandInfo != null) + if (CommandInfo is IScriptCommandInfo scriptCommandInfo) { parameterBinder = new ScriptParameterBinder(scriptCommandInfo.ScriptBlock, cmdlet.MyInvocation, this._context, cmdlet, CommandScope); } @@ -216,8 +215,7 @@ internal override void Prepare(IDictionary psDefaultParameterValues) bool? oldLangModeTransitionStatus = null; try { - var scriptCmdletInfo = this.CommandInfo as IScriptCommandInfo; - if (scriptCmdletInfo != null && + if (this.CommandInfo is IScriptCommandInfo scriptCmdletInfo && scriptCmdletInfo.ScriptBlock.LanguageMode.HasValue && scriptCmdletInfo.ScriptBlock.LanguageMode != Context.LanguageMode) { @@ -256,8 +254,7 @@ protected override void OnSetCurrentScope() { // When dotting a script cmdlet, push the locals of automatic variables to // the 'DottedScopes' of the current scope. - PSScriptCmdlet scriptCmdlet = this.Command as PSScriptCmdlet; - if (scriptCmdlet != null && !UseLocalScope) + if (this.Command is PSScriptCmdlet scriptCmdlet && !UseLocalScope) { scriptCmdlet.PushDottedScope(CommandSessionState.CurrentScope); } @@ -267,8 +264,7 @@ protected override void OnRestorePreviousScope() { // When dotting a script cmdlet, pop the locals of automatic variables from // the 'DottedScopes' of the current scope. - PSScriptCmdlet scriptCmdlet = this.Command as PSScriptCmdlet; - if (scriptCmdlet != null && !UseLocalScope) + if (this.Command is PSScriptCmdlet scriptCmdlet && !UseLocalScope) { scriptCmdlet.PopDottedScope(CommandSessionState.CurrentScope); } diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index 33804b69ae3..e114131698c 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -773,8 +773,7 @@ internal PipelineStoppedException ManageInvocationException(Exception e) { do // false loop { - ProviderInvocationException pie = e as ProviderInvocationException; - if (pie != null) + if (e is ProviderInvocationException pie) { // If a ProviderInvocationException occurred, // discard the ProviderInvocationException and @@ -801,8 +800,7 @@ internal PipelineStoppedException ManageInvocationException(Exception e) break; } - RuntimeException rte = e as RuntimeException; - if (rte != null && rte.WasThrownFromThrowStatement) + if (e is RuntimeException rte && rte.WasThrownFromThrowStatement) { // do not rewrap a script based throw break; @@ -946,8 +944,7 @@ private void Dispose(bool disposing) // 2004/03/05-JonN Look into using metadata to check // whether IDisposable is implemented, in order to avoid // this expensive reflection cast. - IDisposable id = Command as IDisposable; - if (id != null) + if (Command is IDisposable id) { id.Dispose(); } diff --git a/src/System.Management.Automation/engine/CommonCommandParameters.cs b/src/System.Management.Automation/engine/CommonCommandParameters.cs index 73fda1227a7..58512097c6b 100644 --- a/src/System.Management.Automation/engine/CommonCommandParameters.cs +++ b/src/System.Management.Automation/engine/CommonCommandParameters.cs @@ -240,8 +240,7 @@ internal class ValidateVariableName : ValidateArgumentsAttribute { protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { - string varName = arguments as string; - if (varName != null) + if (arguments is string varName) { if (varName.StartsWith('+')) { diff --git a/src/System.Management.Automation/engine/CompiledCommandParameter.cs b/src/System.Management.Automation/engine/CompiledCommandParameter.cs index 90011fbde74..518d76f094d 100644 --- a/src/System.Management.Automation/engine/CompiledCommandParameter.cs +++ b/src/System.Management.Automation/engine/CompiledCommandParameter.cs @@ -437,8 +437,7 @@ private void ProcessAttribute( return; } - ValidateArgumentsAttribute validateAttr = attribute as ValidateArgumentsAttribute; - if (validateAttr != null) + if (attribute is ValidateArgumentsAttribute validateAttr) { if (validationAttributes == null) validationAttributes = new Collection(); @@ -451,8 +450,7 @@ private void ProcessAttribute( return; } - AliasAttribute aliasAttr = attribute as AliasAttribute; - if (aliasAttr != null) + if (attribute is AliasAttribute aliasAttr) { if (aliases == null) { @@ -470,8 +468,7 @@ private void ProcessAttribute( return; } - ArgumentTransformationAttribute argumentAttr = attribute as ArgumentTransformationAttribute; - if (argumentAttr != null) + if (attribute is ArgumentTransformationAttribute argumentAttr) { if (argTransformationAttributes == null) argTransformationAttributes = new Collection(); @@ -479,36 +476,31 @@ private void ProcessAttribute( return; } - AllowNullAttribute allowNullAttribute = attribute as AllowNullAttribute; - if (allowNullAttribute != null) + if (attribute is AllowNullAttribute allowNullAttribute) { this.AllowsNullArgument = true; return; } - AllowEmptyStringAttribute allowEmptyStringAttribute = attribute as AllowEmptyStringAttribute; - if (allowEmptyStringAttribute != null) + if (attribute is AllowEmptyStringAttribute allowEmptyStringAttribute) { this.AllowsEmptyStringArgument = true; return; } - AllowEmptyCollectionAttribute allowEmptyCollectionAttribute = attribute as AllowEmptyCollectionAttribute; - if (allowEmptyCollectionAttribute != null) + if (attribute is AllowEmptyCollectionAttribute allowEmptyCollectionAttribute) { this.AllowsEmptyCollectionArgument = true; return; } - ObsoleteAttribute obsoleteAttr = attribute as ObsoleteAttribute; - if (obsoleteAttr != null) + if (attribute is ObsoleteAttribute obsoleteAttr) { ObsoleteAttribute = obsoleteAttr; return; } - PSTypeNameAttribute psTypeNameAttribute = attribute as PSTypeNameAttribute; - if (psTypeNameAttribute != null) + if (attribute is PSTypeNameAttribute psTypeNameAttribute) { this.PSTypeName = psTypeNameAttribute.PSTypeName; } diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index f1160639c59..bfc964e8a93 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -1617,8 +1617,7 @@ internal static Type EffectiveArgumentType(object arg) if (arg != null) { arg = PSObject.Base(arg); - object[] argAsArray = arg as object[]; - if (argAsArray != null && argAsArray.Length > 0 && PSObject.Base(argAsArray[0]) != null) + if (arg is object[] argAsArray && argAsArray.Length > 0 && PSObject.Base(argAsArray[0]) != null) { Type firstType = PSObject.Base(argAsArray[0]).GetType(); bool allSameType = true; @@ -1887,8 +1886,7 @@ internal static object UnReference(object obj, out bool isArgumentByRef) return reference.Value; } - PSObject mshObj = obj as PSObject; - if (mshObj != null) + if (obj is PSObject mshObj) { reference = mshObj.BaseObject as PSReference; } @@ -1913,8 +1911,7 @@ internal static object PropertySetAndMethodArgumentConvertTo(object valueToConve throw PSTraceSource.NewArgumentNullException(nameof(resultType)); } - PSObject mshObj = valueToConvert as PSObject; - if (mshObj != null) + if (valueToConvert is PSObject mshObj) { if (resultType == typeof(object)) { @@ -3586,8 +3583,7 @@ internal IEnumerable GetPropertiesAndMethods(Type type, bool @static) : GetInstancePropertyReflectionTable(type); for (int i = 0; i < propertyTable.memberCollection.Count; i++) { - var propertyCacheEntry = propertyTable.memberCollection[i] as PropertyCacheEntry; - if (propertyCacheEntry != null) + if (propertyTable.memberCollection[i] is PropertyCacheEntry propertyCacheEntry) yield return propertyCacheEntry.member; } @@ -3596,8 +3592,7 @@ internal IEnumerable GetPropertiesAndMethods(Type type, bool @static) : GetInstanceMethodReflectionTable(type); for (int i = 0; i < methodTable.memberCollection.Count; i++) { - var method = methodTable.memberCollection[i] as MethodCacheEntry; - if (method != null && !method[0].method.IsSpecialName) + if (methodTable.memberCollection[i] is MethodCacheEntry method && !method[0].method.IsSpecialName) { yield return method; } @@ -3743,8 +3738,7 @@ protected T GetFirstDotNetEventOrDefault(object obj, MemberNamePredicate pred protected T GetFirstDynamicMemberOrDefault(object obj, MemberNamePredicate predicate) where T : PSMemberInfo { - var idmop = obj as IDynamicMetaObjectProvider; - if (idmop == null || obj is PSObject) + if (obj is not IDynamicMetaObjectProvider idmop || obj is PSObject) { return null; } @@ -3858,8 +3852,7 @@ internal void AddAllEvents(object obj, PSMemberInfoInternalCollection memb internal void AddAllDynamicMembers(object obj, PSMemberInfoInternalCollection members, bool ignoreDuplicates) where T : PSMemberInfo { - var idmop = obj as IDynamicMetaObjectProvider; - if (idmop == null || obj is PSObject) + if (obj is not IDynamicMetaObjectProvider idmop || obj is PSObject) { return; } @@ -4954,8 +4947,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) PSObject mshObj = (PSObject)obj; foreach (PSMemberInfo member in mshObj.Members) { - T memberAsT = member as T; - if (memberAsT != null) + if (member is T memberAsT) { returnValue.Add(memberAsT); } @@ -5029,8 +5021,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) var returnValue = new PSMemberInfoInternalCollection(); foreach (PSMemberInfo member in ((PSMemberSet)obj).Members) { - T memberAsT = member as T; - if (memberAsT != null) + if (member is T memberAsT) { returnValue.Add(memberAsT); } @@ -5400,8 +5391,7 @@ protected override bool PropertyIsGettable(PSProperty property) private static object GetNodeObject(XmlNode node) { - XmlText text = node as XmlText; - if (text != null) + if (node is XmlText text) { return text.InnerText; } @@ -5427,8 +5417,7 @@ private static object GetNodeObject(XmlNode node) return node.InnerText; } - XmlAttribute attribute = node as XmlAttribute; - if (attribute != null) + if (node is XmlAttribute attribute) { return attribute.Value; } @@ -5479,8 +5468,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c } XmlNode node = nodes[0]; - XmlText text = node as XmlText; - if (text != null) + if (node is XmlText text) { text.InnerText = valueString; return; @@ -5509,8 +5497,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c return; } - XmlAttribute attribute = node as XmlAttribute; - if (attribute != null) + if (node is XmlAttribute attribute) { attribute.Value = valueString; return; diff --git a/src/System.Management.Automation/engine/DscResourceSearcher.cs b/src/System.Management.Automation/engine/DscResourceSearcher.cs index bfd406f56ff..22007ea3d63 100644 --- a/src/System.Management.Automation/engine/DscResourceSearcher.cs +++ b/src/System.Management.Automation/engine/DscResourceSearcher.cs @@ -151,9 +151,8 @@ private DscResourceInfo GetNextDscResource() resourceInfo.CompanyName = resource.CompanyName; - PSModuleInfo psMod = resource.Module as PSModuleInfo; - if (psMod != null) + if (resource.Module is PSModuleInfo psMod) resourceInfo.Module = psMod; if (resource.ImplementedAs != null) @@ -163,9 +162,8 @@ private DscResourceInfo GetNextDscResource() resourceInfo.ImplementedAs = impType; } - var properties = resource.Properties as IList; - if (properties != null) + if (resource.Properties is IList properties) { List propertyList = new List(); diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index d35130092fe..c019939eb32 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -1299,8 +1299,7 @@ private void ConstructFromPSObjectForRemoting(PSObject serializedErrorRecord) string exceptionMessage = null; if (serializedException != null) { - PSPropertyInfo messageProperty = serializedException.Properties["Message"] as PSPropertyInfo; - if (messageProperty != null) + if (serializedException.Properties["Message"] is PSPropertyInfo messageProperty) { exceptionMessage = messageProperty.Value as string; } @@ -1660,8 +1659,7 @@ private string GetInvocationTypeName() return string.Empty; } - IScriptCommandInfo scriptInfo = commandInfo as IScriptCommandInfo; - if (scriptInfo != null) + if (commandInfo is IScriptCommandInfo scriptInfo) { return commandInfo.Name; } diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index f820aec608b..1302c5f61e7 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -572,9 +572,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// private void OnElapsedEvent(object source) { - var localRunspace = _context.CurrentRunspace as LocalRunspace; - - if (localRunspace == null) + if (_context.CurrentRunspace is not LocalRunspace localRunspace) { // This should never happen, the context should always reference to the local runspace _consecutiveIdleSamples = 0; @@ -2201,8 +2199,7 @@ internal PSEventArgs(string computerName, Guid runspaceId, int eventIdentifier, { foreach (object argument in originalArgs) { - EventArgs sourceEventArgs = argument as EventArgs; - if (sourceEventArgs != null) + if (argument is EventArgs sourceEventArgs) { SourceEventArgs = sourceEventArgs; break; diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 3a726be8f73..4aa85f5dbb9 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -434,8 +434,7 @@ internal static void MarkObjectAsUntrusted(object value) // This could result in a recursion if psRef.Value points to itself directly or indirectly, so we check if psRef.Value is already // marked before making a recursive call. The additional check adds extra overhead for handling PSReference object, but it should // be rare in practice. - var psRef = baseValue as PSReference; - if (psRef != null && !IsMarkedAsUntrusted(psRef.Value)) + if (baseValue is PSReference psRef && !IsMarkedAsUntrusted(psRef.Value)) { MarkObjectAsUntrusted(psRef.Value); } @@ -591,8 +590,7 @@ internal T GetEnumPreference(VariablePath preferenceVariablePath, T defaultPr { try { - string valString = val as string; - if (valString != null) + if (val is string valString) { result = (T)Enum.Parse(typeof(T), valString, true); defaultUsed = false; @@ -882,8 +880,7 @@ internal void AppendDollarError(object obj) } object old = this.DollarErrorVariable; - ArrayList arraylist = old as ArrayList; - if (arraylist == null) + if (old is not ArrayList arraylist) { Diagnostics.Assert(false, "$error should be a global constant ArrayList"); return; @@ -897,9 +894,8 @@ internal void AppendDollarError(object obj) if (arraylist[0] == obj) return; // otherwise check the exception members of the error records... - ErrorRecord er1 = arraylist[0] as ErrorRecord; - if (er1 != null && objAsErrorRecord != null && er1.Exception == objAsErrorRecord.Exception) + if (arraylist[0] is ErrorRecord er1 && objAsErrorRecord != null && er1.Exception == objAsErrorRecord.Exception) return; } @@ -1500,9 +1496,8 @@ internal void ReportEngineStartupError(Exception e) if (IsModuleCommandCurrentlyRunning(out currentRunningModuleCommand, out errorId)) { ErrorRecord error = null; - var rte = e as RuntimeException; - error = rte != null + error = e is RuntimeException rte ? new ErrorRecord(rte.ErrorRecord, rte) : new ErrorRecord(e, errorId, ErrorCategory.OperationStopped, null); diff --git a/src/System.Management.Automation/engine/ExtraAdapter.cs b/src/System.Management.Automation/engine/ExtraAdapter.cs index dd6ba0c0784..40a4e55a452 100644 --- a/src/System.Management.Automation/engine/ExtraAdapter.cs +++ b/src/System.Management.Automation/engine/ExtraAdapter.cs @@ -191,9 +191,7 @@ protected override object PropertyGet(PSProperty property) /// Instructs the adapter to convert before setting, if the adapter supports conversion. protected override void PropertySet(PSProperty property, object setValue, bool convertIfPossible) { - PropertyValueCollection values = property.adapterData as PropertyValueCollection; - - if (values != null) + if (property.adapterData is PropertyValueCollection values) { // This means GetMember returned PropertyValueCollection try diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 369ce76ad06..f2350ebb4e0 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -726,8 +726,7 @@ private bool IsNounVerbMatch(CommandInfo command) // Get the noun and verb to check... string verb; string noun; - CmdletInfo cmdlet = command as CmdletInfo; - if (cmdlet != null) + if (command is CmdletInfo cmdlet) { verb = cmdlet.Verb; noun = cmdlet.Noun; @@ -1105,29 +1104,25 @@ private bool IsDuplicate(CommandInfo info) do // false loop { - ApplicationInfo appInfo = info as ApplicationInfo; - if (appInfo != null) + if (info is ApplicationInfo appInfo) { key = appInfo.Path; break; } - CmdletInfo cmdletInfo = info as CmdletInfo; - if (cmdletInfo != null) + if (info is CmdletInfo cmdletInfo) { key = cmdletInfo.FullName; break; } - ScriptInfo scriptInfo = info as ScriptInfo; - if (scriptInfo != null) + if (info is ScriptInfo scriptInfo) { key = scriptInfo.Definition; break; } - ExternalScriptInfo externalScriptInfo = info as ExternalScriptInfo; - if (externalScriptInfo != null) + if (info is ExternalScriptInfo externalScriptInfo) { key = externalScriptInfo.Path; break; diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 8d9b01ad134..2cd16160ddd 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -1290,8 +1290,7 @@ private static void MakeDisallowedEntriesPrivate(InitialSessionStateEntryColl string entryName = nameGetter(entry); // Aliases to allowed commands are OK - SessionStateAliasEntry aliasEntry = entry as SessionStateAliasEntry; - if (aliasEntry != null) + if (entry is SessionStateAliasEntry aliasEntry) { if (allowedNames.Exists(allowedName => allowedName.Equals(aliasEntry.Definition, StringComparison.OrdinalIgnoreCase))) { @@ -2337,8 +2336,7 @@ private void Bind_BindCommands(PSModuleInfo module, bool noClobber, bool local, RunspaceEventSource.Log.LoadCommandStart(cmd.Name); } - SessionStateCmdletEntry ssce = cmd as SessionStateCmdletEntry; - if (ssce != null) + if (cmd is SessionStateCmdletEntry ssce) { if (noClobber && ModuleCmdletBase.CommandFound(ssce.Name, ss)) { @@ -2354,22 +2352,19 @@ private void Bind_BindCommands(PSModuleInfo module, bool noClobber, bool local, cmd.SetModule(module); - SessionStateFunctionEntry ssfe = cmd as SessionStateFunctionEntry; - if (ssfe != null) + if (cmd is SessionStateFunctionEntry ssfe) { ss.AddSessionStateEntry(ssfe); continue; } - SessionStateAliasEntry ssae = cmd as SessionStateAliasEntry; - if (ssae != null) + if (cmd is SessionStateAliasEntry ssae) { ss.AddSessionStateEntry(ssae, StringLiterals.Local); continue; } - SessionStateApplicationEntry ssappe = cmd as SessionStateApplicationEntry; - if (ssappe != null) + if (cmd is SessionStateApplicationEntry ssappe) { if (ssappe.Visibility == SessionStateEntryVisibility.Public) { @@ -2379,8 +2374,7 @@ private void Bind_BindCommands(PSModuleInfo module, bool noClobber, bool local, continue; } - SessionStateScriptEntry ssse = cmd as SessionStateScriptEntry; - if (ssse != null) + if (cmd is SessionStateScriptEntry ssse) { if (ssse.Visibility == SessionStateEntryVisibility.Public) { @@ -2660,8 +2654,7 @@ private void ProcessCommandModifications(Runspace initializedRunspace) } // If we are wrapping a function, rename it. - FunctionInfo commandAsFunction = existingCommand as FunctionInfo; - if (commandAsFunction != null) + if (existingCommand is FunctionInfo commandAsFunction) { string newCommandName = commandAsFunction.Name + "_" + Guid.NewGuid().ToString("N"); commandAsFunction.Rename(newCommandName); @@ -2755,9 +2748,8 @@ private Exception ProcessDynamicVariables(Runspace initializedRunspace) if (variable.ContainsKey("Name")) { string name = variable["Name"].ToString(); - ScriptBlock sb = variable["Value"] as ScriptBlock; - if (!string.IsNullOrEmpty(name) && (sb != null)) + if (!string.IsNullOrEmpty(name) && (variable["Value"] is ScriptBlock sb)) { sb.SessionStateInternal = initializedRunspace.ExecutionContext.EngineSessionState; @@ -2915,15 +2907,13 @@ private Exception ProcessPowerShellCommand(PowerShell psToInvoke, Runspace initi ArrayList errorList = (ArrayList)initializedRunspace.GetExecutionContext.DollarErrorVariable; if (errorList.Count > 0) { - ErrorRecord lastErrorRecord = errorList[0] as ErrorRecord; - if (lastErrorRecord != null) + if (errorList[0] is ErrorRecord lastErrorRecord) { return new Exception(lastErrorRecord.ToString()); } else { - Exception lastException = errorList[0] as Exception; - if (lastException != null) + if (errorList[0] is Exception lastException) { return lastException; } @@ -2949,15 +2939,13 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( foreach (object module in moduleList) { - string moduleName = module as string; - if (moduleName != null) + if (module is string moduleName) { exceptionToReturn = ProcessOneModule(initializedRunspace, moduleName, null, path, publicCommands); } else { - ModuleSpecification moduleSpecification = module as ModuleSpecification; - if (moduleSpecification != null) + if (module is ModuleSpecification moduleSpecification) { if ((moduleSpecification.RequiredVersion == null) && (moduleSpecification.Version == null) && (moduleSpecification.MaximumVersion == null) && (moduleSpecification.Guid == null)) { @@ -3406,8 +3394,7 @@ internal void Unbind(ExecutionContext context) // Remove all of the commands from the top-level session state. foreach (SessionStateCommandEntry cmd in Commands) { - SessionStateCmdletEntry ssce = cmd as SessionStateCmdletEntry; - if (ssce != null) + if (cmd is SessionStateCmdletEntry ssce) { List matches; if (context.TopLevelSessionState.GetCmdletTable().TryGetValue(ssce.Name, out matches)) diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 0928cc8a0d4..74a36a85044 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -723,8 +723,7 @@ private void ProcessPropertyAndMethodParameterSet() if (member is PSMethodInfo) { // first we check if the member is a ParameterizedProperty - PSParameterizedProperty targetParameterizedProperty = member as PSParameterizedProperty; - if (targetParameterizedProperty != null) + if (member is PSParameterizedProperty targetParameterizedProperty) { // should process string propertyAction = string.Format(CultureInfo.InvariantCulture, @@ -763,8 +762,7 @@ private void ProcessPropertyAndMethodParameterSet() } catch (Exception ex) { - MethodException mex = ex as MethodException; - if (mex != null && mex.ErrorRecord != null && mex.ErrorRecord.FullyQualifiedErrorId == "MethodCountCouldNotFindBest") + if (ex is MethodException mex && mex.ErrorRecord != null && mex.ErrorRecord.FullyQualifiedErrorId == "MethodCountCouldNotFindBest") { WriteObject(targetMethod.Value); } @@ -1101,8 +1099,7 @@ private static string GetStringRepresentation(object obj) if (string.IsNullOrEmpty(objInString)) { - var psobj = obj as PSObject; - objInString = psobj != null ? psobj.BaseObject.GetType().FullName : obj.GetType().FullName; + objInString = obj is PSObject psobj ? psobj.BaseObject.GetType().FullName : obj.GetType().FullName; } return objInString; @@ -1116,11 +1113,10 @@ private static string GetStringRepresentation(object obj) private bool GetValueFromIDictionaryInput() { object target = PSObject.Base(_inputObject); - IDictionary hash = target as IDictionary; try { - if (hash != null && hash.Contains(_propertyOrMethodName)) + if (target is IDictionary hash && hash.Contains(_propertyOrMethodName)) { string keyAction = string.Format( CultureInfo.InvariantCulture, @@ -2191,8 +2187,7 @@ protected override void BeginProcessing() case TokenKind.Is: case TokenKind.IsNot: // users might input [int], [string] as they do when using scripts - var strValue = _convertedValue as string; - if (strValue != null) + if (_convertedValue is string strValue) { var typeLength = strValue.Length; if (typeLength > 2 && strValue[0] == '[' && strValue[typeLength - 1] == ']') @@ -2334,10 +2329,9 @@ private object GetValue(ref bool error) // return that, otherwise fall through and see if there is an // underlying member corresponding to the key... object target = PSObject.Base(_inputObject); - IDictionary hash = target as IDictionary; try { - if (hash != null && hash.Contains(_property)) + if (target is IDictionary hash && hash.Contains(_property)) { return hash[_property]; } @@ -2647,8 +2641,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input { object version = PSObject.Base(inputData); - string versionStr = version as string; - if (versionStr != null) + if (version is string versionStr) { if (versionStr.Equals("latest", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/System.Management.Automation/engine/InvocationInfo.cs b/src/System.Management.Automation/engine/InvocationInfo.cs index 1871ae3c9cd..7d687bb1635 100644 --- a/src/System.Management.Automation/engine/InvocationInfo.cs +++ b/src/System.Management.Automation/engine/InvocationInfo.cs @@ -76,8 +76,7 @@ internal InvocationInfo(CommandInfo commandInfo, IScriptExtent scriptPosition, E // Populate the history ID of this command if (contextToUse != null) { - Runspaces.LocalRunspace localRunspace = contextToUse.CurrentRunspace as Runspaces.LocalRunspace; - if (localRunspace != null && localRunspace.History != null) + if (contextToUse.CurrentRunspace is Runspaces.LocalRunspace localRunspace && localRunspace.History != null) { HistoryId = localRunspace.History.GetNextHistoryId(); } @@ -431,8 +430,7 @@ internal void ToPSObjectForRemoting(PSObject psObject) RemotingEncoder.AddNoteProperty(psObject, "InvocationInfo_ScriptName", () => this.ScriptName); RemotingEncoder.AddNoteProperty(psObject, "InvocationInfo_UnboundArguments", () => this.UnboundArguments); - ScriptExtent extent = DisplayScriptPosition as ScriptExtent; - if (extent != null) + if (DisplayScriptPosition is ScriptExtent extent) { extent.ToPSObjectForRemoting(psObject); RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", () => true); diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 322d21faca8..e610745d8c8 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -655,9 +655,8 @@ public static bool Equals(object first, object second, bool ignoreCase, IFormatP return false; // first is not null } - string firstString = first as string; string secondString; - if (firstString != null) + if (first is string firstString) { secondString = second as string ?? (string)LanguagePrimitives.ConvertTo(second, typeof(string), culture); return (culture.CompareInfo.Compare(firstString, secondString, @@ -804,8 +803,7 @@ public static int Compare(object first, object second, bool ignoreCase, IFormatP if (first is string firstString) { - string secondString = second as string; - if (secondString == null) + if (second is not string secondString) { try { @@ -1014,8 +1012,7 @@ public static bool IsTrue(object obj) if (objType == typeof(SwitchParameter)) return ((SwitchParameter)obj).ToBool(); - IList objectArray = obj as IList; - if (objectArray != null) + if (obj is IList objectArray) { return IsTrue(objectArray); } @@ -1195,8 +1192,7 @@ internal static T FromObjectAs(object castObject) T returnType = default(T); // First, see if we can cast the direct type - PSObject wrapperObject = castObject as PSObject; - if (wrapperObject == null) + if (castObject is not PSObject wrapperObject) { try { @@ -1529,8 +1525,7 @@ private static object NewConverterInstance(string assemblyQualifiedTypeName) } catch (Exception e) { - TargetInvocationException inner = e as TargetInvocationException; - string message = (inner == null) || (inner.InnerException == null) ? e.Message : inner.InnerException.Message; + string message = (e is not TargetInvocationException inner) || (inner.InnerException == null) ? e.Message : inner.InnerException.Message; typeConversion.WriteLine("Creating an instance of type \"{0}\" caused an exception to be thrown: \"{1}\"", assemblyQualifiedTypeName, message); return null; } @@ -2582,8 +2577,7 @@ private static bool IsCustomTypeConversion(object valueToConvert, if ((valueConverter != null)) { - TypeConverter valueTypeConverter = valueConverter as TypeConverter; - if (valueTypeConverter != null) + if (valueConverter is TypeConverter valueTypeConverter) { typeConversion.WriteLine("Original type's converter is TypeConverter."); if (valueTypeConverter.CanConvertTo(resultType)) @@ -2608,8 +2602,7 @@ private static bool IsCustomTypeConversion(object valueToConvert, } } - PSTypeConverter valuePSTypeConverter = valueConverter as PSTypeConverter; - if (valuePSTypeConverter != null) + if (valueConverter is PSTypeConverter valuePSTypeConverter) { typeConversion.WriteLine("Original type's converter is PSTypeConverter."); PSObject psValueToConvert = PSObject.AsPSObject(valueToConvert); @@ -2642,8 +2635,7 @@ private static bool IsCustomTypeConversion(object valueToConvert, valueConverter = GetConverter(resultType, backupTypeTable); if (valueConverter != null) { - TypeConverter valueTypeConverter = valueConverter as TypeConverter; - if (valueTypeConverter != null) + if (valueConverter is TypeConverter valueTypeConverter) { typeConversion.WriteLine("Destination type's converter is TypeConverter that can convert from originalType."); if (valueTypeConverter.CanConvertFrom(originalType)) @@ -2668,8 +2660,7 @@ private static bool IsCustomTypeConversion(object valueToConvert, } } - PSTypeConverter valuePSTypeConverter = valueConverter as PSTypeConverter; - if (valuePSTypeConverter != null) + if (valueConverter is PSTypeConverter valuePSTypeConverter) { typeConversion.WriteLine("Destination type's converter is PSTypeConverter."); PSObject psValueToConvert = PSObject.AsPSObject(valueToConvert); @@ -3987,8 +3978,7 @@ internal object Convert(object valueToConvert, if (ecFromTLS == null || (ecFromTLS.LanguageMode == PSLanguageMode.FullLanguage && !ecFromTLS.LanguageModeTransitionInParameterBinding)) { result = _constructor(); - var psobject = valueToConvert as PSObject; - if (psobject != null) + if (valueToConvert is PSObject psobject) { // Use PSObject properties to perform conversion. SetObjectProperties(result, psobject, resultType, CreateMemberNotFoundError, CreateMemberSetValueError, formatProvider, recursion, ignoreUnknownMembers); @@ -4604,8 +4594,7 @@ internal static PSObject SetObjectProperties(object o, PSObject psObject, Type r else { object baseObj = PSObject.Base(psObject); - var dictionary = baseObj as IDictionary; - if (dictionary != null) + if (baseObj is IDictionary dictionary) { // Win8:649519 return SetObjectProperties(o, dictionary, resultType, memberNotFoundErrorAction, memberSetValueErrorAction, enableMethodCall: false); @@ -4613,8 +4602,7 @@ internal static PSObject SetObjectProperties(object o, PSObject psObject, Type r else { // Support PSObject to Strong type conversion. - PSObject psBaseObject = baseObj as PSObject; - if (psBaseObject != null) + if (baseObj is PSObject psBaseObject) { Dictionary properties = new Dictionary(); foreach (var item in psBaseObject.Properties) @@ -4675,8 +4663,7 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T try { - PSObject propertyValue = prop.Value as PSObject; - if (propertyValue != null) + if (prop.Value is PSObject propertyValue) { propValue = LanguagePrimitives.ConvertPSObjectToType(propertyValue, propType, recursion, formatProvider, ignoreUnknownMembers); } @@ -4702,9 +4689,7 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T { if (pso.BaseObject is PSCustomObject) { - var key = prop.Key as string; - var value = prop.Value as string; - if (key != null && value != null && key.Equals("PSTypeName", StringComparison.OrdinalIgnoreCase)) + if (prop.Key is string key && prop.Value is string value && key.Equals("PSTypeName", StringComparison.OrdinalIgnoreCase)) { pso.TypeNames.Insert(0, value); } diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index d1669bb4593..106d960c515 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -105,8 +105,7 @@ private IEnumerable GetTypeNameHierarchyFromDerivation(ManagementBaseObj Dbg.Assert(derivationData.IsArray, "__Derivation must be a string array as per MSDN documentation"); // give the typenames based on NameSpace + __Derivation - string[] typeHierarchy = PropertySetAndMethodArgumentConvertTo(derivationData.Value, typeof(string[]), CultureInfo.InvariantCulture) as string[]; - if (typeHierarchy != null) + if (PropertySetAndMethodArgumentConvertTo(derivationData.Value, typeof(string[]), CultureInfo.InvariantCulture) is string[] typeHierarchy) { foreach (string t in typeHierarchy) { @@ -534,16 +533,14 @@ private static void PopulateMethodTable(ManagementClass mgmtClass, CacheTable me private static ManagementClass CreateClassFrmObject(ManagementBaseObject mgmtBaseObject) { // Construct a ManagementClass object for this object to get the member metadata - ManagementClass mgmtClass = mgmtBaseObject as ManagementClass; // try to use the actual object sent to this method..otherwise construct one - if (mgmtClass == null) + if (mgmtBaseObject is not ManagementClass mgmtClass) { mgmtClass = new ManagementClass(mgmtBaseObject.ClassPath); // inherit ManagementObject properties - ManagementObject mgmtObject = mgmtBaseObject as ManagementObject; - if (mgmtObject != null) + if (mgmtBaseObject is ManagementObject mgmtObject) { mgmtClass.Scope = mgmtObject.Scope; mgmtClass.Options = mgmtObject.Options; diff --git a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs index 8b055d8fb0f..921a4efea85 100644 --- a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs +++ b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs @@ -250,8 +250,7 @@ private static bool CheckModulesTypesInManifestAgainstExportedCommands(Hashtable var nestedModules = moduleManifestProperties["NestedModules"]; if (nestedModules != null) { - var nestedModule = nestedModules as string; - if (nestedModule != null) + if (nestedModules is string nestedModule) { return ModuleAnalysisViaGetModuleRequired(nestedModule, hadCmdlets, hadFunctions, hadAliases); } @@ -298,14 +297,12 @@ private static bool AddPsd1EntryToResult(ConcurrentDictionary result, object value, CommandTypes commandTypeToAdd, ref bool sawWildcard) { - string command = value as string; - if (command != null) + if (value is string command) { return AddPsd1EntryToResult(result, command, commandTypeToAdd, ref sawWildcard); } - object[] commands = value as object[]; - if (commands != null) + if (value is object[] commands) { foreach (var o in commands) { diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 32d5326a48c..630100a8ab5 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -534,8 +534,7 @@ internal Hashtable LoadModuleManifestData( } } - Hashtable data = result as Hashtable; - if (data == null) + if (result is not Hashtable data) { if (writingErrors) { @@ -2602,8 +2601,7 @@ internal PSModuleInfo LoadModuleManifest( { using (TextReader reader = File.OpenText(psgetItemInfoXml)) { - PSObject xml = PSSerializer.Deserialize(reader.ReadToEnd()) as PSObject; - if (xml != null && xml.Properties["RepositorySourceLocation"] != null) + if (PSSerializer.Deserialize(reader.ReadToEnd()) is PSObject xml && xml.Properties["RepositorySourceLocation"] != null) { var repositorySourceLocation = xml.Properties["RepositorySourceLocation"].Value.ToString(); Uri repositorySourceLocationUri; @@ -5174,8 +5172,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC Context.Modules.IsImplicitRemotingModuleLoaded = false; foreach (var modInfo in Context.Modules.ModuleTable.Values) { - var privateData = modInfo.PrivateData as Hashtable; - if ((privateData != null) && privateData.ContainsKey("ImplicitRemoting")) + if ((modInfo.PrivateData is Hashtable privateData) && privateData.ContainsKey("ImplicitRemoting")) { Context.Modules.IsImplicitRemotingModuleLoaded = true; break; @@ -7086,9 +7083,8 @@ internal static void AddModuleToModuleTables(ExecutionContext context, SessionSt targetSessionState.Module.AddNestedModule(module); } - var privateDataHashTable = module.PrivateData as Hashtable; if (context.Modules.IsImplicitRemotingModuleLoaded == false && - privateDataHashTable != null && privateDataHashTable.ContainsKey("ImplicitRemoting")) + module.PrivateData is Hashtable privateDataHashTable && privateDataHashTable.ContainsKey("ImplicitRemoting")) { context.Modules.IsImplicitRemotingModuleLoaded = true; } diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 71f86332861..6e0dbf32dab 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -190,8 +190,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object } else { - var sbText = moduleCode as string; - if (sbText != null) + if (moduleCode is string sbText) sb = ScriptBlock.Create(_context, sbText); } } diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index 65c2931db0f..8fb8fa1d700 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -324,8 +324,7 @@ internal static ErrorRecord GetErrorRecordForProcessingOfCimModule(Exception inn private static ErrorRecord GetErrorRecordForRemoteDiscoveryProvider(Exception innerException) { - CimException cimException = innerException as CimException; - if ((cimException != null) && + if ((innerException is CimException cimException) && ((cimException.NativeErrorCode == NativeErrorCode.InvalidNamespace) || (cimException.NativeErrorCode == NativeErrorCode.InvalidClass) || (cimException.NativeErrorCode == NativeErrorCode.MethodNotFound) || @@ -359,8 +358,7 @@ private static ErrorRecord GetErrorRecordForRemotePipelineInvocation(Exception i innerException.Message); Exception outerException = new InvalidOperationException(errorMessage, innerException); - RemoteException remoteException = innerException as RemoteException; - ErrorRecord remoteErrorRecord = remoteException != null ? remoteException.ErrorRecord : null; + ErrorRecord remoteErrorRecord = innerException is RemoteException remoteException ? remoteException.ErrorRecord : null; string errorId = remoteErrorRecord != null ? remoteErrorRecord.FullyQualifiedErrorId : innerException.GetType().Name; ErrorCategory errorCategory = remoteErrorRecord != null ? remoteErrorRecord.CategoryInfo.Category : ErrorCategory.NotSpecified; ErrorRecord errorRecord = new ErrorRecord(outerException, errorId, errorCategory, null); @@ -1082,15 +1080,13 @@ internal static void DispatchModuleInfoProcessing( return; } - Tuple cimSessionInfo = weaklyTypeSession as Tuple; - if (cimSessionInfo != null) + if (weaklyTypeSession is Tuple cimSessionInfo) { cimSessionAction(cimSessionInfo.Item1, cimSessionInfo.Item2, cimSessionInfo.Item3); return; } - PSSession psSession = weaklyTypeSession as PSSession; - if (psSession != null) + if (weaklyTypeSession is PSSession psSession) { psSessionAction(psSession); return; diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index 4db13309f6b..8bd07498d78 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -197,8 +197,7 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun { foreach (ExpressionAst aliasAst in attribute.PositionalArguments) { - var aliasExpression = aliasAst as StringConstantExpressionAst; - if (aliasExpression != null) + if (aliasAst is StringConstantExpressionAst aliasExpression) { string alias = aliasExpression.Value; @@ -426,15 +425,13 @@ private void ProcessCmdletArguments(object value, Action onEachArgument) { if (value == null) return; - var commandName = value as string; - if (commandName != null) + if (value is string commandName) { onEachArgument(commandName); return; } - var names = value as object[]; - if (names != null) + if (value is object[] names) { foreach (var n in names) { @@ -462,8 +459,7 @@ private Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string command for (int i = 1; i < commandAst.CommandElements.Count; i++) { var element = commandAst.CommandElements[i]; - var specifiedParameter = element as CommandParameterAst; - if (specifiedParameter != null) + if (element is CommandParameterAst specifiedParameter) { bool boundParameter = false; var specifiedParamName = specifiedParameter.ParameterName; diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index 65802f8b712..d86cca797f1 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -661,8 +661,7 @@ internal IEnumerable GetCommands(string name, CommandTypes commandT continue; } - CommandInfo commandInfo = ((IEnumerator)searcher).Current as CommandInfo; - if (commandInfo != null) + if (((IEnumerator)searcher).Current is CommandInfo commandInfo) { yield return commandInfo; } @@ -853,8 +852,7 @@ private Collection InvokeScript(ScriptBlock sb, bool useNewScope, } // If the result is already a collection of PSObjects, just return it... - Collection result = rawResult as Collection; - if (result != null) + if (rawResult is Collection result) return result; result = new Collection(); @@ -971,8 +969,7 @@ public PagingParameters PagingParameters if (_pagingParameters == null) { - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { _pagingParameters = mshCommandRuntime.PagingParameters ?? new PagingParameters(mshCommandRuntime); } diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 2709ba1384e..9788a349529 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -781,8 +781,7 @@ internal void WriteInformation(InformationRecord record, bool overrideInquire = if ((record.Tags.Contains("PSHOST") && (!record.Tags.Contains("FORWARDED"))) || (preference == ActionPreference.Continue)) { - HostInformationMessage hostOutput = record.MessageData as HostInformationMessage; - if (hostOutput != null) + if (record.MessageData is HostInformationMessage hostOutput) { string message = hostOutput.Message; ConsoleColor? foregroundColor = null; @@ -890,9 +889,7 @@ public void WriteCommandDetail(string text) private bool InitShouldLogPipelineExecutionDetail() { - CmdletInfo cmdletInfo = _commandInfo as CmdletInfo; - - if (cmdletInfo != null) + if (_commandInfo is CmdletInfo cmdletInfo) { if (string.Equals("Add-Type", cmdletInfo.Name, StringComparison.OrdinalIgnoreCase)) { @@ -913,8 +910,7 @@ private bool InitShouldLogPipelineExecutionDetail() } // Logging should be enabled for functions from modules also - FunctionInfo functionInfo = _commandInfo as FunctionInfo; - if (functionInfo != null && functionInfo.Module != null) + if (_commandInfo is FunctionInfo functionInfo && functionInfo.Module != null) { return functionInfo.Module.LogPipelineExecutionDetails; } diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index 71d567c7d1b..c43f5fd4b1a 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -1302,10 +1302,9 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) return true; } - PSObject mshObj = obj as PSObject; #region plain object - if (mshObj == null) + if (obj is not PSObject mshObj) { if (obj == null) { @@ -1353,10 +1352,9 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) #region object ToString - IFormattable objFormattable = obj as IFormattable; try { - if (objFormattable == null) + if (obj is not IFormattable objFormattable) { Type type = obj as Type; if (type != null) @@ -1495,10 +1493,9 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) return baseObjString; } - IFormattable msjObjFormattable = baseObject as IFormattable; try { - var result = msjObjFormattable == null ? baseObject.ToString() : msjObjFormattable.ToString(format, formatProvider); + var result = baseObject is not IFormattable msjObjFormattable ? baseObject.ToString() : msjObjFormattable.ToString(format, formatProvider); return result ?? string.Empty; } diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index 6ad66f6c100..1da0542762e 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -215,8 +215,7 @@ private static PSObject GetComponentPSObject(object component) { // If you use the PSObjectTypeDescriptor directly as your object, it will be the component // if you use a provider, the PSObject will be the component. - PSObject mshObj = component as PSObject; - if (mshObj == null) + if (component is not PSObject mshObj) { if (!(component is PSObjectTypeDescriptor descriptor)) { @@ -275,8 +274,7 @@ public override void SetValue(object component, object value) PSObject mshObj = GetComponentPSObject(component); try { - PSPropertyInfo property = mshObj.Properties[this.Name] as PSPropertyInfo; - if (property == null) + if (mshObj.Properties[this.Name] is not PSPropertyInfo property) { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to set its value.", this.Name); ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorSetValue", @@ -379,11 +377,9 @@ private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attrib Type propertyType = typeof(object); if (attributes != null && attributes.Length != 0) { - PSProperty property = propertyInfo as PSProperty; - if (property != null) + if (propertyInfo is PSProperty property) { - DotNetAdapter.PropertyCacheEntry propertyEntry = property.adapterData as DotNetAdapter.PropertyCacheEntry; - if (propertyEntry == null) + if (property.adapterData is not DotNetAdapter.PropertyCacheEntry propertyEntry) { typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it is an adapted property (not a .NET property).", property.Name); } @@ -508,8 +504,7 @@ public override PropertyDescriptor GetDefaultProperty() PSMemberSet standardMembers = this.Instance.PSStandardMembers; if (standardMembers != null) { - PSNoteProperty note = standardMembers.Properties[TypeTable.DefaultDisplayProperty] as PSNoteProperty; - if (note != null) + if (standardMembers.Properties[TypeTable.DefaultDisplayProperty] is PSNoteProperty note) { defaultProperty = note.Value as string; } @@ -520,8 +515,7 @@ public override PropertyDescriptor GetDefaultProperty() object[] defaultPropertyAttributes = this.Instance.BaseObject.GetType().GetCustomAttributes(typeof(DefaultPropertyAttribute), true); if (defaultPropertyAttributes.Length == 1) { - DefaultPropertyAttribute defaultPropertyAttribute = defaultPropertyAttributes[0] as DefaultPropertyAttribute; - if (defaultPropertyAttribute != null) + if (defaultPropertyAttributes[0] is DefaultPropertyAttribute defaultPropertyAttribute) { defaultProperty = defaultPropertyAttribute.Name; } diff --git a/src/System.Management.Automation/engine/MshReference.cs b/src/System.Management.Automation/engine/MshReference.cs index 05077708608..3fbdb8e4980 100644 --- a/src/System.Management.Automation/engine/MshReference.cs +++ b/src/System.Management.Automation/engine/MshReference.cs @@ -47,9 +47,7 @@ public object Value { get { - PSVariable variable = _value as PSVariable; - - if (variable != null) + if (_value is PSVariable variable) { return variable.Value; } @@ -59,9 +57,7 @@ public object Value set { - PSVariable variable = _value as PSVariable; - - if (variable != null) + if (_value is PSVariable variable) { variable.Value = value; return; diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 0af57e7b420..2f6aaf54683 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -1064,8 +1064,7 @@ private void ProcessOutputRecord(ProcessOutputObject outputValue) } else if (outputValue.Stream == MinishellStream.Progress) { - PSObject temp = outputValue.Data as PSObject; - if (temp != null) + if (outputValue.Data is PSObject temp) { long sourceId = 0; PSMemberInfo info = temp.Properties["SourceId"]; diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index f3572cdbeb5..d871acc600f 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -390,9 +390,7 @@ internal virtual bool BindParameter( { try { - ArgumentTypeConverterAttribute argumentTypeConverter = dma as ArgumentTypeConverterAttribute; - - if (argumentTypeConverter != null) + if (dma is ArgumentTypeConverterAttribute argumentTypeConverter) { if (coerceTypeIfNeeded) { @@ -558,8 +556,7 @@ internal virtual bool BindParameter( parameterMetadata.Name, parameterMetadata.ObsoleteAttribute.Message); - var mshCommandRuntime = this.Command.commandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (this.Command.commandRuntime is MshCommandRuntime mshCommandRuntime) { // Write out warning only if we are in the context of MshCommandRuntime. // This is because @@ -619,8 +616,7 @@ internal virtual bool BindParameter( this.CommandLineParameters.Add(parameter.ParameterName, parameterValue); } - MshCommandRuntime cmdRuntime = this.Command.commandRuntime as MshCommandRuntime; - if ((cmdRuntime != null) && + if ((this.Command.commandRuntime is MshCommandRuntime cmdRuntime) && (cmdRuntime.LogPipelineExecutionDetail || _isTranscribing) && (cmdRuntime.PipelineProcessor != null)) { @@ -851,8 +847,7 @@ private bool ShouldContinueUncoercedBind( return true; } - var psobj = parameterValue as PSObject; - if (psobj != null && !psobj.ImmediateBaseObjectIsEmpty) + if (parameterValue is PSObject psobj && !psobj.ImmediateBaseObjectIsEmpty) { // See if the base object is of the same type or // as subclass of the parameter @@ -2025,8 +2020,7 @@ internal void SetImplicitUsingParameters(object obj) if (_dictionary.ImplicitUsingParameters == null) { // Handle downlevel V4 case where using parameters are passed as an array list. - IList implicitArrayUsingParameters = PSObject.Base(obj) as IList; - if ((implicitArrayUsingParameters != null) && (implicitArrayUsingParameters.Count > 0)) + if ((PSObject.Base(obj) is IList implicitArrayUsingParameters) && (implicitArrayUsingParameters.Count > 0)) { // Convert array to hash table. _dictionary.ImplicitUsingParameters = new Hashtable(); diff --git a/src/System.Management.Automation/engine/ParameterBinderController.cs b/src/System.Management.Automation/engine/ParameterBinderController.cs index ed2b107b214..edb692aff7a 100644 --- a/src/System.Management.Automation/engine/ParameterBinderController.cs +++ b/src/System.Management.Automation/engine/ParameterBinderController.cs @@ -343,8 +343,7 @@ internal static void AddArgumentsToCommandProcessor(CommandProcessorBase command { if ((arguments != null) && (arguments.Length > 0)) { - PSBoundParametersDictionary boundParameters = arguments[0] as PSBoundParametersDictionary; - if ((boundParameters != null) && (arguments.Length == 1)) + if ((arguments[0] is PSBoundParametersDictionary boundParameters) && (arguments.Length == 1)) { // If they are supplying a dictionary of parameters, use those directly foreach (KeyValuePair boundParameter in boundParameters) diff --git a/src/System.Management.Automation/engine/Pipe.cs b/src/System.Management.Automation/engine/Pipe.cs index 98b55cf1105..33c9b73ccc7 100644 --- a/src/System.Management.Automation/engine/Pipe.cs +++ b/src/System.Management.Automation/engine/Pipe.cs @@ -509,8 +509,7 @@ internal void AddItems(object objects) { // If our object came from GetEnumerator (and hence is not IEnumerator), then we need to dispose // Otherwise, we don't own the object, so don't dispose. - var disposable = ie as IDisposable; - if (disposable != null && objects is not IEnumerator) + if (ie is IDisposable disposable && objects is not IEnumerator) { disposable.Dispose(); } diff --git a/src/System.Management.Automation/engine/ProxyCommand.cs b/src/System.Management.Automation/engine/ProxyCommand.cs index 5703adec664..f38eed58878 100644 --- a/src/System.Management.Automation/engine/ProxyCommand.cs +++ b/src/System.Management.Automation/engine/ProxyCommand.cs @@ -262,8 +262,7 @@ private static string GetObjText(object obj) { string text = null; - PSObject psobj = obj as PSObject; - if (psobj != null) + if (obj is PSObject psobj) { text = GetProperty(psobj, "Text"); } diff --git a/src/System.Management.Automation/engine/ScopedItemSearcher.cs b/src/System.Management.Automation/engine/ScopedItemSearcher.cs index fc67ee26374..e86fe686dff 100644 --- a/src/System.Management.Automation/engine/ScopedItemSearcher.cs +++ b/src/System.Management.Automation/engine/ScopedItemSearcher.cs @@ -397,8 +397,7 @@ protected override bool GetScopeItem( if (script != null) { bool isPrivate; - FilterInfo filterInfo = script as FilterInfo; - if (filterInfo != null) + if (script is FilterInfo filterInfo) { isPrivate = (filterInfo.Options & ScopedItemOptions.Private) != 0; } diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index 218fa6fd1c0..93c09b760e8 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -520,8 +520,7 @@ internal ProviderInvocationException NewProviderInvocationException( // ProviderBase.ThrowTerminatingError, it is already a // ProviderInvocationException, and we don't want to // re-wrap it. - ProviderInvocationException pie = e as ProviderInvocationException; - if (pie != null) + if (e is ProviderInvocationException pie) { pie._providerInfo = provider; return pie; diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index 6fbd3b340a8..fd1d276fd9d 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -1818,8 +1818,7 @@ private void ProcessPathItems( foreach (PSObject filteredChildName in filteredChildNameObjects) { - string filteredName = filteredChildName.BaseObject as string; - if (filteredName != null) + if (filteredChildName.BaseObject is string filteredName) { filteredChildNameDictionary[filteredName] = true; } diff --git a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs index 42d3607cadb..e71ee446629 100644 --- a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs @@ -773,8 +773,7 @@ internal void RemoveFunction(string name, PSModuleInfo module) { Dbg.Assert(module != null, "Caller should verify that module parameter is not null"); - FunctionInfo func = GetFunction(name) as FunctionInfo; - if (func != null && func.ScriptBlock != null + if (GetFunction(name) is FunctionInfo func && func.ScriptBlock != null && func.ScriptBlock.File != null && func.ScriptBlock.File.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/System.Management.Automation/engine/SessionStateNavigation.cs b/src/System.Management.Automation/engine/SessionStateNavigation.cs index 4afb9218dd7..0381fb5bc3c 100644 --- a/src/System.Management.Automation/engine/SessionStateNavigation.cs +++ b/src/System.Management.Automation/engine/SessionStateNavigation.cs @@ -696,8 +696,7 @@ internal string NormalizeRelativePath( Provider.CmdletProvider providerInstance = GetProviderInstance(provider); - NavigationCmdletProvider navigationCmdletProvider = providerInstance as NavigationCmdletProvider; - if (navigationCmdletProvider != null) + if (providerInstance is NavigationCmdletProvider navigationCmdletProvider) { try { @@ -971,9 +970,8 @@ internal string MakePath( string result = null; - NavigationCmdletProvider navigationCmdletProvider = providerInstance as NavigationCmdletProvider; - if (navigationCmdletProvider != null) + if (providerInstance is NavigationCmdletProvider navigationCmdletProvider) { try { diff --git a/src/System.Management.Automation/engine/SessionStatePublic.cs b/src/System.Management.Automation/engine/SessionStatePublic.cs index 35360dc0d45..5b4ff83a3e7 100644 --- a/src/System.Management.Automation/engine/SessionStatePublic.cs +++ b/src/System.Management.Automation/engine/SessionStatePublic.cs @@ -187,8 +187,7 @@ public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck) SessionStateException exception; if (!IsVisible(origin, valueToCheck)) { - PSVariable sv = valueToCheck as PSVariable; - if (sv != null) + if (valueToCheck is PSVariable sv) { exception = new SessionStateException( @@ -201,8 +200,7 @@ public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck) throw exception; } - CommandInfo cinfo = valueToCheck as CommandInfo; - if (cinfo != null) + if (valueToCheck is CommandInfo cinfo) { string commandName = cinfo.Name; if (commandName != null) @@ -253,8 +251,7 @@ public static bool IsVisible(CommandOrigin origin, object valueToCheck) { if (origin == CommandOrigin.Internal) return true; - IHasSessionStateEntryVisibility obj = valueToCheck as IHasSessionStateEntryVisibility; - if (obj != null) + if (valueToCheck is IHasSessionStateEntryVisibility obj) { return (obj.Visibility == SessionStateEntryVisibility.Public); } diff --git a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs index f63a0a87c0f..19f456378c3 100644 --- a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs @@ -881,9 +881,7 @@ internal object GetVariableValueAtScope(string name, string scopeID) if (resultItem != null) { - PSVariable variable = resultItem as PSVariable; - - if (variable != null) + if (resultItem is PSVariable variable) { resultItem = variable.Value; } diff --git a/src/System.Management.Automation/engine/ShellVariable.cs b/src/System.Management.Automation/engine/ShellVariable.cs index 4be5a96f52b..a591daa1c5a 100644 --- a/src/System.Management.Automation/engine/ShellVariable.cs +++ b/src/System.Management.Automation/engine/ShellVariable.cs @@ -442,8 +442,7 @@ internal static bool IsValidValue(object value, Attribute attribute) { bool result = true; - ValidateArgumentsAttribute validationAttribute = attribute as ValidateArgumentsAttribute; - if (validationAttribute != null) + if (attribute is ValidateArgumentsAttribute validationAttribute) { try { @@ -502,9 +501,7 @@ internal static object TransformValue(IEnumerable attributes, object foreach (Attribute attribute in attributes) { - ArgumentTransformationAttribute transformationAttribute = - attribute as ArgumentTransformationAttribute; - if (transformationAttribute != null) + if (attribute is ArgumentTransformationAttribute transformationAttribute) { result = transformationAttribute.TransformInternal(engine, result); } diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index 06799ff1a7d..fa3971ccf39 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -899,8 +899,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) { string result; - ValidateLengthAttribute validLengthAttrib = attrib as ValidateLengthAttribute; - if (validLengthAttrib != null) + if (attrib is ValidateLengthAttribute validLengthAttrib) { result = string.Format( CultureInfo.InvariantCulture, @@ -910,8 +909,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) return result; } - ValidateRangeAttribute validRangeAttrib = attrib as ValidateRangeAttribute; - if (validRangeAttrib != null) + if (attrib is ValidateRangeAttribute validRangeAttrib) { if (validRangeAttrib.RangeKind.HasValue) { @@ -946,32 +944,28 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } } - AllowNullAttribute allowNullAttrib = attrib as AllowNullAttribute; - if (allowNullAttrib != null) + if (attrib is AllowNullAttribute allowNullAttrib) { result = string.Format(CultureInfo.InvariantCulture, AllowNullFormat, prefix); return result; } - AllowEmptyStringAttribute allowEmptyStringAttrib = attrib as AllowEmptyStringAttribute; - if (allowEmptyStringAttrib != null) + if (attrib is AllowEmptyStringAttribute allowEmptyStringAttrib) { result = string.Format(CultureInfo.InvariantCulture, AllowEmptyStringFormat, prefix); return result; } - AllowEmptyCollectionAttribute allowEmptyColAttrib = attrib as AllowEmptyCollectionAttribute; - if (allowEmptyColAttrib != null) + if (attrib is AllowEmptyCollectionAttribute allowEmptyColAttrib) { result = string.Format(CultureInfo.InvariantCulture, AllowEmptyCollectionFormat, prefix); return result; } - ValidatePatternAttribute patternAttrib = attrib as ValidatePatternAttribute; - if (patternAttrib != null) + if (attrib is ValidatePatternAttribute patternAttrib) { /* TODO: Validate Pattern dont support Options in ScriptCmdletText. StringBuilder regexOps = new System.Text.StringBuilder(); @@ -1001,32 +995,28 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) return result; } - ValidateCountAttribute countAttrib = attrib as ValidateCountAttribute; - if (countAttrib != null) + if (attrib is ValidateCountAttribute countAttrib) { result = string.Format(CultureInfo.InvariantCulture, ValidateCountFormat, prefix, countAttrib.MinLength, countAttrib.MaxLength); return result; } - ValidateNotNullAttribute notNullAttrib = attrib as ValidateNotNullAttribute; - if (notNullAttrib != null) + if (attrib is ValidateNotNullAttribute notNullAttrib) { result = string.Format(CultureInfo.InvariantCulture, ValidateNotNullFormat, prefix); return result; } - ValidateNotNullOrEmptyAttribute notNullEmptyAttrib = attrib as ValidateNotNullOrEmptyAttribute; - if (notNullEmptyAttrib != null) + if (attrib is ValidateNotNullOrEmptyAttribute notNullEmptyAttrib) { result = string.Format(CultureInfo.InvariantCulture, ValidateNotNullOrEmptyFormat, prefix); return result; } - ValidateSetAttribute setAttrib = attrib as ValidateSetAttribute; - if (setAttrib != null) + if (attrib is ValidateSetAttribute setAttrib) { Text.StringBuilder values = new System.Text.StringBuilder(); string comma = string.Empty; @@ -1045,8 +1035,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) return result; } - ValidateScriptAttribute scriptAttrib = attrib as ValidateScriptAttribute; - if (scriptAttrib != null) + if (attrib is ValidateScriptAttribute scriptAttrib) { // Talked with others and I think it is okay to use *unescaped* value from sb.ToString() // 1. implicit remoting is not bringing validation scripts across @@ -1057,8 +1046,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) return result; } - PSTypeNameAttribute psTypeNameAttrib = attrib as PSTypeNameAttribute; - if (psTypeNameAttrib != null) + if (attrib is PSTypeNameAttribute psTypeNameAttrib) { result = string.Format( CultureInfo.InvariantCulture, @@ -1068,8 +1056,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) return result; } - ObsoleteAttribute obsoleteAttrib = attrib as ObsoleteAttribute; - if (obsoleteAttrib != null) + if (attrib is ObsoleteAttribute obsoleteAttrib) { string parameters = string.Empty; if (obsoleteAttrib.IsError) diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index 06389ddee42..6cd2623633c 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -256,8 +256,7 @@ private bool BoolConverter(object value, string name) private void CheckStandardNote(TypeMemberData member, TypeData typeData, Action setter, Func converter) { - var note = member as NotePropertyData; - if (note != null) + if (member is NotePropertyData note) { T value; if (note.Value.GetType() != typeof(T)) @@ -279,8 +278,7 @@ private void CheckStandardNote(TypeMemberData member, TypeData typeData, Acti private bool CheckStandardPropertySet(TypeMemberData member, TypeData typeData, Action setter) { - var propertySet = member as PropertySetData; - if (propertySet != null) + if (member is PropertySetData propertySet) { setter(typeData, propertySet); return true; @@ -485,8 +483,7 @@ private TypeData Read_Type() } else if (m.Name.Equals(TypeTable.StringSerializationSource, StringComparison.OrdinalIgnoreCase)) { - var aliasData = m as AliasPropertyData; - if (aliasData != null) + if (m is AliasPropertyData aliasData) { typeData.StringSerializationSource = aliasData.ReferencedMemberName; } @@ -2968,8 +2965,7 @@ private static bool GetCheckNote(ConcurrentBag errors, string typeName, object sourceValue = note.Value; if (noteType.GetTypeCode().Equals(TypeCode.Boolean)) { - string sourceValueAsString = sourceValue as string; - if (sourceValueAsString != null) + if (sourceValue is string sourceValueAsString) { if (sourceValueAsString.Length == 0) { @@ -3643,9 +3639,7 @@ private static void ProcessTypeAdapter( PSObject.AdapterSet adapterSet = null; if (CreateInstance(errors, typeName, adapterType, TypesXmlStrings.UnableToInstantiateTypeAdapter, out object instance)) { - PSPropertyAdapter psPropertyAdapter = instance as PSPropertyAdapter; - - if (psPropertyAdapter == null) + if (instance is not PSPropertyAdapter psPropertyAdapter) { AddError(errors, typeName, TypesXmlStrings.TypeIsNotTypeAdapter, adapterType.FullName); } @@ -4052,12 +4046,10 @@ private PSMemberInfoInternalCollection MemberFactory(string k, Con } // There was a currentMember with the same name as typeMember - PSMemberSet currentMemberAsMemberSet = currentMember as PSMemberSet; - PSMemberSet typeMemberAsMemberSet = typeMember as PSMemberSet; // if we are not in a memberset inherit members situation we just replace // the current member with the new more specific member - if (currentMemberAsMemberSet == null || typeMemberAsMemberSet == null || + if (currentMember is not PSMemberSet currentMemberAsMemberSet || typeMember is not PSMemberSet typeMemberAsMemberSet || !typeMemberAsMemberSet.InheritMembers) { retValue.Remove(typeMember.Name); @@ -4148,48 +4140,41 @@ internal PSObject.AdapterSet GetTypeAdapter(Type type) private TypeMemberData GetTypeMemberDataFromPSMemberInfo(PSMemberInfo member) { - var note = member as PSNoteProperty; - if (note != null) + if (member is PSNoteProperty note) { return new NotePropertyData(note.Name, note.Value); } - var alias = member as PSAliasProperty; - if (alias != null) + if (member is PSAliasProperty alias) { return new AliasPropertyData(alias.Name, alias.ReferencedMemberName); } - var scriptProperty = member as PSScriptProperty; - if (scriptProperty != null) + if (member is PSScriptProperty scriptProperty) { ScriptBlock getter = scriptProperty.IsGettable ? scriptProperty.GetterScript : null; ScriptBlock setter = scriptProperty.IsSettable ? scriptProperty.SetterScript : null; return new ScriptPropertyData(scriptProperty.Name, getter, setter); } - var codeProperty = member as PSCodeProperty; - if (codeProperty != null) + if (member is PSCodeProperty codeProperty) { MethodInfo getter = codeProperty.IsGettable ? codeProperty.GetterCodeReference : null; MethodInfo setter = codeProperty.IsSettable ? codeProperty.SetterCodeReference : null; return new CodePropertyData(codeProperty.Name, getter, setter); } - var scriptMethod = member as PSScriptMethod; - if (scriptMethod != null) + if (member is PSScriptMethod scriptMethod) { return new ScriptMethodData(scriptMethod.Name, scriptMethod.Script); } - var codeMethod = member as PSCodeMethod; - if (codeMethod != null) + if (member is PSCodeMethod codeMethod) { return new CodeMethodData(codeMethod.Name, codeMethod.CodeReference); } - var memberSet = member as PSMemberSet; - if (memberSet != null) + if (member is PSMemberSet memberSet) { if (memberSet.Name.Equals(PSStandardMembers, StringComparison.OrdinalIgnoreCase)) { @@ -4225,8 +4210,7 @@ private void LoadMembersToTypeData(PSMemberInfo member, TypeData typeData) return; } - var memberSet = member as PSMemberSet; - if (memberSet != null) + if (member is PSMemberSet memberSet) { if (memberSet.Name.Equals(PSStandardMembers, StringComparison.OrdinalIgnoreCase)) { @@ -4281,8 +4265,7 @@ private void LoadStandardMembersToTypeData(PSMemberSet memberSet, TypeData typeD } else if (memberName.Equals(StringSerializationSource, StringComparison.OrdinalIgnoreCase)) { - var aliasProperty = standardMember as PSAliasProperty; - if (aliasProperty != null) + if (standardMember is PSAliasProperty aliasProperty) { typeData.StringSerializationSource = aliasProperty.ReferencedMemberName; } diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 968e2c2aea6..875fd04181c 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1507,11 +1507,10 @@ internal static void QueueWorkItemWithImpersonation( private static void WorkItemCallback(object callBackArgs) { object[] args = callBackArgs as object[]; - WindowsIdentity identityToImpersonate = args[0] as WindowsIdentity; WaitCallback callback = args[1] as WaitCallback; object state = args[2]; - if (identityToImpersonate != null) + if (args[0] is WindowsIdentity identityToImpersonate) { WindowsIdentity.RunImpersonated( identityToImpersonate.AccessToken, diff --git a/src/System.Management.Automation/engine/VariableAttributeCollection.cs b/src/System.Management.Automation/engine/VariableAttributeCollection.cs index 65b52b3c235..fe0a93e344b 100644 --- a/src/System.Management.Automation/engine/VariableAttributeCollection.cs +++ b/src/System.Management.Automation/engine/VariableAttributeCollection.cs @@ -119,8 +119,7 @@ private object VerifyNewAttribute(Attribute item) object variableValue = _variable.Value; // Perform transformation before validating - ArgumentTransformationAttribute argumentTransformation = item as ArgumentTransformationAttribute; - if (argumentTransformation != null) + if (item is ArgumentTransformationAttribute argumentTransformation) { // Get an EngineIntrinsics instance using the context of the thread. diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 430608ee777..d1d135a7941 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -135,9 +135,7 @@ internal void SetParameterSetName(string parameterSetName) /// internal override void DoBeginProcessing() { - MshCommandRuntime mshRuntime = this.CommandRuntime as MshCommandRuntime; - - if (mshRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshRuntime) { if (mshRuntime.UseTransaction && (!this.Context.TransactionManager.HasTransaction)) @@ -678,8 +676,7 @@ public void WriteInformation(object messageData, string[] tags) { using (PSTransactionManager.GetEngineProtectionScope()) { - ICommandRuntime2 commandRuntime2 = commandRuntime as ICommandRuntime2; - if (commandRuntime2 != null) + if (commandRuntime is ICommandRuntime2 commandRuntime2) { string source = this.MyInvocation.PSCommandPath; if (string.IsNullOrEmpty(source)) @@ -736,8 +733,7 @@ public void WriteInformation(InformationRecord informationRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { - ICommandRuntime2 commandRuntime2 = commandRuntime as ICommandRuntime2; - if (commandRuntime2 != null) + if (commandRuntime is ICommandRuntime2 commandRuntime2) { commandRuntime2.WriteInformation(informationRecord); } @@ -1565,8 +1561,7 @@ public bool ShouldContinue( { if (commandRuntime != null) { - ICommandRuntime2 runtime2 = commandRuntime as ICommandRuntime2; - if (runtime2 != null) + if (commandRuntime is ICommandRuntime2 runtime2) { return runtime2.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); } diff --git a/src/System.Management.Automation/engine/debugger/Breakpoint.cs b/src/System.Management.Automation/engine/debugger/Breakpoint.cs index b506ee8a246..9168805c1a6 100644 --- a/src/System.Management.Automation/engine/debugger/Breakpoint.cs +++ b/src/System.Management.Automation/engine/debugger/Breakpoint.cs @@ -226,8 +226,7 @@ private bool CommandInfoMatches(CommandInfo commandInfo) return true; } - var externalScript = commandInfo as ExternalScriptInfo; - if (externalScript != null) + if (commandInfo is ExternalScriptInfo externalScript) { if (externalScript.Path.Equals(Command, StringComparison.OrdinalIgnoreCase)) return true; diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index a32276bcc79..3e348702d52 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -1147,8 +1147,7 @@ internal void EnterScriptFunction(FunctionContext functionContext) if (_context._debuggingMode > 0) { - var scriptCommandInfo = invocationInfo.MyCommand as ExternalScriptInfo; - if (scriptCommandInfo != null) + if (invocationInfo.MyCommand is ExternalScriptInfo scriptCommandInfo) { RegisterScriptFile(scriptCommandInfo); } @@ -1263,22 +1262,19 @@ private LineBreakpoint AddLineBreakpoint(LineBreakpoint breakpoint) private void AddNewBreakpoint(Breakpoint breakpoint) { - LineBreakpoint lineBreakpoint = breakpoint as LineBreakpoint; - if (lineBreakpoint != null) + if (breakpoint is LineBreakpoint lineBreakpoint) { AddLineBreakpoint(lineBreakpoint); return; } - CommandBreakpoint cmdBreakpoint = breakpoint as CommandBreakpoint; - if (cmdBreakpoint != null) + if (breakpoint is CommandBreakpoint cmdBreakpoint) { AddCommandBreakpoint(cmdBreakpoint); return; } - VariableBreakpoint varBreakpoint = breakpoint as VariableBreakpoint; - if (varBreakpoint != null) + if (breakpoint is VariableBreakpoint varBreakpoint) { AddVariableBreakpoint(varBreakpoint); } @@ -2352,8 +2348,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC { if (item == null) { continue; } - DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand; - if (dbgCmd != null) + if (item.BaseObject is DebuggerCommand dbgCmd) { bool executedByDebugger = (dbgCmd.ResumeAction != null || dbgCmd.ExecutedByDebugger); results = new DebuggerCommandResults(dbgCmd.ResumeAction, executedByDebugger); @@ -2930,8 +2925,7 @@ internal override void DebugJob(Job job, bool breakAll) private bool TryAddDebugJob(Job job, bool breakAll) { - IJobDebugger debuggableJob = job as IJobDebugger; - if ((debuggableJob != null) && (debuggableJob.Debugger != null) && + if ((job is IJobDebugger debuggableJob) && (debuggableJob.Debugger != null) && ((job.JobStateInfo.State == JobState.Running) || (job.JobStateInfo.State == JobState.AtBreakpoint))) { // Check to see if job is already stopped in debugger. @@ -2946,8 +2940,7 @@ private bool TryAddDebugJob(Job job, bool breakAll) // Raise debug stop event if job is already in stopped state. if (jobDebugAlreadyStopped) { - RemotingJobDebugger remoteJobDebugger = debuggableJob.Debugger as RemotingJobDebugger; - if (remoteJobDebugger != null) + if (debuggableJob.Debugger is RemotingJobDebugger remoteJobDebugger) { remoteJobDebugger.CheckStateAndRaiseStopEvent(); } @@ -3107,8 +3100,7 @@ public override void CancelDebuggerProcessing() private void ReleaseInternalRunspaceDebugProcessing(object sender, bool emptyQueue = false) { - Runspace runspace = sender as Runspace; - if (runspace != null) + if (sender is Runspace runspace) { runspace.StateChanged -= RunspaceStateChangedHandler; runspace.AvailabilityChanged -= RunspaceAvailabilityChangedHandler; @@ -4525,8 +4517,7 @@ internal bool IsSameDebugger(Debugger testDebugger) /// internal void CheckStateAndRaiseStopEvent() { - RemoteDebugger remoteDebugger = _wrappedDebugger as RemoteDebugger; - if (remoteDebugger != null) + if (_wrappedDebugger is RemoteDebugger remoteDebugger) { // Have remote debugger raise existing debugger stop event. remoteDebugger.CheckStateAndRaiseStopEvent(); @@ -4540,8 +4531,7 @@ internal void CheckStateAndRaiseStopEvent() { // If this is a remote server debugger then we want to convert the pending remote // debugger stop to a local debugger stop event for this Debug-Runspace to handle. - ServerRemoteDebugger serverRemoteDebugger = this._wrappedDebugger as ServerRemoteDebugger; - if (serverRemoteDebugger != null) + if (this._wrappedDebugger is ServerRemoteDebugger serverRemoteDebugger) { serverRemoteDebugger.ReleaseAndRaiseDebugStopLocal(); } @@ -4651,8 +4641,7 @@ private void RestoreRemoteOutput(object runningCmd) { if (runningCmd == null) { return; } - var runningPowerShell = runningCmd as PowerShell; - if (runningPowerShell != null) + if (runningCmd is PowerShell runningPowerShell) { runningPowerShell.ResumeIncomingData(); } @@ -4860,15 +4849,13 @@ private InvocationInfo CreateInvocationInfoFromParent( int callingLineNumber = parentStackFrame.ScriptLineNumber; StatementAst debugStatement = null; - StatementAst callingStatement = _parentScriptBlockAst.Find( - ast => ast is StatementAst && (ast.Extent.StartLineNumber == callingLineNumber), true) as StatementAst; - if (callingStatement != null) + if (_parentScriptBlockAst.Find(ast => ast is StatementAst && (ast.Extent.StartLineNumber == callingLineNumber), true) + is StatementAst callingStatement) { // Find first statement in calling statement. - StatementAst firstStatement = callingStatement.Find( - ast => ast is StatementAst && ast.Extent.StartLineNumber > callingLineNumber, true) as StatementAst; - if (firstStatement != null) + if (callingStatement.Find(ast => ast is StatementAst && ast.Extent.StartLineNumber > callingLineNumber, true) + is StatementAst firstStatement) { int adjustedLineNumber = firstStatement.Extent.StartLineNumber + debugLineNumber - 1; debugStatement = callingStatement.Find( @@ -4948,15 +4935,13 @@ private void RestoreRemoteOutput(object runningCmd) { if (runningCmd == null) { return; } - PowerShell command = runningCmd as PowerShell; - if (command != null) + if (runningCmd is PowerShell command) { command.ResumeIncomingData(); } else { - Pipeline pipelineCommand = runningCmd as Pipeline; - if (pipelineCommand != null) + if (runningCmd is Pipeline pipelineCommand) { pipelineCommand.ResumeIncomingData(); } diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 29e86c91b9b..b2f2f162bcd 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -565,12 +565,10 @@ public static bool CanUseDefaultRunspace get { - RunspaceBase runspace = Runspace.DefaultRunspace as RunspaceBase; - if (runspace != null) + if (Runspace.DefaultRunspace is RunspaceBase runspace) { Pipeline currentPipeline = runspace.GetCurrentlyRunningPipeline(); - LocalPipeline localPipeline = currentPipeline as LocalPipeline; - if ((localPipeline != null) && (localPipeline.NestedPipelineExecutionThread != null)) + if ((currentPipeline is LocalPipeline localPipeline) && (localPipeline.NestedPipelineExecutionThread != null)) { return (localPipeline.NestedPipelineExecutionThread.ManagedThreadId @@ -972,8 +970,7 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise } Pipeline currentPipeline = this.GetCurrentlyRunningPipeline(); - RemotePipeline remotePipeline = currentPipeline as RemotePipeline; - Guid? pipeLineCmdInstance = (remotePipeline != null && remotePipeline.PowerShell != null) ? remotePipeline.PowerShell.InstanceId : (Guid?)null; + Guid? pipeLineCmdInstance = (currentPipeline is RemotePipeline remotePipeline && remotePipeline.PowerShell != null) ? remotePipeline.PowerShell.InstanceId : (Guid?)null; if (currentPipeline == null) { // A runspace is available: @@ -1116,15 +1113,13 @@ internal void UpdateRunspaceAvailability(PSInvocationState invocationState, bool protected void UpdateRunspaceAvailability(RunspaceState runspaceState, bool raiseEvent) { RunspaceAvailability oldAvailability = this.RunspaceAvailability; - RemoteRunspace remoteRunspace = this as RemoteRunspace; Internal.ConnectCommandInfo remoteCommand = null; bool remoteDebug = false; - if (remoteRunspace != null) + if (this is RemoteRunspace remoteRunspace) { remoteCommand = remoteRunspace.RemoteCommand; - RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger; - remoteDebug = (remoteDebugger != null) && remoteDebugger.IsRemoteDebug; + remoteDebug = (remoteRunspace.Debugger is RemoteDebugger remoteDebugger) && remoteDebugger.IsRemoteDebug; } switch (oldAvailability) diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs index 25989f6d4cf..55571124864 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs @@ -971,8 +971,7 @@ internal bool CanRunActionInCurrentPipeline() { // If we have no running pipeline, or if the currently running pipeline is // the same as the current thread, then execute the action. - var pipelineRunning = _currentlyRunningPipeline as PipelineBase; - return pipelineRunning == null || + return _currentlyRunningPipeline is not PipelineBase pipelineRunning || Thread.CurrentThread == pipelineRunning.NestedPipelineExecutionThread; } } diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index b3e29423a83..5c3db8392ba 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -411,8 +411,7 @@ internal static List GetSuggestion(HistoryInfo lastHistory, object lastE { object result = null; - ScriptBlock evaluator = suggestion["Rule"] as ScriptBlock; - if (evaluator == null) + if (suggestion["Rule"] is not ScriptBlock evaluator) { suggestion["Enabled"] = false; @@ -463,8 +462,7 @@ internal static List GetSuggestion(HistoryInfo lastHistory, object lastE { if (lastError != null) { - Exception lastException = lastError as Exception; - if (lastException != null) + if (lastError is Exception lastException) { matchText = lastException.Message; } @@ -689,10 +687,9 @@ runspace.ConnectionInfo is VMConnectionInfo || return basePrompt; } - SSHConnectionInfo sshConnectionInfo = runspace.ConnectionInfo as SSHConnectionInfo; // Usernames are case-sensitive on Unix systems - if (sshConnectionInfo != null && + if (runspace.ConnectionInfo is SSHConnectionInfo sshConnectionInfo && !string.IsNullOrEmpty(sshConnectionInfo.UserName) && !System.Environment.UserName.Equals(sshConnectionInfo.UserName, StringComparison.Ordinal)) { diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index 79aca5b48ba..b973b7a1618 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -419,9 +419,7 @@ public void EmitPop() internal void SwitchToBoxed(int index, int instructionIndex) { - var instruction = _instructions[instructionIndex] as IBoxableInstruction; - - if (instruction != null) + if (_instructions[instructionIndex] is IBoxableInstruction instruction) { var newInstruction = instruction.BoxIfIndexMatches(index); if (newInstruction != null) diff --git a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs index f58aa35632e..6d964bec6d9 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs @@ -624,8 +624,7 @@ private void StateCallBackHandler(object sender, RunspaceStateEventArgs eArgs) bool writeError = true; if (_queryRunspaces == null) { - PSRemotingTransportException transportException = eArgs.RunspaceStateInfo.Reason as PSRemotingTransportException; - if (transportException != null && + if (eArgs.RunspaceStateInfo.Reason is PSRemotingTransportException transportException && transportException.ErrorCode == WSManNativeApi.ERROR_WSMAN_INUSE_CANNOT_RECONNECT) { lock (s_LockObject) @@ -707,8 +706,7 @@ private void WriteConnectFailed( if (e != null && !string.IsNullOrEmpty(e.Message)) { // Update fully qualified error Id if we have a transport error. - PSRemotingTransportException transportException = e as PSRemotingTransportException; - if (transportException != null) + if (e is PSRemotingTransportException transportException) { FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(transportException.ErrorCode, FQEID); } diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 503e183d63b..804a289f205 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -459,9 +459,8 @@ protected override void BeginProcessing() RemotingCommandUtil.CheckRemotingCmdletPrerequisites(); PSSessionConfigurationCommandUtilities.ThrowIfNotAdministrator(); - WSManConfigurationOption wsmanOption = transportOption as WSManConfigurationOption; - if (wsmanOption != null) + if (transportOption is WSManConfigurationOption wsmanOption) { if (wsmanOption.ProcessIdleTimeoutSec != null && !isUseSharedProcessSpecified) { @@ -1331,8 +1330,7 @@ internal static void CollectShouldProcessParameters(PSCmdlet cmdlet, out bool wh whatIf = false; // confirm is always true to start with confirm = false; - MshCommandRuntime cmdRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (cmdRuntime != null) + if (cmdlet.CommandRuntime is MshCommandRuntime cmdRuntime) { whatIf = cmdRuntime.WhatIf; // take the value of confirm only if it is explicitly set by the user @@ -1413,16 +1411,14 @@ internal static string GetModulePathAsString(object[] modulePath) StringBuilder sb = new StringBuilder(); foreach (object s in modulePath) { - var module = s as string; - if (module != null) + if (s is string module) { sb.Append(s); sb.Append(','); } else { - var moduleSpec = s as ModuleSpecification; - if (moduleSpec != null) + if (s is ModuleSpecification moduleSpec) { // Double escaping on ModuleSpecification string is required to treat it as a single value along with module names/paths in SessionConfigurationData sb.Append(SecurityElement.Escape(SecurityElement.Escape(moduleSpec.ToString()))); @@ -1815,8 +1811,7 @@ private static void ParseKeyValue( // Mixed // @{ Or = 'Group1', @{ And = 'Group2','Group3' } } // (Member_of {SID(Group1)} || (Member_of {SID(Group2)} && Member_of {SID(Group3)})) - object[] values = keyValue as object[]; - if (values != null) + if (keyValue is object[] values) { int count = values.Length; for (int i = 0; i < count;) @@ -1843,8 +1838,7 @@ private static void ParseValues( object inValue) { // Value to parse can be a single object or an array of objects - object[] values = inValue as object[]; - if (values != null) + if (inValue is object[] values) { foreach (object value in values) { @@ -1862,8 +1856,7 @@ private static void ParseValue( object value) { // Single value objects can be either a group name or a new logical hash table - string groupName = value as string; - if (groupName != null) + if (value is string groupName) { // Resolve group name to SID NTAccount ntAccount = new NTAccount(groupName); @@ -1872,8 +1865,7 @@ private static void ParseValue( } else { - Hashtable recurseCondition = value as Hashtable; - if (recurseCondition != null) + if (value is Hashtable recurseCondition) { // Recurse to handle logical hash table AddCondition(sb, recurseCondition); @@ -2355,9 +2347,7 @@ public object[] ModulesToImport { foreach (var s in value) { - var hashtable = s as Hashtable; - - if (hashtable != null) + if (s is Hashtable hashtable) { var moduleSpec = new ModuleSpecification(hashtable); if (moduleSpec != null) @@ -3395,8 +3385,7 @@ protected override void ProcessRecord() using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { ps.AddScript(string.Format(CultureInfo.InvariantCulture, getSessionTypeFormat, CodeGeneration.EscapeSingleQuotedStringContent(Name))); - Collection psObjectCollection = ps.Invoke(new object[] { Name }) as Collection; - if (psObjectCollection == null || psObjectCollection.Count != 1) + if (ps.Invoke(new object[] { Name }) is not Collection psObjectCollection || psObjectCollection.Count != 1) { Dbg.Assert(false, "This should never happen. ps.Invoke always return a Collection"); } diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index 5e4f3b8c129..a5ab0693c9c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -369,9 +369,7 @@ private string GetLocalhostWithNetworkAccessEnabled(Dictionary foreach (PSSession psSession in psSessions.Values) { - WSManConnectionInfo wsManConnectionInfo = psSession.Runspace.ConnectionInfo as WSManConnectionInfo; - - if ((wsManConnectionInfo != null) && (wsManConnectionInfo.IsLocalhostAndNetworkAccess)) + if ((psSession.Runspace.ConnectionInfo is WSManConnectionInfo wsManConnectionInfo) && (wsManConnectionInfo.IsLocalhostAndNetworkAccess)) { sb.Append(psSession.Name + ", "); } diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index faf8bfdaa00..9f959541269 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -456,8 +456,7 @@ private void QueryForAndConnectCommands(string name, Guid instanceId) if (shellUri != null) { // Compare with returned shell Uri in connection info. - WSManConnectionInfo wsmanConnectionInfo = runspace.ConnectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null && + if (runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo && !shellUri.Equals(wsmanConnectionInfo.ShellUri, StringComparison.OrdinalIgnoreCase)) { continue; @@ -1193,9 +1192,8 @@ private PSSession TryGetSessionFromServer(PSSession session) private PSRemotingJob FindJobForSession(PSSession session) { PSRemotingJob job = null; - RemoteRunspace remoteSessionRunspace = session.Runspace as RemoteRunspace; - if (remoteSessionRunspace == null || + if (session.Runspace is not RemoteRunspace remoteSessionRunspace || remoteSessionRunspace.RemoteCommand != null) { // The provided session is created for *reconstruction* and we diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index d39733bed49..4904c1dd10f 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -252,8 +252,7 @@ private static FileSystemInfo GetFileSystemInfo(string path, out bool isContaine internal override bool IsFilterSet() { bool attributeFilterSet = false; - GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters; - if (fspDynamicParam != null) + if (DynamicParameters is GetChildDynamicParameters fspDynamicParam) { attributeFilterSet = ( (fspDynamicParam.Attributes != null) @@ -1387,8 +1386,7 @@ private FileSystemInfo GetFileSystemItem(string path, ref bool isContainer, bool FlagsExpression evaluator = null; FlagsExpression switchEvaluator = null; - GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters; - if (fspDynamicParam != null) + if (DynamicParameters is GetChildDynamicParameters fspDynamicParam) { evaluator = fspDynamicParam.Attributes; switchEvaluator = FormatAttributeSwitchParameters(); @@ -1650,8 +1648,7 @@ private void GetPathItems( if (recurse) { - GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters; - if (fspDynamicParam != null && fspDynamicParam.FollowSymlink) + if (DynamicParameters is GetChildDynamicParameters fspDynamicParam && fspDynamicParam.FollowSymlink) { tracker = new InodeTracker(fsinfo.FullName); } @@ -1664,8 +1661,7 @@ private void GetPathItems( { FlagsExpression evaluator = null; FlagsExpression switchEvaluator = null; - GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters; - if (fspDynamicParam != null) + if (DynamicParameters is GetChildDynamicParameters fspDynamicParam) { evaluator = fspDynamicParam.Attributes; switchEvaluator = FormatAttributeSwitchParameters(); @@ -1775,8 +1771,7 @@ private void Dir( FlagsExpression evaluator = null; FlagsExpression switchEvaluator = null; - GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters; - if (fspDynamicParam != null) + if (DynamicParameters is GetChildDynamicParameters fspDynamicParam) { evaluator = fspDynamicParam.Attributes; switchEvaluator = FormatAttributeSwitchParameters(); @@ -3416,11 +3411,9 @@ private bool ItemExists(string path, out ErrorRecord error) var fsinfo = GetFileSystemInfo(path, out bool _); result = fsinfo != null; - FileSystemItemProviderDynamicParameters itemExistsDynamicParameters = - DynamicParameters as FileSystemItemProviderDynamicParameters; // If the items see if we need to check the age of the file... - if (result && itemExistsDynamicParameters != null) + if (result && DynamicParameters is FileSystemItemProviderDynamicParameters itemExistsDynamicParameters) { DateTime lastWriteTime = fsinfo.LastWriteTime; @@ -3621,9 +3614,8 @@ protected override void CopyItem( PSSession fromSession = null; PSSession toSession = null; - CopyItemDynamicParameters copyDynamicParameter = DynamicParameters as CopyItemDynamicParameters; - if (copyDynamicParameter != null) + if (DynamicParameters is CopyItemDynamicParameters copyDynamicParameter) { if (copyDynamicParameter.FromSession != null) { @@ -6608,10 +6600,7 @@ public IContentReader GetContentReader(string path) // They override the defaults specified above. if (DynamicParameters != null) { - FileSystemContentReaderDynamicParameters dynParams = - DynamicParameters as FileSystemContentReaderDynamicParameters; - - if (dynParams != null) + if (DynamicParameters is FileSystemContentReaderDynamicParameters dynParams) { // -raw is not allowed when -first,-last or -wait is specified // this call will validate that and throws. @@ -6778,10 +6767,7 @@ public IContentWriter GetContentWriter(string path) // Get the dynamic parameters if (DynamicParameters != null) { - FileSystemContentWriterDynamicParameters dynParams = - DynamicParameters as FileSystemContentWriterDynamicParameters; - - if (dynParams != null) + if (DynamicParameters is FileSystemContentWriterDynamicParameters dynParams) { usingByteEncoding = dynParams.AsByteStream; streamTypeSpecified = dynParams.WasStreamTypeSpecified; @@ -8086,9 +8072,7 @@ public static string GetTarget(PSObject instance) /// The link type of the reparse point. SymbolicLink for symbolic links. public static string GetLinkType(PSObject instance) { - FileSystemInfo fileSysInfo = instance.BaseObject as FileSystemInfo; - - if (fileSysInfo != null) + if (instance.BaseObject is FileSystemInfo fileSysInfo) { return InternalGetLinkType(fileSysInfo); }