Apply IDE0019: InlineAsTypeCheck in Microsoft.PowerShell.Commands (#19688)

This commit is contained in:
Dmitry Volodin
2023-05-25 09:28:59 +05:00
committed by GitHub
parent 51da40a9fd
commit fa64ecba70
24 changed files with 74 additions and 155 deletions
@@ -1187,8 +1187,7 @@ namespace Microsoft.PowerShell.Commands
//
// Build xpath for <Suppress>
//
Hashtable suppresshash = hash[hashkey_supress_lc] as Hashtable;
if (suppresshash != null)
if (hash[hashkey_supress_lc] is Hashtable suppresshash)
{
xpathStringSuppress = BuildXPathFromHashTable(suppresshash);
}
@@ -1255,8 +1254,7 @@ namespace Microsoft.PowerShell.Commands
private static string HandleEventIdHashValue(object value)
{
StringBuilder ret = new();
Array idsArray = value as Array;
if (idsArray != null)
if (value is Array idsArray)
{
ret.Append('(');
for (int i = 0; i < idsArray.Length; i++)
@@ -1285,8 +1283,7 @@ namespace Microsoft.PowerShell.Commands
private static string HandleLevelHashValue(object value)
{
StringBuilder ret = new();
Array levelsArray = value as Array;
if (levelsArray != null)
if (value is Array levelsArray)
{
ret.Append('(');
for (int i = 0; i < levelsArray.Length; i++)
@@ -1317,8 +1314,7 @@ namespace Microsoft.PowerShell.Commands
long keywordsMask = 0;
long keywordLong = 0;
Array keywordArray = value as Array;
if (keywordArray != null)
if (value is Array keywordArray)
{
foreach (object keyword in keywordArray)
{
@@ -1473,8 +1469,7 @@ namespace Microsoft.PowerShell.Commands
private static string HandleDataHashValue(object value)
{
StringBuilder ret = new();
Array dataArray = value as Array;
if (dataArray != null)
if (value is Array dataArray)
{
ret.Append('(');
for (int i = 0; i < dataArray.Length; i++)
@@ -1504,8 +1499,7 @@ namespace Microsoft.PowerShell.Commands
private static string HandleNamedDataHashValue(string key, object value)
{
StringBuilder ret = new();
Array dataArray = value as Array;
if (dataArray != null)
if (value is Array dataArray)
{
ret.Append('(');
for (int i = 0; i < dataArray.Length; i++)
@@ -1752,8 +1746,7 @@ namespace Microsoft.PowerShell.Commands
}
else
{
Array eltArray = value as Array;
if (eltArray != null)
if (value is Array eltArray)
{
foreach (object elt in eltArray)
{
@@ -491,8 +491,7 @@ namespace Microsoft.PowerShell.Cmdletization
return this.Session;
}
var sessionBoundQueryBuilder = queryBuilder as ISessionBoundQueryBuilder<TSession>;
if (sessionBoundQueryBuilder != null)
if (queryBuilder is ISessionBoundQueryBuilder<TSession> sessionBoundQueryBuilder)
{
TSession sessionOfTheQueryBuilder = sessionBoundQueryBuilder.GetTargetSession();
if (sessionOfTheQueryBuilder != null)
@@ -98,16 +98,14 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
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(message, inner);
var containsErrorRecord = inner as IContainsErrorRecord;
if (containsErrorRecord != null)
if (inner is IContainsErrorRecord containsErrorRecord)
{
cimJobException.InitializeErrorRecord(
jobContext,
@@ -356,8 +354,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
{
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;
}
@@ -66,8 +66,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
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 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
}
}
var cimInstance = dotNetValue as CimInstance;
if (cimInstance != null)
if (dotNetValue is CimInstance cimInstance)
{
CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session);
}
@@ -191,15 +189,13 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
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;
@@ -53,8 +53,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
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)
@@ -623,8 +623,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
}
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;
@@ -1013,8 +1012,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
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;
}
@@ -36,8 +36,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
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 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
}
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 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
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);
@@ -903,8 +903,7 @@ namespace Microsoft.PowerShell.Commands
}
catch (InvalidOperationException e)
{
Win32Exception eInner = e.InnerException as Win32Exception;
if (eInner == null
if (e.InnerException is not Win32Exception eInner
|| eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_ALREADY_RUNNING)
{
exception = e;
@@ -1020,9 +1019,7 @@ namespace Microsoft.PowerShell.Commands
}
catch (InvalidOperationException e)
{
Win32Exception eInner =
e.InnerException as Win32Exception;
if (eInner == null
if (e.InnerException is not Win32Exception eInner
|| eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_NOT_ACTIVE)
{
exception = e;
@@ -1117,8 +1114,7 @@ namespace Microsoft.PowerShell.Commands
}
catch (InvalidOperationException e)
{
Win32Exception eInner = e.InnerException as Win32Exception;
if (eInner != null
if (e.InnerException is Win32Exception eInner
&& eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE)
{
serviceNotRunning = true;
@@ -1198,8 +1194,7 @@ namespace Microsoft.PowerShell.Commands
}
catch (InvalidOperationException e)
{
Win32Exception eInner = e.InnerException as Win32Exception;
if (eInner != null
if (e.InnerException is Win32Exception eInner
&& eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE)
{
serviceNotRunning = true;
@@ -560,9 +560,8 @@ namespace Microsoft.PowerShell.Commands
{
protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
{
string notePropertyName = arguments as string;
PSMemberTypes memberType;
if (notePropertyName != null && LanguagePrimitives.TryConvertTo<PSMemberTypes>(notePropertyName, out memberType))
if (arguments is string notePropertyName && LanguagePrimitives.TryConvertTo<PSMemberTypes>(notePropertyName, out memberType))
{
switch (memberType)
{
@@ -502,9 +502,8 @@ namespace Microsoft.PowerShell.Commands
MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
string Message = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]);
WarningRecord record = new(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo)
{
record.SetInvocationInfo(invocationInfo);
}
@@ -553,16 +552,14 @@ namespace Microsoft.PowerShell.Commands
foreach (MshParameter p in mshParams)
{
COLTag.Append("<col");
string width = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string;
if (width != null)
if (p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) is string width)
{
COLTag.Append(" width = \"");
COLTag.Append(width);
COLTag.Append('"');
}
string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string;
if (alignment != null)
if (p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) is string alignment)
{
COLTag.Append(" align = \"");
COLTag.Append(alignment);
@@ -608,8 +605,7 @@ namespace Microsoft.PowerShell.Commands
private static void WritePropertyName(StringBuilder Listtag, MshParameter p)
{
// for writing the property name
string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string;
if (label != null)
if (p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) is string label)
{
Listtag.Append(label);
}
@@ -338,8 +338,7 @@ namespace System.Management.Automation
Dbg.Assert(source != null, "caller should validate the parameter");
bool sourceHandled = false;
PSObject moSource = source as PSObject;
if (moSource != null && !moSource.ImmediateBaseObjectIsEmpty)
if (source is PSObject moSource && !moSource.ImmediateBaseObjectIsEmpty)
{
// Check if baseObject is primitive known type
object baseObject = moSource.ImmediateBaseObject;
@@ -407,8 +407,7 @@ namespace Microsoft.PowerShell.Commands
private void HandleRunspaceAvailabilityChanged(object sender, RunspaceAvailabilityEventArgs e)
{
// Ignore nested commands.
LocalRunspace localRunspace = sender as LocalRunspace;
if (localRunspace != null)
if (sender is LocalRunspace localRunspace)
{
var basePowerShell = localRunspace.GetCurrentBasePowerShell();
if ((basePowerShell != null) && (basePowerShell.IsNested))
@@ -438,8 +437,7 @@ namespace Microsoft.PowerShell.Commands
private void HandlePipelineOutputDataReady(object sender, EventArgs e)
{
PipelineReader<PSObject> reader = sender as PipelineReader<PSObject>;
if (reader != null && reader.IsOpen)
if (sender is PipelineReader<PSObject> reader && reader.IsOpen)
{
WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Output);
}
@@ -447,8 +445,7 @@ namespace Microsoft.PowerShell.Commands
private void HandlePipelineErrorDataReady(object sender, EventArgs e)
{
PipelineReader<object> reader = sender as PipelineReader<object>;
if (reader != null && reader.IsOpen)
if (sender is PipelineReader<object> reader && reader.IsOpen)
{
WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Error);
}
@@ -538,8 +535,7 @@ namespace Microsoft.PowerShell.Commands
// 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
{
@@ -552,8 +548,7 @@ namespace Microsoft.PowerShell.Commands
private static 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;
}
@@ -33,15 +33,13 @@ namespace Microsoft.PowerShell.Commands
// 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)
@@ -180,8 +180,7 @@ namespace Microsoft.PowerShell.Commands
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)
@@ -71,8 +71,7 @@ namespace Microsoft.PowerShell.Commands
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(
@@ -69,8 +69,7 @@ namespace Microsoft.PowerShell.Commands
if (token != null)
{
FieldPropertyToken fpt = token as FieldPropertyToken;
if (fpt != null)
if (token is FieldPropertyToken fpt)
{
// If Database does not provide a label(DisplayName) for the current property, use the expression value instead.
displayName ??= fpt.expression.expressionValue;
@@ -98,8 +97,7 @@ namespace Microsoft.PowerShell.Commands
}
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);
@@ -139,22 +139,19 @@ namespace Microsoft.PowerShell.Commands
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)
@@ -230,8 +230,7 @@ namespace Microsoft.PowerShell.Commands
{
if (!Force)
{
PSMethod memberAsPSMethod = member as PSMethod;
if ((memberAsPSMethod != null) && (memberAsPSMethod.IsSpecial))
if ((member is PSMethod memberAsPSMethod) && (memberAsPSMethod.IsSpecial))
{
continue;
}
@@ -726,8 +726,7 @@ namespace Microsoft.PowerShell.Commands
//
// 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)))
{
@@ -1575,8 +1574,7 @@ namespace Microsoft.PowerShell.Commands
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);
@@ -1942,20 +1940,17 @@ namespace Microsoft.PowerShell.Commands
/// <returns>Connection URI associated with the remote runspace.</returns>
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;
}
@@ -2244,8 +2239,7 @@ function Get-PSImplicitRemotingSessionOption
{
StringBuilder result = new("& $script:NewPSSessionOption ");
RunspaceConnectionInfo runspaceConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as RunspaceConnectionInfo;
if (runspaceConnectionInfo != null)
if (_remoteRunspaceInfo.Runspace.ConnectionInfo is RunspaceConnectionInfo runspaceConnectionInfo)
{
result.Append(null, $"-Culture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.Culture.ToString())}' ");
result.Append(null, $"-UICulture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.UICulture.ToString())}' ");
@@ -2256,8 +2250,7 @@ function Get-PSImplicitRemotingSessionOption
result.Append(null, $"-OperationTimeOut {runspaceConnectionInfo.OperationTimeout} ");
}
WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo;
if (wsmanConnectionInfo != null)
if (_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo)
{
if (!wsmanConnectionInfo.UseCompression)
{
@@ -2522,8 +2515,7 @@ function Get-PSImplicitRemotingSession
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(
@@ -2535,8 +2527,7 @@ function Get-PSImplicitRemotingSession
}
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(
@@ -2578,19 +2569,16 @@ function Get-PSImplicitRemotingSession
/// <returns></returns>
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,
@@ -571,15 +571,13 @@ namespace Microsoft.PowerShell.Commands
}
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);
}
@@ -626,9 +624,8 @@ namespace Microsoft.PowerShell.Commands
}
bool wasDictionary = true;
IDictionary dict = obj as IDictionary;
if (dict == null)
if (obj is not IDictionary dict)
{
wasDictionary = false;
dict = new Dictionary<string, object>();
@@ -33,15 +33,11 @@ namespace Microsoft.PowerShell.Commands
// 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(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo)
{
record.SetInvocationInfo(invocationInfo);
}
@@ -81,15 +77,11 @@ namespace Microsoft.PowerShell.Commands
// 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(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo)
{
record.SetInvocationInfo(invocationInfo);
}
@@ -129,15 +121,11 @@ namespace Microsoft.PowerShell.Commands
// 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(Message);
InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;
if (invocationInfo != null)
if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo)
{
record.SetInvocationInfo(invocationInfo);
}
@@ -361,8 +349,7 @@ namespace Microsoft.PowerShell.Commands
// 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;
@@ -51,9 +51,7 @@ namespace Microsoft.PowerShell.Commands
{
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)
@@ -61,7 +59,7 @@ namespace Microsoft.PowerShell.Commands
return s;
}
}
else if ((enumerable = o as IEnumerable) != null)
else if (o is IEnumerable enumerable)
{
// unroll enumerables, including arrays.
@@ -764,12 +764,10 @@ namespace Microsoft.PowerShell.Commands
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)
{
@@ -512,8 +512,7 @@ namespace Microsoft.PowerShell.Commands
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)
@@ -522,8 +521,7 @@ namespace Microsoft.PowerShell.Commands
}
}
ErrorRecord errorRecordResult = obj as ErrorRecord;
if (errorRecordResult != null)
if (obj is ErrorRecord errorRecordResult)
{
result = errorRecordResult;
}