diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs
index afadd0a3fe4..6f321d9bb00 100644
--- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs
+++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs
@@ -388,8 +388,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re
if (cimReference != null)
{
object baseObject = GetBaseObject(cimReference.Value);
- CimInstance cimInstance = baseObject as CimInstance;
- if (cimInstance == null)
+ if (!(baseObject is CimInstance cimInstance))
{
return null;
}
@@ -412,8 +411,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re
CimInstance[] cimInstanceArray = new CimInstance[cimReferenceArray.Length];
for (int i = 0; i < cimReferenceArray.Length; i++)
{
- PSReference tempCimReference = cimReferenceArray[i] as PSReference;
- if (tempCimReference == null)
+ if (!(cimReferenceArray[i] is PSReference tempCimReference))
{
return null;
}
diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs
index 56e90ad6f8b..3cf93601109 100644
--- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs
+++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs
@@ -2085,8 +2085,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args)
}
CimWriteResultObject writeResultObject = args.Action as CimWriteResultObject;
- CimClass cimClass = writeResultObject.Result as CimClass;
- if (cimClass == null)
+ if (!(writeResultObject.Result is CimClass cimClass))
{
return true;
}
@@ -2239,8 +2238,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args)
}
CimWriteResultObject writeResultObject = args.Action as CimWriteResultObject;
- CimInstance cimInstance = writeResultObject.Result as CimInstance;
- if (cimInstance == null)
+ if (!(writeResultObject.Result is CimInstance cimInstance))
{
return true;
}
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 f23c74c142c..3e885cf60ce 100644
--- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs
+++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs
@@ -84,8 +84,7 @@ private enum WsManErrorCode : uint
private static bool IsWsManQuotaReached(Exception exception)
{
- var cimException = exception as CimException;
- if (cimException == null)
+ if (!(exception is CimException cimException))
{
return false;
}
@@ -1010,8 +1009,7 @@ private CimResponseType PromptUserCallback(string message, CimPromptType promptT
internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance)
{
PSObject pso = PSObject.AsPSObject(cimInstance);
- PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo;
- if (psShowComputerNameProperty == null)
+ if (!(pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] is PSPropertyInfo psShowComputerNameProperty))
{
return false;
}
diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs
index a667e6da2f5..7bddc46b312 100644
--- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs
+++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs
@@ -172,8 +172,7 @@ private CimJobContext CreateJobContext(CimSession session, object targetObject)
/// object that performs a query against the wrapped object model.
internal override StartableJob CreateQueryJob(CimSession session, QueryBuilder baseQuery)
{
- CimQuery query = baseQuery as CimQuery;
- if (query == null)
+ if (!(baseQuery is CimQuery query))
{
throw new ArgumentNullException(nameof(baseQuery));
}
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 dc94df195e2..4159cc07685 100644
--- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs
+++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs
@@ -572,8 +572,7 @@ private static bool ActualValueGreaterThanOrEqualToExpectedValue(string property
{
try
{
- var expectedComparable = expectedPropertyValue as IComparable;
- if (expectedComparable == null)
+ if (!(expectedPropertyValue is IComparable expectedComparable))
{
return false;
}
@@ -608,8 +607,7 @@ private static bool ActualValueLessThanOrEqualToExpectedValue(string propertyNam
{
try
{
- var actualComparable = actualPropertyValue as IComparable;
- if (actualComparable == null)
+ if (!(actualPropertyValue is IComparable actualComparable))
{
return false;
}
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs
index 2c85a64cf18..75340d7f117 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs
@@ -710,8 +710,7 @@ private void WriteMemberInfoCollection(
continue;
}
- PSPropertyInfo property = info as PSPropertyInfo;
- if (property == null)
+ if (!(info is PSPropertyInfo property))
{
continue;
}
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs
index 0d2db93302a..a42462737ea 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs
@@ -48,8 +48,7 @@ internal Type GetValueType(PSObject liveObject, out object columnValue)
/// The source string limited in the number of lines.
internal static object LimitString(object src)
{
- string srcString = src as string;
- if (srcString == null)
+ if (!(src is string srcString))
{
return src;
}
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs
index 4f8903facfd..b2680912dfc 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs
@@ -120,9 +120,7 @@ protected override void ProcessRecord()
Command,
delegate (Breakpoint breakpoint, string command)
{
- CommandBreakpoint commandBreakpoint = breakpoint as CommandBreakpoint;
-
- if (commandBreakpoint == null)
+ if (!(breakpoint is CommandBreakpoint commandBreakpoint))
{
return false;
}
@@ -137,9 +135,7 @@ protected override void ProcessRecord()
Variable,
delegate (Breakpoint breakpoint, string variable)
{
- VariableBreakpoint variableBreakpoint = breakpoint as VariableBreakpoint;
-
- if (variableBreakpoint == null)
+ if (!(breakpoint is VariableBreakpoint variableBreakpoint))
{
return false;
}
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs
index b7266fa1114..4ae17fd1881 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs
@@ -2623,8 +2623,7 @@ private string GenerateConnectionStringForNewRunspace()
private string GenerateAllowRedirectionParameter()
{
- WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo;
- if (wsmanConnectionInfo == null)
+ if (!(_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo))
{
return string.Empty;
}
@@ -2650,8 +2649,7 @@ private string GenerateAuthenticationMechanismParameter()
return string.Empty;
}
- WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo;
- if (wsmanConnectionInfo == null)
+ if (!(_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo))
{
return string.Empty;
}
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs
index fd69a2011fb..e95c6f239c7 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs
@@ -77,8 +77,7 @@ internal CultureInfo Culture
/// True if both the objects are same or else returns false.
public override bool Equals(object inputObject)
{
- ObjectCommandPropertyValue objectCommandPropertyValueObject = inputObject as ObjectCommandPropertyValue;
- if (objectCommandPropertyValueObject == null)
+ if (!(inputObject is ObjectCommandPropertyValue objectCommandPropertyValueObject))
{
return false;
}
diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs
index c2ebc9261a1..6688ae1f8bb 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs
@@ -358,9 +358,7 @@ internal static string[] GetDefaultKeyPropertySet(PSObject mshObj)
return null;
}
- PSPropertySet defaultKeys = standardNames.Members["DefaultKeyPropertySet"] as PSPropertySet;
-
- if (defaultKeys == null)
+ if (!(standardNames.Members["DefaultKeyPropertySet"] is PSPropertySet defaultKeys))
{
return null;
}
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 2b9bce8fd82..5b19635c45a 100644
--- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs
+++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs
@@ -633,9 +633,7 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso
///
private static object AddPsProperties(object psObj, object obj, int depth, bool isPurePSObj, bool isCustomObj, in ConvertToJsonContext context)
{
- PSObject pso = psObj as PSObject;
-
- if (pso == null)
+ if (!(psObj is PSObject pso))
{
return obj;
}
diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs
index 37dd52d7ebe..7fa42b31424 100644
--- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs
+++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs
@@ -208,8 +208,7 @@ public static string GetOwner(PSObject instance)
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
- ObjectSecurity sd = instance.BaseObject as ObjectSecurity;
- if (sd == null)
+ if (!(instance.BaseObject is ObjectSecurity sd))
{
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
@@ -248,8 +247,7 @@ public static string GetGroup(PSObject instance)
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
- ObjectSecurity sd = instance.BaseObject as ObjectSecurity;
- if (sd == null)
+ if (!(instance.BaseObject is ObjectSecurity sd))
{
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
@@ -588,8 +586,7 @@ public static string GetSddl(PSObject instance)
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
- ObjectSecurity sd = instance.BaseObject as ObjectSecurity;
- if (sd == null)
+ if (!(instance.BaseObject is ObjectSecurity sd))
{
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs
index ec0c40736fb..86c5dbf4e3f 100644
--- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs
+++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs
@@ -602,9 +602,7 @@ internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo a
else
{
// check if we have a type group reference
- TypeGroupReference tgr = r as TypeGroupReference;
-
- if (tgr == null)
+ if (!(r is TypeGroupReference tgr))
continue;
// find the type group definition the reference points to
diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs
index 8609d35c9a9..b9a7968a645 100644
--- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs
+++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs
@@ -55,9 +55,7 @@ fid is GroupEndData ||
return false;
}
- string classId = GetProperty(so, FormatInfoData.classidProperty) as string;
-
- if (classId == null)
+ if (!(GetProperty(so, FormatInfoData.classidProperty) is string classId))
{
// it's not one of the objects derived from FormatInfoData
return false;
@@ -113,9 +111,7 @@ fid is GroupEndData ||
return so;
}
- string classId = GetProperty(so, FormatInfoData.classidProperty) as string;
-
- if (classId == null)
+ if (!(GetProperty(so, FormatInfoData.classidProperty) is string classId))
{
// it's not one of the objects derived from FormatInfoData,
// just return it as is
diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs
index 3a7e29a4c14..81ccb73133b 100644
--- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs
+++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs
@@ -285,8 +285,7 @@ private List GetInheritanceChain(CimInstance cimInstance)
///
public override Collection GetTypeNameHierarchy(object baseObject)
{
- var cimInstance = baseObject as CimInstance;
- if (cimInstance == null)
+ if (!(baseObject is CimInstance cimInstance))
{
throw new ArgumentNullException(nameof(baseObject));
}
@@ -362,8 +361,7 @@ public override bool IsSettable(PSAdaptedProperty adaptedProperty)
return false;
}
- CimProperty cimProperty = adaptedProperty.Tag as CimProperty;
- if (cimProperty == null)
+ if (!(adaptedProperty.Tag is CimProperty cimProperty))
{
return false;
}
diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs
index e9b6be3caff..ab06bbd6f35 100644
--- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs
+++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs
@@ -67,9 +67,7 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b
else
temp = result;
- PSReference reference = temp as PSReference;
-
- if (reference == null)
+ if (!(temp is PSReference reference))
{
throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null,
ExtendedTypeSystem.ReferenceTypeExpected);
diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs
index 16445703030..9709e6ee26e 100644
--- a/src/System.Management.Automation/engine/Attributes.cs
+++ b/src/System.Management.Automation/engine/Attributes.cs
@@ -839,8 +839,7 @@ public sealed class ValidateLengthAttribute : ValidateEnumeratedArgumentsAttribu
/// For invalid arguments.
protected override void ValidateElement(object element)
{
- string objectString = element as string;
- if (objectString == null)
+ if (!(element is string objectString))
{
throw new ValidationMetadataException(
"ValidateLengthNotString",
@@ -1857,8 +1856,7 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin
Metadata.ValidateNotNullFailure);
}
- var path = arguments as string;
- if (path == null)
+ if (!(arguments is string path))
{
throw new ValidationMetadataException(
"PathArgumentIsNotValid",
diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs
index eeccc290883..80503d31794 100644
--- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs
+++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs
@@ -626,8 +626,7 @@ private Dictionary GetDefaultParameterVa
foreach (DictionaryEntry entry in DefaultParameterValues)
{
- string key = entry.Key as string;
- if (key == null)
+ if (!(entry.Key is string key))
{
continue;
}
@@ -4389,8 +4388,7 @@ public override bool ContainsKey(object key)
throw PSTraceSource.NewArgumentNullException(nameof(key));
}
- var strKey = key as string;
- if (strKey == null) { return false; }
+ if (!(key is string strKey)) { return false; }
string keyAfterTrim = strKey.Trim();
return base.ContainsKey(keyAfterTrim);
@@ -4416,8 +4414,7 @@ private void AddImpl(object key, object value, bool isSelfIndexing)
throw PSTraceSource.NewArgumentNullException(nameof(key));
}
- var strKey = key as string;
- if (strKey == null)
+ if (!(key is string strKey))
{
throw PSTraceSource.NewArgumentException(nameof(key), ParameterBinderStrings.StringValueKeyExpected, key, key.GetType().FullName);
}
@@ -4462,8 +4459,7 @@ public override object this[object key]
{
if (key == null) { throw PSTraceSource.NewArgumentNullException(nameof(key)); }
- var strKey = key as string;
- if (strKey == null) { return null; }
+ if (!(key is string strKey)) { return null; }
string keyAfterTrim = strKey.Trim();
return base[keyAfterTrim];
@@ -4486,8 +4482,7 @@ public override void Remove(object key)
throw PSTraceSource.NewArgumentNullException(nameof(key));
}
- var strKey = key as string;
- if (strKey == null) { return; }
+ if (!(key is string strKey)) { return; }
string keyAfterTrim = strKey.Trim();
if (base.ContainsKey(keyAfterTrim))
diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs
index db32f5de184..a36e5196f65 100644
--- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs
+++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs
@@ -239,8 +239,7 @@ private static bool CompleteAgainstSwitchFile(Ast lastAst, Token tokenBeforeCurs
if (lastAst.Parent is CommandExpressionAst)
{
// Handle "switch -file m" or "switch -file *.ps1"
- var pipeline = lastAst.Parent.Parent as PipelineAst;
- if (pipeline == null)
+ if (!(lastAst.Parent.Parent is PipelineAst pipeline))
{
return false;
}
diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs
index a3c5b2053ef..7cb7130c9ed 100644
--- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs
+++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs
@@ -542,8 +542,7 @@ internal static List CompleteCommandParameter(CompletionContex
else
{
// No CommandParameterAst is found. It could be a StringConstantExpressionAst "-"
- var dashAst = (context.RelatedAsts[context.RelatedAsts.Count - 1] as StringConstantExpressionAst);
- if (dashAst == null)
+ if (!(context.RelatedAsts[context.RelatedAsts.Count - 1] is StringConstantExpressionAst dashAst))
return result;
if (!dashAst.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase))
return result;
@@ -2803,8 +2802,7 @@ private static void NativeCompletionCimNamespace(
continue;
}
- string childNamespace = namespaceNameProperty.Value as string;
- if (childNamespace == null)
+ if (!(namespaceNameProperty.Value is string childNamespace))
{
continue;
}
@@ -3793,8 +3791,7 @@ private static void NativeCompletionMemberName(CompletionContext context, List CompleteComment(CompletionContext context
for (int index = psobjs.Count - 1; index >= 0; index--)
{
var psobj = psobjs[index];
- var historyInfo = PSObject.Base(psobj) as HistoryInfo;
- if (historyInfo == null) continue;
+ if (!(PSObject.Base(psobj) is HistoryInfo historyInfo)) continue;
var commandLine = historyInfo.CommandLine;
if (!string.IsNullOrEmpty(commandLine) && pattern.IsMatch(commandLine))
@@ -6460,8 +6456,7 @@ internal static bool IsPathSafelyExpandable(ExpandableStringExpressionAst expand
var varValues = new List();
foreach (ExpressionAst nestedAst in expandableStringAst.NestedExpressions)
{
- var variableAst = nestedAst as VariableExpressionAst;
- if (variableAst == null) { return false; }
+ if (!(nestedAst is VariableExpressionAst variableAst)) { return false; }
string strValue = CombineVariableWithPartialPath(variableAst, null, executionContext);
if (strValue != null)
@@ -6586,8 +6581,7 @@ internal static void CompleteMemberHelper(
IEnumerable members;
if (@static)
{
- var type = PSObject.Base(value) as Type;
- if (type == null)
+ if (!(PSObject.Base(value) is Type type))
{
return;
}
@@ -6653,8 +6647,7 @@ internal static void CompleteMemberHelper(
var pattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase);
foreach (DictionaryEntry entry in dictionary)
{
- var key = entry.Key as string;
- if (key == null)
+ if (!(entry.Key is string key))
continue;
if (pattern.IsMatch(key))
diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs
index 4433d75ca99..0b97330715e 100644
--- a/src/System.Management.Automation/engine/CommandProcessor.cs
+++ b/src/System.Management.Automation/engine/CommandProcessor.cs
@@ -101,8 +101,7 @@ internal CommandProcessor(IScriptCommandInfo scriptCommandInfo, ExecutionContext
///
internal ParameterBinderController NewParameterBinderController(InternalCommand command)
{
- Cmdlet cmdlet = command as Cmdlet;
- if (cmdlet == null)
+ if (!(command is Cmdlet cmdlet))
{
throw PSTraceSource.NewArgumentException(nameof(command));
}
diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs
index b6752387d58..1317b8aa346 100644
--- a/src/System.Management.Automation/engine/CoreAdapter.cs
+++ b/src/System.Management.Automation/engine/CoreAdapter.cs
@@ -1658,8 +1658,7 @@ internal static void SetReferences(object[] arguments, MethodInformation methodI
// It still might be an PSObject wrapping an PSReference
if (originalArgumentReference == null)
{
- PSObject originalArgumentObj = originalArgument as PSObject;
- if (originalArgumentObj == null)
+ if (!(originalArgument is PSObject originalArgumentObj))
{
continue;
}
@@ -3878,8 +3877,7 @@ internal void AddAllDynamicMembers(object obj, PSMemberInfoInternalCollection
private static bool PropertyIsStatic(PSProperty property)
{
- PropertyCacheEntry entry = property.adapterData as PropertyCacheEntry;
- if (entry == null)
+ if (!(property.adapterData is PropertyCacheEntry entry))
{
return false;
}
diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs
index e95bb060bdd..41b3bb671a3 100644
--- a/src/System.Management.Automation/engine/ErrorPackage.cs
+++ b/src/System.Management.Automation/engine/ErrorPackage.cs
@@ -1666,8 +1666,7 @@ private string GetInvocationTypeName()
return commandInfo.Name;
}
- CmdletInfo cmdletInfo = commandInfo as CmdletInfo;
- if (cmdletInfo == null)
+ if (!(commandInfo is CmdletInfo cmdletInfo))
{
return string.Empty;
}
diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs
index 7c37cc4f0eb..b8bd6a80998 100644
--- a/src/System.Management.Automation/engine/InternalCommands.cs
+++ b/src/System.Management.Automation/engine/InternalCommands.cs
@@ -2008,8 +2008,7 @@ private void CheckLanguageMode()
private object GetLikeRHSOperand(object operand)
{
- var val = operand as string;
- if (val == null)
+ if (!(operand is string val))
{
return operand;
}
diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs
index 5929a5637e9..fb49fc1a075 100644
--- a/src/System.Management.Automation/engine/LanguagePrimitives.cs
+++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs
@@ -637,8 +637,7 @@ public static bool Equals(object first, object second, bool ignoreCase, IFormatP
formatProvider = CultureInfo.InvariantCulture;
}
- var culture = formatProvider as CultureInfo;
- if (culture == null)
+ if (!(formatProvider is CultureInfo culture))
{
throw PSTraceSource.NewArgumentException(nameof(formatProvider));
}
@@ -785,8 +784,7 @@ public static int Compare(object first, object second, bool ignoreCase, IFormatP
formatProvider = CultureInfo.InvariantCulture;
}
- var culture = formatProvider as CultureInfo;
- if (culture == null)
+ if (!(formatProvider is CultureInfo culture))
{
throw PSTraceSource.NewArgumentException(nameof(formatProvider));
}
@@ -1045,9 +1043,7 @@ internal static bool IsTrue(IList objectArray)
// but since we don't want this to recurse indefinitely
// we explicitly check the case where it would recurse
// and deal with it.
- IList firstElement = PSObject.Base(objectArray[0]) as IList;
-
- if (firstElement == null)
+ if (!(PSObject.Base(objectArray[0]) is IList firstElement))
{
return IsTrue(objectArray[0]);
}
@@ -2095,8 +2091,7 @@ public override object ConvertFrom(object sourceValue, Type destinationType, IFo
protected static object BaseConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase, bool multipleValues)
{
Diagnostics.Assert(sourceValue != null, "the type converter has a special case for null source values");
- string sourceValueString = sourceValue as string;
- if (sourceValueString == null)
+ if (!(sourceValue is string sourceValueString))
{
throw new PSInvalidCastException("InvalidCastEnumFromTypeNotAString", null,
ExtendedTypeSystem.InvalidCastException,
diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs
index 94e07d3af0e..1bbac5d39c1 100644
--- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs
+++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs
@@ -172,9 +172,7 @@ protected override T GetMember(object obj, string memberName)
{
tracer.WriteLine("Getting member with name {0}", memberName);
- ManagementBaseObject mgmtObject = obj as ManagementBaseObject;
-
- if (mgmtObject == null)
+ if (!(obj is ManagementBaseObject mgmtObject))
{
return null;
}
@@ -366,8 +364,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)
{
- ManagementBaseObject mObj = property.baseObject as ManagementBaseObject;
- if (mObj == null)
+ if (!(property.baseObject is ManagementBaseObject mObj))
{
throw new SetValueInvocationException("CannotSetNonManagementObjectMsg",
null,
diff --git a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs
index dd188b3ff99..7047525c1ba 100644
--- a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs
+++ b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs
@@ -194,8 +194,7 @@ internal static bool ModuleIsEditionIncompatible(string modulePath, Hashtable mo
internal static bool ModuleAnalysisViaGetModuleRequired(object modulePathObj, bool hadCmdlets, bool hadFunctions, bool hadAliases)
{
- var modulePath = modulePathObj as string;
- if (modulePath == null)
+ if (!(modulePathObj is string modulePath))
return true;
if (modulePath.EndsWith(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase))
@@ -257,8 +256,7 @@ private static bool CheckModulesTypesInManifestAgainstExportedCommands(Hashtable
return ModuleAnalysisViaGetModuleRequired(nestedModule, hadCmdlets, hadFunctions, hadAliases);
}
- var nestedModuleArray = nestedModules as object[];
- if (nestedModuleArray == null)
+ if (!(nestedModules is object[] nestedModuleArray))
return true;
foreach (var element in nestedModuleArray)
diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs
index 2816dd42f13..1fc335f3d96 100644
--- a/src/System.Management.Automation/engine/MshCommandRuntime.cs
+++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs
@@ -2321,8 +2321,7 @@ internal AllowWrite(InternalCommand permittedToWrite, bool permittedToWriteToPip
{
if (permittedToWrite == null)
throw PSTraceSource.NewArgumentNullException(nameof(permittedToWrite));
- MshCommandRuntime mcr = permittedToWrite.commandRuntime as MshCommandRuntime;
- if (mcr == null)
+ if (!(permittedToWrite.commandRuntime is MshCommandRuntime mcr))
throw PSTraceSource.NewArgumentNullException("permittedToWrite.CommandRuntime");
_pp = mcr.PipelineProcessor;
if (_pp == null)
diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs
index cd7a8cf0a14..ec4fa7f3248 100644
--- a/src/System.Management.Automation/engine/MshObject.cs
+++ b/src/System.Management.Automation/engine/MshObject.cs
@@ -588,9 +588,7 @@ protected PSObject(SerializationInfo info, StreamingContext context)
throw PSTraceSource.NewArgumentNullException(nameof(info));
}
- string serializedData = info.GetValue("CliXml", typeof(string)) as string;
-
- if (serializedData == null)
+ if (!(info.GetValue("CliXml", typeof(string)) is string serializedData))
{
throw PSTraceSource.NewArgumentNullException(nameof(info));
}
@@ -988,8 +986,7 @@ public static implicit operator PSObject(bool valueToConvert)
///
internal static object Base(object obj)
{
- PSObject mshObj = obj as PSObject;
- if (mshObj == null)
+ if (!(obj is PSObject mshObj))
{
return obj;
}
@@ -1073,8 +1070,7 @@ internal static PSObject AsPSObject(object obj, bool storeTypeNameAndInstanceMem
///
internal static object GetKeyForResurrectionTables(object obj)
{
- var pso = obj as PSObject;
- if (pso == null)
+ if (!(obj is PSObject pso))
{
return obj;
}
@@ -1861,8 +1857,7 @@ internal static object GetNoteSettingValue(PSMemberSet settings, string noteName
settings.ReplicateInstance(ownerObject);
}
- PSNoteProperty note = settings.Members[noteName] as PSNoteProperty;
- if (note == null)
+ if (!(settings.Members[noteName] is PSNoteProperty note))
{
return defaultValue;
}
diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs
index 8fe26b1437c..6ad66f6c100 100644
--- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs
+++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs
@@ -218,8 +218,7 @@ private static PSObject GetComponentPSObject(object component)
PSObject mshObj = component as PSObject;
if (mshObj == null)
{
- PSObjectTypeDescriptor descriptor = component as PSObjectTypeDescriptor;
- if (descriptor == null)
+ if (!(component is PSObjectTypeDescriptor descriptor))
{
throw PSTraceSource.NewArgumentException(nameof(component), ExtendedTypeSystem.InvalidComponent,
"component",
@@ -467,8 +466,7 @@ public override PropertyDescriptorCollection GetProperties(Attribute[] attribute
/// True if the Instance property of is equal to the current Instance; otherwise, false.
public override bool Equals(object obj)
{
- PSObjectTypeDescriptor other = obj as PSObjectTypeDescriptor;
- if (other == null)
+ if (!(obj is PSObjectTypeDescriptor other))
{
return false;
}
diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs
index 09f9829c289..c10b57b54bb 100644
--- a/src/System.Management.Automation/engine/PSVersionInfo.cs
+++ b/src/System.Management.Automation/engine/PSVersionInfo.cs
@@ -844,8 +844,7 @@ public int CompareTo(object version)
return 1;
}
- var v = version as SemanticVersion;
- if (v == null)
+ if (!(version is SemanticVersion v))
{
throw PSTraceSource.NewArgumentException(nameof(version));
}
diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs
index f4f2a46d2a5..6fbd3b340a8 100644
--- a/src/System.Management.Automation/engine/SessionStateContainer.cs
+++ b/src/System.Management.Automation/engine/SessionStateContainer.cs
@@ -1841,9 +1841,7 @@ private void ProcessPathItems(
return;
}
- string childName = childNameObjects[index].BaseObject as string;
-
- if (childName == null)
+ if (!(childNameObjects[index].BaseObject is string childName))
{
continue;
}
@@ -2588,9 +2586,7 @@ private void DoGetChildNamesManually(
return;
}
- string name = result.BaseObject as string;
-
- if (name == null)
+ if (!(result.BaseObject is string name))
{
continue;
}
@@ -2638,9 +2634,7 @@ private void DoGetChildNamesManually(
return;
}
- string name = result.BaseObject as string;
-
- if (name == null)
+ if (!(result.BaseObject is string name))
{
continue;
}
diff --git a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs
index f1b637a1d84..bc79b45600a 100644
--- a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs
+++ b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs
@@ -350,10 +350,7 @@ internal DriveCmdletProvider GetDriveProviderInstance(string providerId)
throw PSTraceSource.NewArgumentNullException(nameof(providerId));
}
- DriveCmdletProvider driveCmdletProvider =
- GetProviderInstance(providerId) as DriveCmdletProvider;
-
- if (driveCmdletProvider == null)
+ if (!(GetProviderInstance(providerId) is DriveCmdletProvider driveCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported);
@@ -385,10 +382,7 @@ internal DriveCmdletProvider GetDriveProviderInstance(ProviderInfo provider)
throw PSTraceSource.NewArgumentNullException(nameof(provider));
}
- DriveCmdletProvider driveCmdletProvider =
- GetProviderInstance(provider) as DriveCmdletProvider;
-
- if (driveCmdletProvider == null)
+ if (!(GetProviderInstance(provider) is DriveCmdletProvider driveCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported);
@@ -420,10 +414,7 @@ private static DriveCmdletProvider GetDriveProviderInstance(CmdletProvider provi
throw PSTraceSource.NewArgumentNullException(nameof(providerInstance));
}
- DriveCmdletProvider driveCmdletProvider =
- providerInstance as DriveCmdletProvider;
-
- if (driveCmdletProvider == null)
+ if (!(providerInstance is DriveCmdletProvider driveCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported);
@@ -458,10 +449,7 @@ internal ItemCmdletProvider GetItemProviderInstance(string providerId)
throw PSTraceSource.NewArgumentNullException(nameof(providerId));
}
- ItemCmdletProvider itemCmdletProvider =
- GetProviderInstance(providerId) as ItemCmdletProvider;
-
- if (itemCmdletProvider == null)
+ if (!(GetProviderInstance(providerId) is ItemCmdletProvider itemCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported);
@@ -493,10 +481,7 @@ internal ItemCmdletProvider GetItemProviderInstance(ProviderInfo provider)
throw PSTraceSource.NewArgumentNullException(nameof(provider));
}
- ItemCmdletProvider itemCmdletProvider =
- GetProviderInstance(provider) as ItemCmdletProvider;
-
- if (itemCmdletProvider == null)
+ if (!(GetProviderInstance(provider) is ItemCmdletProvider itemCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported);
@@ -528,10 +513,7 @@ private static ItemCmdletProvider GetItemProviderInstance(CmdletProvider provide
throw PSTraceSource.NewArgumentNullException(nameof(providerInstance));
}
- ItemCmdletProvider itemCmdletProvider =
- providerInstance as ItemCmdletProvider;
-
- if (itemCmdletProvider == null)
+ if (!(providerInstance is ItemCmdletProvider itemCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported);
@@ -566,10 +548,7 @@ internal ContainerCmdletProvider GetContainerProviderInstance(string providerId)
throw PSTraceSource.NewArgumentNullException(nameof(providerId));
}
- ContainerCmdletProvider containerCmdletProvider =
- GetProviderInstance(providerId) as ContainerCmdletProvider;
-
- if (containerCmdletProvider == null)
+ if (!(GetProviderInstance(providerId) is ContainerCmdletProvider containerCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported);
@@ -601,10 +580,7 @@ internal ContainerCmdletProvider GetContainerProviderInstance(ProviderInfo provi
throw PSTraceSource.NewArgumentNullException(nameof(provider));
}
- ContainerCmdletProvider containerCmdletProvider =
- GetProviderInstance(provider) as ContainerCmdletProvider;
-
- if (containerCmdletProvider == null)
+ if (!(GetProviderInstance(provider) is ContainerCmdletProvider containerCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported);
@@ -636,10 +612,7 @@ private static ContainerCmdletProvider GetContainerProviderInstance(CmdletProvid
throw PSTraceSource.NewArgumentNullException(nameof(providerInstance));
}
- ContainerCmdletProvider containerCmdletProvider =
- providerInstance as ContainerCmdletProvider;
-
- if (containerCmdletProvider == null)
+ if (!(providerInstance is ContainerCmdletProvider containerCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported);
@@ -671,10 +644,7 @@ internal NavigationCmdletProvider GetNavigationProviderInstance(ProviderInfo pro
throw PSTraceSource.NewArgumentNullException(nameof(provider));
}
- NavigationCmdletProvider navigationCmdletProvider =
- GetProviderInstance(provider) as NavigationCmdletProvider;
-
- if (navigationCmdletProvider == null)
+ if (!(GetProviderInstance(provider) is NavigationCmdletProvider navigationCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(SessionStateStrings.NavigationCmdletProvider_NotSupported);
diff --git a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs
index 73cf89cebdf..e59ff3aa55a 100644
--- a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs
+++ b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs
@@ -35,10 +35,7 @@ internal static ISecurityDescriptorCmdletProvider GetPermissionProviderInstance(
throw PSTraceSource.NewArgumentNullException(nameof(providerInstance));
}
- ISecurityDescriptorCmdletProvider permissionCmdletProvider =
- providerInstance as ISecurityDescriptorCmdletProvider;
-
- if (permissionCmdletProvider == null)
+ if (!(providerInstance is ISecurityDescriptorCmdletProvider permissionCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(
diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs
index a58bc094458..3258313952f 100644
--- a/src/System.Management.Automation/engine/TypeTable.cs
+++ b/src/System.Management.Automation/engine/TypeTable.cs
@@ -3970,8 +3970,7 @@ internal Collection GetSpecificProperties(ConsolidatedString types)
}
PSMemberSet settings = typeMembers[PSStandardMembers] as PSMemberSet;
- PSPropertySet typeProperties = settings?.Members[PropertySerializationSet] as PSPropertySet;
- if (typeProperties == null)
+ if (!(settings?.Members[PropertySerializationSet] is PSPropertySet typeProperties))
{
continue;
}
diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs
index 0396f11c76a..7d61e7190cf 100644
--- a/src/System.Management.Automation/engine/Utils.cs
+++ b/src/System.Management.Automation/engine/Utils.cs
@@ -1674,8 +1674,7 @@ internal static bool TryRunAsImplicitBatch(string command, Runspace runspace)
try
{
var scriptBlock = ScriptBlock.Create(command);
- var scriptBlockAst = scriptBlock.Ast as ScriptBlockAst;
- if (scriptBlockAst == null)
+ if (!(scriptBlock.Ast is ScriptBlockAst scriptBlockAst))
{
return false;
}
diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs
index 06e2ec78615..ba7e97a49ef 100644
--- a/src/System.Management.Automation/engine/debugger/debugger.cs
+++ b/src/System.Management.Automation/engine/debugger/debugger.cs
@@ -2319,8 +2319,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC
//
// Otherwise let root script debugger handle it.
//
- LocalRunspace localRunspace = _context.CurrentRunspace as LocalRunspace;
- if (localRunspace == null)
+ if (!(_context.CurrentRunspace is LocalRunspace localRunspace))
{
throw new PSInvalidOperationException(
DebuggerStrings.CannotProcessDebuggerCommandNotStopped,
@@ -3765,8 +3764,7 @@ private void HandleMonitorRunningRSDebuggerStop(object sender, DebuggerStopEvent
}
// Get nested debugger runspace info.
- NestedRunspaceDebugger nestedDebugger = senderDebugger as NestedRunspaceDebugger;
- if (nestedDebugger == null) { return; }
+ if (!(senderDebugger is NestedRunspaceDebugger nestedDebugger)) { return; }
PSMonitorRunspaceType runspaceType = nestedDebugger.RunspaceType;
@@ -4626,8 +4624,7 @@ protected override void HandleDebuggerStop(object sender, DebuggerStopEventArgs
private object DrainAndBlockRemoteOutput()
{
// We do this only for remote runspaces.
- RemoteRunspace remoteRunspace = _runspace as RemoteRunspace;
- if (remoteRunspace == null) { return null; }
+ if (!(_runspace is RemoteRunspace remoteRunspace)) { return null; }
var runningPowerShell = remoteRunspace.GetCurrentBasePowerShell();
if (runningPowerShell != null)
diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs
index 26496f74ef7..0a062187018 100644
--- a/src/System.Management.Automation/engine/hostifaces/History.cs
+++ b/src/System.Management.Automation/engine/hostifaces/History.cs
@@ -1434,8 +1434,7 @@ void ProcessRecord()
break;
}
// Read CommandLine property
- string commandLine = GetPropertyValue(mshObject, "CommandLine") as string;
- if (commandLine == null)
+ if (!(GetPropertyValue(mshObject, "CommandLine") is string commandLine))
{
break;
}
diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs
index ecc4780c284..9c1f4ffca2e 100644
--- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs
+++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs
@@ -309,8 +309,7 @@ internal static string GetMaxLines(string source, int maxLines)
internal static List GetSuggestion(Runspace runspace)
{
- LocalRunspace localRunspace = runspace as LocalRunspace;
- if (localRunspace == null) { return new List(); }
+ if (!(runspace is LocalRunspace localRunspace)) { return new List(); }
// Get the last value of $?
bool questionMarkVariableValue = localRunspace.ExecutionContext.QuestionMarkVariableValue;
diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs
index e170a3792e4..2a956c44c22 100644
--- a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs
+++ b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs
@@ -448,8 +448,7 @@ public override void NotifyEndApplication()
///
private IHostSupportsInteractiveSession GetIHostSupportsInteractiveSession()
{
- IHostSupportsInteractiveSession host = _externalHostRef.Value as IHostSupportsInteractiveSession;
- if (host == null)
+ if (!(_externalHostRef.Value is IHostSupportsInteractiveSession host))
{
throw new PSNotImplementedException();
}
diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs
index 191a5309cc7..ee058d8d15c 100644
--- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs
+++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs
@@ -219,8 +219,7 @@ public void ApplyTo(object collectionToUpdate)
collectionToUpdate = PSObject.Base(collectionToUpdate);
- IList list = collectionToUpdate as IList;
- if (list == null)
+ if (!(collectionToUpdate is IList list))
{
throw PSTraceSource.NewInvalidOperationException(PSListModifierStrings.UpdateFailed);
}
diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs
index dfd33cc2257..6c128cf994f 100644
--- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs
+++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs
@@ -336,9 +336,7 @@ protected PSDataCollection(SerializationInfo info, StreamingContext context)
throw PSTraceSource.NewArgumentNullException(nameof(info));
}
- IList listToUse = info.GetValue("Data", typeof(IList)) as IList;
-
- if (listToUse == null)
+ if (!(info.GetValue("Data", typeof(IList)) is IList listToUse))
{
throw PSTraceSource.NewArgumentNullException(nameof(info));
}
diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs
index 12a4ffce7ab..17cafc805aa 100644
--- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs
+++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs
@@ -1370,9 +1370,7 @@ public PowerShell AddParameters(IDictionary parameters)
foreach (DictionaryEntry entry in parameters)
{
- string parameterName = entry.Key as string;
-
- if (parameterName == null)
+ if (!(entry.Key is string parameterName))
{
throw PSTraceSource.NewArgumentException(nameof(parameters), PowerShellStrings.KeyMustBeString);
}
@@ -3325,9 +3323,7 @@ public Task> InvokeAsync(PSDataColle
///
private IAsyncResult BeginBatchInvoke(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings, AsyncCallback callback, object state)
{
- PSDataCollection asyncOutput = (object)output as PSDataCollection;
-
- if (asyncOutput == null)
+ if (!((object)output is PSDataCollection asyncOutput))
{
throw PSTraceSource.NewInvalidOperationException();
}
diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs
index e5d399bf480..ed7fd4fd38f 100644
--- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs
+++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs
@@ -1297,8 +1297,7 @@ private bool TryPushLabelBlock(Expression node)
private void DefineBlockLabels(Expression node)
{
- var block = node as BlockExpression;
- if (block == null)
+ if (!(node is BlockExpression block))
{
return;
}
diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs
index 99e0f0f6cbf..c0d86965352 100644
--- a/src/System.Management.Automation/engine/lang/parserutils.cs
+++ b/src/System.Management.Automation/engine/lang/parserutils.cs
@@ -1466,8 +1466,7 @@ internal static string GetTypeFullName(object obj)
return string.Empty;
}
- PSObject mshObj = obj as PSObject;
- if (mshObj == null)
+ if (!(obj is PSObject mshObj))
{
return obj.GetType().FullName;
}
@@ -1571,9 +1570,7 @@ internal static object CallMethod(
// not really a method call.
if (valueToSet != AutomationNull.Value)
{
- PSParameterizedProperty propertyToSet = targetMethod as PSParameterizedProperty;
-
- if (propertyToSet == null)
+ if (!(targetMethod is PSParameterizedProperty propertyToSet))
{
throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition,
"ParameterizedPropertyAssignmentFailed", ParserStrings.ParameterizedPropertyAssignmentFailed, GetTypeFullName(target), methodName);
diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs
index b08d588fa0e..ec6e02fe96f 100644
--- a/src/System.Management.Automation/engine/parser/Compiler.cs
+++ b/src/System.Management.Automation/engine/parser/Compiler.cs
@@ -5935,14 +5935,12 @@ public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst)
private static Expression GetLikeRHSOperand(WildcardOptions options, Expression expr)
{
- var constExpr = expr as ConstantExpression;
- if (constExpr == null)
+ if (!(expr is ConstantExpression constExpr))
{
return expr;
}
- var val = constExpr.Value as string;
- if (val == null)
+ if (!(constExpr.Value is string val))
{
return expr;
}
diff --git a/src/System.Management.Automation/engine/parser/ConstantValues.cs b/src/System.Management.Automation/engine/parser/ConstantValues.cs
index 5813ed9d41f..60c10144626 100644
--- a/src/System.Management.Automation/engine/parser/ConstantValues.cs
+++ b/src/System.Management.Automation/engine/parser/ConstantValues.cs
@@ -160,8 +160,7 @@ public object VisitPipeline(PipelineAst pipelineAst)
private static bool IsNullDivisor(ExpressionAst operand)
{
- var varExpr = operand as VariableExpressionAst;
- if (varExpr == null)
+ if (!(operand is VariableExpressionAst varExpr))
{
return false;
}
@@ -272,8 +271,7 @@ public object VisitMemberExpression(MemberExpressionAst memberExpressionAst)
return false;
}
- var member = memberExpressionAst.Member as StringConstantExpressionAst;
- if (member == null)
+ if (!(memberExpressionAst.Member is StringConstantExpressionAst member))
{
return false;
}
diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs
index e3245e91564..0969d242e98 100644
--- a/src/System.Management.Automation/engine/parser/Parser.cs
+++ b/src/System.Management.Automation/engine/parser/Parser.cs
@@ -732,8 +732,7 @@ internal static bool TryParseAsConstantHashtable(string input, out Hashtable res
return false;
}
- var pipelineAst = statements[0] as PipelineAst;
- if (pipelineAst == null)
+ if (!(statements[0] is PipelineAst pipelineAst))
{
return false;
}
@@ -744,8 +743,7 @@ internal static bool TryParseAsConstantHashtable(string input, out Hashtable res
return false;
}
- var hashTableAst = expr as HashtableAst;
- if (hashTableAst == null)
+ if (!(expr is HashtableAst hashTableAst))
{
return false;
}
diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs
index e9f273fed14..24ce0d118a2 100644
--- a/src/System.Management.Automation/engine/parser/Position.cs
+++ b/src/System.Management.Automation/engine/parser/Position.cs
@@ -571,8 +571,7 @@ internal sealed class EmptyScriptExtent : IScriptExtent
public override bool Equals(object obj)
{
- IScriptExtent otherPosition = obj as IScriptExtent;
- if (otherPosition == null)
+ if (!(obj is IScriptExtent otherPosition))
{
return false;
}
diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs
index f46b366785b..051b8f4bd54 100644
--- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs
+++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs
@@ -692,8 +692,7 @@ public override AstVisitAction VisitContinueStatement(ContinueStatementAst conti
private void CheckForReturnStatement(ReturnStatementAst ast)
{
- var functionMemberAst = _memberScopeStack.Peek() as FunctionMemberAst;
- if (functionMemberAst == null)
+ if (!(_memberScopeStack.Peek() is FunctionMemberAst functionMemberAst))
{
return;
}
@@ -1583,8 +1582,7 @@ private static void LookupRequiredMembers(Parser parser, TypeDefinitionAst typeD
foreach (var baseType in typeDefinitionAst.BaseTypes)
{
- var baseTypeName = baseType.TypeName as TypeName;
- if (baseTypeName == null)
+ if (!(baseType.TypeName is TypeName baseTypeName))
{
continue;
}
diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs
index 59cf5348cc8..2543c5273d0 100644
--- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs
+++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs
@@ -316,8 +316,7 @@ internal void AddMembersByInferredTypeDefinitionAst(
// iterate through bases/interfaces
foreach (var baseType in typename.TypeDefinitionAst.BaseTypes)
{
- var baseTypeName = baseType.TypeName as TypeName;
- if (baseTypeName == null)
+ if (!(baseType.TypeName is TypeName baseTypeName))
{
continue;
}
@@ -1484,8 +1483,7 @@ private IEnumerable InferTypesFrom(MemberExpressionAst memberExpress
var expression = memberExpressionAst.Expression;
// If the member name isn't simple, don't even try.
- var memberAsStringConst = memberCommandElement as StringConstantExpressionAst;
- if (memberAsStringConst == null)
+ if (!(memberCommandElement is StringConstantExpressionAst memberAsStringConst))
{
return Array.Empty();
}
@@ -1728,8 +1726,7 @@ private PSTypeName[] GetExpressionType(ExpressionAst expression, bool isStatic)
PSTypeName[] exprType;
if (isStatic)
{
- var exprAsType = expression as TypeExpressionAst;
- if (exprAsType == null)
+ if (!(expression is TypeExpressionAst exprAsType))
{
return null;
}
@@ -2281,8 +2278,7 @@ private IEnumerable GetInferredEnumeratedTypes(IEnumerable inferredTypes)
{
var argumentPair = argument as AstPair;
- var scriptBlockExpressionAst = argumentPair?.Argument as ScriptBlockExpressionAst;
- if (scriptBlockExpressionAst == null)
+ if (!(argumentPair?.Argument is ScriptBlockExpressionAst scriptBlockExpressionAst))
{
return;
}
diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs
index fa054554b2a..b5e6ae733a1 100644
--- a/src/System.Management.Automation/engine/parser/TypeResolver.cs
+++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs
@@ -615,9 +615,7 @@ public override bool Equals(object obj)
if (object.ReferenceEquals(this, obj))
return true;
- var other = obj as TypeResolutionState;
-
- if (other == null)
+ if (!(obj is TypeResolutionState other))
return false;
if (this.attribute != other.attribute)
diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs
index 459b6c206c4..9e2f996cfd3 100644
--- a/src/System.Management.Automation/engine/parser/ast.cs
+++ b/src/System.Management.Automation/engine/parser/ast.cs
@@ -7213,8 +7213,7 @@ internal virtual bool ShouldPreserveOutputInCaseOfException()
PSTraceSource.NewInvalidOperationException();
}
- var commandExpr = this.Parent as CommandExpressionAst;
- if (commandExpr == null)
+ if (!(this.Parent is CommandExpressionAst commandExpr))
{
return false;
}
@@ -7726,8 +7725,7 @@ Expression IAssignableValue.SetValue(Compiler compiler, Expression rhs)
var attributes = GetAttributes();
var assignableValue = GetActualAssignableAst().GetAssignableValue();
- var variableExpr = assignableValue as VariableExpressionAst;
- if (variableExpr == null)
+ if (!(assignableValue is VariableExpressionAst variableExpr))
{
return assignableValue.SetValue(compiler, Compiler.ConvertValue(rhs, attributes));
}
@@ -8371,8 +8369,7 @@ public override string ToString()
///
public override bool Equals(object obj)
{
- var other = obj as TypeName;
- if (other == null)
+ if (!(obj is TypeName other))
return false;
if (!_name.Equals(other._name, StringComparison.OrdinalIgnoreCase))
@@ -8690,8 +8687,7 @@ public override string ToString()
///
public override bool Equals(object obj)
{
- var other = obj as GenericTypeName;
- if (other == null)
+ if (!(obj is GenericTypeName other))
return false;
if (!TypeName.Equals(other.TypeName))
@@ -8916,8 +8912,7 @@ public override string ToString()
///
public override bool Equals(object obj)
{
- var other = obj as ArrayTypeName;
- if (other == null)
+ if (!(obj is ArrayTypeName other))
return false;
return ElementType.Equals(other.ElementType) && Rank == other.Rank;
@@ -9018,8 +9013,7 @@ public override string ToString()
///
public override bool Equals(object obj)
{
- var other = obj as ReflectionTypeName;
- if (other == null)
+ if (!(obj is ReflectionTypeName other))
return false;
return _type == other._type;
}
diff --git a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs
index ba4e08c8f6f..1fcad961c7c 100644
--- a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs
+++ b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs
@@ -134,8 +134,7 @@ internal static void Dispatch(
///
private bool IsRunspacePushed(PSHost host)
{
- IHostSupportsInteractiveSession host2 = host as IHostSupportsInteractiveSession;
- if (host2 == null) { return false; }
+ if (!(host is IHostSupportsInteractiveSession host2)) { return false; }
// IsRunspacePushed can throw (not implemented exception)
try
diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs
index 1758da68258..e296609cd92 100644
--- a/src/System.Management.Automation/engine/remoting/client/Job.cs
+++ b/src/System.Management.Automation/engine/remoting/client/Job.cs
@@ -750,12 +750,10 @@ private void WriteError(Cmdlet cmdlet, ErrorRecord errorRecord)
private static Exception GetExceptionFromErrorRecord(ErrorRecord errorRecord)
{
- RuntimeException runtimeException = errorRecord.Exception as RuntimeException;
- if (runtimeException == null)
+ if (!(errorRecord.Exception is RuntimeException runtimeException))
return null;
- RemoteException remoteException = runtimeException as RemoteException;
- if (remoteException == null)
+ if (!(runtimeException is RemoteException remoteException))
return null;
PSPropertyInfo wasThrownFromThrow =
@@ -1910,8 +1908,7 @@ internal List GetJobsForComputer(string computerName)
foreach (Job j in ChildJobs)
{
- PSRemotingChildJob child = j as PSRemotingChildJob;
- if (child == null) continue;
+ if (!(j is PSRemotingChildJob child)) continue;
if (string.Equals(child.Runspace.ConnectionInfo.ComputerName, computerName,
StringComparison.OrdinalIgnoreCase))
{
@@ -1934,8 +1931,7 @@ internal List GetJobsForRunspace(PSSession runspace)
foreach (Job j in ChildJobs)
{
- PSRemotingChildJob child = j as PSRemotingChildJob;
- if (child == null) continue;
+ if (!(j is PSRemotingChildJob child)) continue;
if (child.Runspace.InstanceId.Equals(runspace.InstanceId))
{
returnJobList.Add(child);
@@ -1958,8 +1954,7 @@ internal List GetJobsForOperation(IThrottleOperation operation)
foreach (Job j in ChildJobs)
{
- PSRemotingChildJob child = j as PSRemotingChildJob;
- if (child == null) continue;
+ if (!(j is PSRemotingChildJob child)) continue;
if (child.Helper.Equals(helper))
{
returnJobList.Add(child);
diff --git a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs
index f38ac4a39d0..de3d41d1956 100644
--- a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs
+++ b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs
@@ -415,8 +415,7 @@ public void StoreJobIdForReuse(Job2 job, bool recurse)
duplicateDetector.Add(job.InstanceId, job.InstanceId);
foreach (Job child in job.ChildJobs)
{
- Job2 childJob = child as Job2;
- if (childJob == null) continue;
+ if (!(child is Job2 childJob)) continue;
StoreJobIdForReuseHelper(duplicateDetector, childJob, true);
}
}
@@ -432,8 +431,7 @@ private void StoreJobIdForReuseHelper(Hashtable duplicateDetector, Job2 job, boo
if (!recurse || job.ChildJobs == null) return;
foreach (Job child in job.ChildJobs)
{
- Job2 childJob = child as Job2;
- if (childJob == null) continue;
+ if (!(child is Job2 childJob)) continue;
StoreJobIdForReuseHelper(duplicateDetector, childJob, recurse);
}
}
diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs
index 17b07b0f148..31401e6b058 100644
--- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs
+++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs
@@ -1237,11 +1237,9 @@ public override RunspacePoolCapability GetCapabilities()
internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable)
{
- WSManConnectionInfo wsmanConnectionInfoParam = connectionInfo as WSManConnectionInfo;
-
- // Disconnect-Connect currently only supported by WSMan.
- if (wsmanConnectionInfoParam == null)
+ if (!(connectionInfo is WSManConnectionInfo wsmanConnectionInfoParam))
{
+ // Disconnect-Connect currently only supported by WSMan.
throw new NotSupportedException();
}
diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs
index 71985462fc5..666fae3dffe 100644
--- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs
+++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs
@@ -1753,8 +1753,7 @@ internal static string CreateConditionalACEFromConfig(
}
StringBuilder conditionalACE = new StringBuilder();
- Hashtable requiredGroupsHash = configTable[ConfigFileConstants.RequiredGroups] as Hashtable;
- if (requiredGroupsHash == null)
+ if (!(configTable[ConfigFileConstants.RequiredGroups] is Hashtable requiredGroupsHash))
{
throw new PSInvalidOperationException(RemotingErrorIdStrings.RequiredGroupsNotHashTable);
}
diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs
index daef292017f..4ac65085e3e 100644
--- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs
+++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs
@@ -1007,8 +1007,7 @@ protected override void BeginProcessing()
// create collection of input writers here
foreach (IThrottleOperation operation in Operations)
{
- ExecutionCmdletHelperRunspace ecHelper = operation as ExecutionCmdletHelperRunspace;
- if (ecHelper == null)
+ if (!(operation is ExecutionCmdletHelperRunspace ecHelper))
{
// either all the operations will be of type ExecutionCmdletHelperRunspace
// or not...there is no mix.
diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs
index 500c5032a49..7609a3eda44 100644
--- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs
+++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs
@@ -1158,8 +1158,7 @@ private PSSession ConnectSession(PSSession session, out Exception ex)
/// PSSession disconnected runspace object.
private PSSession TryGetSessionFromServer(PSSession session)
{
- RemoteRunspace remoteRunspace = session.Runspace as RemoteRunspace;
- if (remoteRunspace == null)
+ if (!(session.Runspace is RemoteRunspace remoteRunspace))
{
return null;
}
diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs
index c134cde53cc..6b4e91efae3 100644
--- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs
+++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs
@@ -1124,8 +1124,7 @@ private string ResolveShellUri(string shell)
internal static T ExtractPropertyAsWsManConnectionInfo(RunspaceConnectionInfo rsCI,
string property, T defaultValue)
{
- WSManConnectionInfo wsCI = rsCI as WSManConnectionInfo;
- if (wsCI == null)
+ if (!(rsCI is WSManConnectionInfo wsCI))
{
return defaultValue;
}
diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs
index 9188263fd54..fc011b313e2 100644
--- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs
+++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs
@@ -2088,8 +2088,7 @@ internal static object GetPowerShellOutput(object data)
/// PSInvocationInfo.
internal static PSInvocationStateInfo GetPowerShellStateInfo(object data)
{
- PSObject dataAsPSObject = data as PSObject;
- if (dataAsPSObject == null)
+ if (!(data is PSObject dataAsPSObject))
{
throw new PSRemotingDataStructureException(
RemotingErrorIdStrings.DecodingErrorForPowerShellStateInfo);
@@ -2357,9 +2356,7 @@ internal static RemoteStreamOptions GetRemoteStreamOptions(object data)
/// RemoteSessionCapability object.
internal static RemoteSessionCapability GetSessionCapability(object data)
{
- PSObject dataAsPSObject = data as PSObject;
-
- if (dataAsPSObject == null)
+ if (!(data is PSObject dataAsPSObject))
{
throw new PSRemotingDataStructureException(
RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName);
diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs
index 07597fd79ec..18e221d1330 100644
--- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs
+++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs
@@ -2804,9 +2804,7 @@ internal static Hashtable[] TryGetHashtableArray(object hashObj)
for (int i = 0; i < hashArray.Length; i++)
{
- Hashtable hash = objArray[i] as Hashtable;
-
- if (hash == null)
+ if (!(objArray[i] is Hashtable hash))
{
return null;
}
diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs
index 921f9f456f1..35957d47b0e 100644
--- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs
+++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs
@@ -327,8 +327,7 @@ public override void PushRunspace(Runspace runspace)
throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostAlreadyPushed);
}
- RemoteRunspace remoteRunspace = runspace as RemoteRunspace;
- if (remoteRunspace == null)
+ if (!(runspace is RemoteRunspace remoteRunspace))
{
throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostNotRemoteRunspace);
}
diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs
index f441a84470c..ee4b45e5c51 100644
--- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs
+++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs
@@ -193,8 +193,7 @@ private void ReallyCompile(bool optimize)
private void PerformSecurityChecks()
{
- var scriptBlockAst = Ast as ScriptBlockAst;
- if (scriptBlockAst == null)
+ if (!(Ast is ScriptBlockAst scriptBlockAst))
{
// Checks are only needed at the top level.
return;
@@ -263,14 +262,12 @@ bool IsScriptBlockInFactASafeHashtable()
return false;
}
- PipelineAst pipelineAst = endBlock.Statements[0] as PipelineAst;
- if (pipelineAst == null)
+ if (!(endBlock.Statements[0] is PipelineAst pipelineAst))
{
return false;
}
- HashtableAst hashtableAst = pipelineAst.GetPureExpression() as HashtableAst;
- if (hashtableAst == null)
+ if (!(pipelineAst.GetPureExpression() is HashtableAst hashtableAst))
{
return false;
}
@@ -763,8 +760,7 @@ private PipelineAst GetSimplePipeline(Func errorHandler)
return errorHandler(AutomationExceptions.CantConvertScriptBlockWithTrap);
}
- var pipeAst = statements[0] as PipelineAst;
- if (pipeAst == null)
+ if (!(statements[0] is PipelineAst pipeAst))
{
return errorHandler(AutomationExceptions.CanOnlyConvertOnePipeline);
}
diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs
index 2b5d1771ed3..b9cc1e515ad 100644
--- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs
+++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs
@@ -1280,8 +1280,7 @@ internal static void DefineFunction(ExecutionContext context,
}
catch (Exception exception)
{
- var rte = exception as RuntimeException;
- if (rte == null)
+ if (!(exception is RuntimeException rte))
{
throw ExceptionHandlingOps.ConvertToRuntimeException(exception, functionDefinitionAst.Extent);
}
diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs
index 4e6d81e9208..09e21f5c7b4 100644
--- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs
+++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs
@@ -386,8 +386,7 @@ private static Tuple, object[]> GetUsingValues(Ast bo
if (variables != null)
{
- var variableAst = usingAst.SubExpression as VariableExpressionAst;
- if (variableAst == null)
+ if (!(usingAst.SubExpression is VariableExpressionAst variableAst))
{
throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
usingAst.Extent, "CantGetUsingExpressionValueWithSpecifiedVariableDictionary", AutomationExceptions.CantGetUsingExpressionValueWithSpecifiedVariableDictionary, usingAst.Extent.Text);
diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs
index de5d107404c..0fb9e974279 100644
--- a/src/System.Management.Automation/engine/serialization.cs
+++ b/src/System.Management.Automation/engine/serialization.cs
@@ -1982,8 +1982,7 @@ int depth
foreach (PSMemberInfo info in propertyCollection)
{
- PSProperty prop = info as PSProperty;
- if (prop == null)
+ if (!(info is PSProperty prop))
{
continue;
}
@@ -3331,32 +3330,28 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty)
PSObject psoDeserializedClass = PSObject.AsPSObject(deserializedClass);
- PSPropertyInfo namespaceProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimNamespaceProperty] as PSPropertyInfo;
- if (namespaceProperty == null)
+ if (!(psoDeserializedClass.InstanceMembers[InternalDeserializer.CimNamespaceProperty] is PSPropertyInfo namespaceProperty))
{
return null;
}
string cimNamespace = namespaceProperty.Value as string;
- PSPropertyInfo classNameProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimClassNameProperty] as PSPropertyInfo;
- if (classNameProperty == null)
+ if (!(psoDeserializedClass.InstanceMembers[InternalDeserializer.CimClassNameProperty] is PSPropertyInfo classNameProperty))
{
return null;
}
string cimClassName = classNameProperty.Value as string;
- PSPropertyInfo computerNameProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimServerNameProperty] as PSPropertyInfo;
- if (computerNameProperty == null)
+ if (!(psoDeserializedClass.InstanceMembers[InternalDeserializer.CimServerNameProperty] is PSPropertyInfo computerNameProperty))
{
return null;
}
string computerName = computerNameProperty.Value as string;
- PSPropertyInfo hashCodeProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimHashCodeProperty] as PSPropertyInfo;
- if (hashCodeProperty == null)
+ if (!(psoDeserializedClass.InstanceMembers[InternalDeserializer.CimHashCodeProperty] is PSPropertyInfo hashCodeProperty))
{
return null;
}
@@ -3473,8 +3468,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject)
{
foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.AdaptedMembers)
{
- PSPropertyInfo deserializedProperty = deserializedMemberInfo as PSPropertyInfo;
- if (deserializedProperty == null)
+ if (!(deserializedMemberInfo is PSPropertyInfo deserializedProperty))
{
continue;
}
@@ -3494,8 +3488,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject)
// process properties that were originally "extended" properties
foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.InstanceMembers)
{
- PSPropertyInfo deserializedProperty = deserializedMemberInfo as PSPropertyInfo;
- if (deserializedProperty == null)
+ if (!(deserializedMemberInfo is PSPropertyInfo deserializedProperty))
{
continue;
}
@@ -7279,8 +7272,7 @@ public static UInt32 GetParameterSetMetadataFlags(PSObject instance)
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
- ParameterSetMetadata parameterSetMetadata = instance.BaseObject as ParameterSetMetadata;
- if (parameterSetMetadata == null)
+ if (!(instance.BaseObject is ParameterSetMetadata parameterSetMetadata))
{
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
@@ -7301,8 +7293,7 @@ public static PSObject GetInvocationInfo(PSObject instance)
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
- DebuggerStopEventArgs dbgStopEventArgs = instance.BaseObject as DebuggerStopEventArgs;
- if (dbgStopEventArgs == null)
+ if (!(instance.BaseObject is DebuggerStopEventArgs dbgStopEventArgs))
{
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
@@ -7561,8 +7552,7 @@ public static Guid GetFormatViewDefinitionInstanceId(PSObject instance)
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
- FormatViewDefinition formatViewDefinition = instance.BaseObject as FormatViewDefinition;
- if (formatViewDefinition == null)
+ if (!(instance.BaseObject is FormatViewDefinition formatViewDefinition))
{
throw PSTraceSource.NewArgumentNullException(nameof(instance));
}
diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs
index 7dd893d2c7c..4dff9fdd6ab 100644
--- a/src/System.Management.Automation/help/CommandHelpProvider.cs
+++ b/src/System.Management.Automation/help/CommandHelpProvider.cs
@@ -765,9 +765,7 @@ private void ProcessUserDefinedHelpData(string mshSnapInId, UserDefinedHelpData
if (helpInfo == null)
return;
- MamlCommandHelpInfo commandHelpInfo = helpInfo as MamlCommandHelpInfo;
-
- if (commandHelpInfo == null)
+ if (!(helpInfo is MamlCommandHelpInfo commandHelpInfo))
return;
commandHelpInfo.AddUserDefinedData(userDefinedHelpData);
diff --git a/src/System.Management.Automation/help/ProviderContext.cs b/src/System.Management.Automation/help/ProviderContext.cs
index 184ad5526fa..cb24ece0593 100644
--- a/src/System.Management.Automation/help/ProviderContext.cs
+++ b/src/System.Management.Automation/help/ProviderContext.cs
@@ -108,11 +108,9 @@ internal MamlCommandHelpInfo GetProviderSpecificHelpInfo(string helpItemName)
// Does the provider know how to generate MAML.
CmdletProvider cmdletProvider = providerInfo.CreateInstance();
- ICmdletProviderSupportsHelp provider = cmdletProvider as ICmdletProviderSupportsHelp;
-
- // Under JEA sessions the resolvedProviderPath will be null, we should allow get-help to continue.
- if (provider == null)
+ if (!(cmdletProvider is ICmdletProviderSupportsHelp provider))
{
+ // Under JEA sessions the resolvedProviderPath will be null, we should allow get-help to continue.
return null;
}
diff --git a/src/System.Management.Automation/namespaces/ProviderBase.cs b/src/System.Management.Automation/namespaces/ProviderBase.cs
index 326d4d51b04..5d5477a7d48 100644
--- a/src/System.Management.Automation/namespaces/ProviderBase.cs
+++ b/src/System.Management.Automation/namespaces/ProviderBase.cs
@@ -259,9 +259,7 @@ internal void GetProperty(
{
Context = cmdletProviderContext;
- IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@@ -299,9 +297,7 @@ internal object GetPropertyDynamicParameters(
{
Context = cmdletProviderContext;
- IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IPropertyCmdletProvider propertyProvider))
{
return null;
}
@@ -330,9 +326,7 @@ internal void SetProperty(
{
Context = cmdletProviderContext;
- IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@@ -370,9 +364,7 @@ internal object SetPropertyDynamicParameters(
{
Context = cmdletProviderContext;
- IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IPropertyCmdletProvider propertyProvider))
{
return null;
}
@@ -404,9 +396,7 @@ internal void ClearProperty(
{
Context = cmdletProviderContext;
- IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@@ -444,9 +434,7 @@ internal object ClearPropertyDynamicParameters(
{
Context = cmdletProviderContext;
- IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IPropertyCmdletProvider propertyProvider))
{
return null;
}
@@ -490,9 +478,7 @@ internal void NewProperty(
{
Context = cmdletProviderContext;
- IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@@ -537,9 +523,7 @@ internal object NewPropertyDynamicParameters(
{
Context = cmdletProviderContext;
- IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
return null;
}
@@ -571,9 +555,7 @@ internal void RemoveProperty(
{
Context = cmdletProviderContext;
- IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@@ -610,9 +592,7 @@ internal object RemovePropertyDynamicParameters(
{
Context = cmdletProviderContext;
- IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
return null;
}
@@ -648,9 +628,7 @@ internal void RenameProperty(
{
Context = cmdletProviderContext;
- IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@@ -691,9 +669,7 @@ internal object RenamePropertyDynamicParameters(
{
Context = cmdletProviderContext;
- IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
return null;
}
@@ -733,9 +709,7 @@ internal void CopyProperty(
{
Context = cmdletProviderContext;
- IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@@ -780,9 +754,7 @@ internal object CopyPropertyDynamicParameters(
{
Context = cmdletProviderContext;
- IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
return null;
}
@@ -822,9 +794,7 @@ internal void MoveProperty(
{
Context = cmdletProviderContext;
- IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@@ -869,9 +839,7 @@ internal object MovePropertyDynamicParameters(
{
Context = cmdletProviderContext;
- IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
-
- if (propertyProvider == null)
+ if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
return null;
}
@@ -902,9 +870,7 @@ internal IContentReader GetContentReader(
{
Context = cmdletProviderContext;
- IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
-
- if (contentProvider == null)
+ if (!(this is IContentCmdletProvider contentProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@@ -937,9 +903,7 @@ internal object GetContentReaderDynamicParameters(
{
Context = cmdletProviderContext;
- IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
-
- if (contentProvider == null)
+ if (!(this is IContentCmdletProvider contentProvider))
{
return null;
}
@@ -966,9 +930,7 @@ internal IContentWriter GetContentWriter(
{
Context = cmdletProviderContext;
- IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
-
- if (contentProvider == null)
+ if (!(this is IContentCmdletProvider contentProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@@ -1001,9 +963,7 @@ internal object GetContentWriterDynamicParameters(
{
Context = cmdletProviderContext;
- IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
-
- if (contentProvider == null)
+ if (!(this is IContentCmdletProvider contentProvider))
{
return null;
}
@@ -1027,9 +987,7 @@ internal void ClearContent(
{
Context = cmdletProviderContext;
- IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
-
- if (contentProvider == null)
+ if (!(this is IContentCmdletProvider contentProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@@ -1062,9 +1020,7 @@ internal object ClearContentDynamicParameters(
{
Context = cmdletProviderContext;
- IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
-
- if (contentProvider == null)
+ if (!(this is IContentCmdletProvider contentProvider))
{
return null;
}
diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs
index 5866e3d52f9..a07eb4ab692 100644
--- a/src/System.Management.Automation/utils/PsUtils.cs
+++ b/src/System.Management.Automation/utils/PsUtils.cs
@@ -386,8 +386,7 @@ internal static Hashtable EvaluatePowerShellDataFile(
ex.Message);
}
- var retResult = evaluationResult as Hashtable;
- if (retResult == null)
+ if (!(evaluationResult is Hashtable retResult))
{
throw PSTraceSource.NewInvalidOperationException(
ParserStrings.InvalidPowerShellDataFile,
@@ -539,16 +538,14 @@ internal static object[] Base64ToArgsConverter(string base64)
throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter);
}
- PSObject mo = dso as PSObject;
- if (mo == null)
+ if (!(dso is PSObject mo))
{
// This helper function should move the host. Provide appropriate error message.
// Format of args parameter is not correct.
throw PSTraceSource.NewArgumentException(MinishellParameterBinderController.ArgsParameter);
}
- var argsList = mo.BaseObject as ArrayList;
- if (argsList == null)
+ if (!(mo.BaseObject is ArrayList argsList))
{
// This helper function should move the host. Provide appropriate error message.
// Format of args parameter is not correct.
diff --git a/src/System.Management.Automation/utils/RuntimeException.cs b/src/System.Management.Automation/utils/RuntimeException.cs
index 3a2cbd5c05f..c9bbd8d2cf7 100644
--- a/src/System.Management.Automation/utils/RuntimeException.cs
+++ b/src/System.Management.Automation/utils/RuntimeException.cs
@@ -241,8 +241,7 @@ internal static string RetrieveMessage(Exception e)
if (e == null)
return string.Empty;
- IContainsErrorRecord icer = e as IContainsErrorRecord;
- if (icer == null)
+ if (!(e is IContainsErrorRecord icer))
return e.Message;
ErrorRecord er = icer.ErrorRecord;
if (er == null)