Fix RCS1221: Use pattern matching instead of combination of 'as' operator and null check (#13333)

* Autofix RCS1221: Use pattern matching instead of combination of 'as' operator and null check

https://github.com/JosefPihrt/Roslynator/blob/master/docs/analyzers/RCS1221.md

* Restore stripped comments
This commit is contained in:
xtqqczze 2020-11-05 16:58:48 +00:00 committed by GitHub
parent 03a58c4186
commit 76cef3b299
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
74 changed files with 175 additions and 416 deletions

View file

@ -388,8 +388,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets
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 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets
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;
}

View file

@ -2077,8 +2077,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets
}
CimWriteResultObject writeResultObject = args.Action as CimWriteResultObject;
CimClass cimClass = writeResultObject.Result as CimClass;
if (cimClass == null)
if (!(writeResultObject.Result is CimClass cimClass))
{
return true;
}
@ -2231,8 +2230,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets
}
CimWriteResultObject writeResultObject = args.Action as CimWriteResultObject;
CimInstance cimInstance = writeResultObject.Result as CimInstance;
if (cimInstance == null)
if (!(writeResultObject.Result is CimInstance cimInstance))
{
return true;
}

View file

@ -84,8 +84,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
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 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
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;
}

View file

@ -172,8 +172,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
/// <returns><see cref="System.Management.Automation.Job"/> object that performs a query against the wrapped object model.</returns>
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));
}

View file

@ -572,8 +572,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
{
try
{
var expectedComparable = expectedPropertyValue as IComparable;
if (expectedComparable == null)
if (!(expectedPropertyValue is IComparable expectedComparable))
{
return false;
}
@ -608,8 +607,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
{
try
{
var actualComparable = actualPropertyValue as IComparable;
if (actualComparable == null)
if (!(actualPropertyValue is IComparable actualComparable))
{
return false;
}

View file

@ -710,8 +710,7 @@ namespace System.Management.Automation
continue;
}
PSPropertyInfo property = info as PSPropertyInfo;
if (property == null)
if (!(info is PSPropertyInfo property))
{
continue;
}

View file

@ -48,8 +48,7 @@ namespace Microsoft.PowerShell.Commands
/// <returns>The source string limited in the number of lines.</returns>
internal static object LimitString(object src)
{
string srcString = src as string;
if (srcString == null)
if (!(src is string srcString))
{
return src;
}

View file

@ -120,9 +120,7 @@ namespace Microsoft.PowerShell.Commands
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 @@ namespace Microsoft.PowerShell.Commands
Variable,
delegate (Breakpoint breakpoint, string variable)
{
VariableBreakpoint variableBreakpoint = breakpoint as VariableBreakpoint;
if (variableBreakpoint == null)
if (!(breakpoint is VariableBreakpoint variableBreakpoint))
{
return false;
}

View file

@ -2623,8 +2623,7 @@ function Get-PSImplicitRemotingSession
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 @@ function Get-PSImplicitRemotingSession
return string.Empty;
}
WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo;
if (wsmanConnectionInfo == null)
if (!(_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo))
{
return string.Empty;
}

View file

@ -77,8 +77,7 @@ namespace Microsoft.PowerShell.Commands
/// <returns>True if both the objects are same or else returns false.</returns>
public override bool Equals(object inputObject)
{
ObjectCommandPropertyValue objectCommandPropertyValueObject = inputObject as ObjectCommandPropertyValue;
if (objectCommandPropertyValueObject == null)
if (!(inputObject is ObjectCommandPropertyValue objectCommandPropertyValueObject))
{
return false;
}

View file

@ -358,9 +358,7 @@ namespace Microsoft.PowerShell.Commands
return null;
}
PSPropertySet defaultKeys = standardNames.Members["DefaultKeyPropertySet"] as PSPropertySet;
if (defaultKeys == null)
if (!(standardNames.Members["DefaultKeyPropertySet"] is PSPropertySet defaultKeys))
{
return null;
}

View file

@ -633,9 +633,7 @@ namespace Microsoft.PowerShell.Commands
/// </returns>
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;
}

View file

@ -208,8 +208,7 @@ namespace Microsoft.PowerShell.Commands
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 @@ namespace Microsoft.PowerShell.Commands
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 @@ namespace Microsoft.PowerShell.Commands
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));
}

View file

@ -602,9 +602,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
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

View file

@ -55,9 +55,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
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 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
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

View file

@ -285,8 +285,7 @@ namespace Microsoft.PowerShell.Cim
/// <returns></returns>
public override Collection<string> 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 @@ namespace Microsoft.PowerShell.Cim
return false;
}
CimProperty cimProperty = adaptedProperty.Tag as CimProperty;
if (cimProperty == null)
if (!(adaptedProperty.Tag is CimProperty cimProperty))
{
return false;
}

View file

@ -67,9 +67,7 @@ namespace System.Management.Automation
else
temp = result;
PSReference reference = temp as PSReference;
if (reference == null)
if (!(temp is PSReference reference))
{
throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null,
ExtendedTypeSystem.ReferenceTypeExpected);

View file

@ -839,8 +839,7 @@ namespace System.Management.Automation
/// <exception cref="ArgumentException">For invalid arguments.</exception>
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 @@ namespace System.Management.Automation
Metadata.ValidateNotNullFailure);
}
var path = arguments as string;
if (path == null)
if (!(arguments is string path))
{
throw new ValidationMetadataException(
"PathArgumentIsNotValid",

View file

@ -626,8 +626,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
{
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 @@ namespace System.Management.Automation
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))

View file

@ -239,8 +239,7 @@ namespace System.Management.Automation
if (lastAst.Parent is CommandExpressionAst)
{
// Handle "switch -file m<tab>" or "switch -file *.ps1<tab>"
var pipeline = lastAst.Parent.Parent as PipelineAst;
if (pipeline == null)
if (!(lastAst.Parent.Parent is PipelineAst pipeline))
{
return false;
}

View file

@ -542,8 +542,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
continue;
}
string childNamespace = namespaceNameProperty.Value as string;
if (childNamespace == null)
if (!(namespaceNameProperty.Value is string childNamespace))
{
continue;
}
@ -3793,8 +3791,7 @@ namespace System.Management.Automation
{
// Command is something like where-object/foreach-object/format-list/etc. where there is a parameter that is a property name
// and we want member names based on the input object, which is either the parameter InputObject, or comes from the pipeline.
var pipelineAst = commandAst.Parent as PipelineAst;
if (pipelineAst == null)
if (!(commandAst.Parent is PipelineAst pipelineAst))
return;
int i;
@ -4973,8 +4970,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
var varValues = new List<string>();
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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))

View file

@ -101,8 +101,7 @@ namespace System.Management.Automation
/// </exception>
internal ParameterBinderController NewParameterBinderController(InternalCommand command)
{
Cmdlet cmdlet = command as Cmdlet;
if (cmdlet == null)
if (!(command is Cmdlet cmdlet))
{
throw PSTraceSource.NewArgumentException(nameof(command));
}

View file

@ -1658,8 +1658,7 @@ namespace System.Management.Automation
// 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 @@ namespace System.Management.Automation
private static bool PropertyIsStatic(PSProperty property)
{
PropertyCacheEntry entry = property.adapterData as PropertyCacheEntry;
if (entry == null)
if (!(property.adapterData is PropertyCacheEntry entry))
{
return false;
}

View file

@ -1666,8 +1666,7 @@ namespace System.Management.Automation
return commandInfo.Name;
}
CmdletInfo cmdletInfo = commandInfo as CmdletInfo;
if (cmdletInfo == null)
if (!(commandInfo is CmdletInfo cmdletInfo))
{
return string.Empty;
}

View file

@ -2008,8 +2008,7 @@ namespace Microsoft.PowerShell.Commands
private object GetLikeRHSOperand(object operand)
{
var val = operand as string;
if (val == null)
if (!(operand is string val))
{
return operand;
}

View file

@ -637,8 +637,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
// 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 @@ namespace System.Management.Automation
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,

View file

@ -172,9 +172,7 @@ namespace System.Management.Automation
{
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 @@ namespace System.Management.Automation
/// <param name="convertIfPossible">Instructs the adapter to convert before setting, if the adapter supports conversion.</param>
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,

View file

@ -194,8 +194,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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)

View file

@ -2321,8 +2321,7 @@ namespace System.Management.Automation
{
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)

View file

@ -588,9 +588,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
/// </summary>
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 @@ namespace System.Management.Automation
/// <returns></returns>
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 @@ namespace System.Management.Automation
settings.ReplicateInstance(ownerObject);
}
PSNoteProperty note = settings.Members[noteName] as PSNoteProperty;
if (note == null)
if (!(settings.Members[noteName] is PSNoteProperty note))
{
return defaultValue;
}

View file

@ -218,8 +218,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
/// <returns>True if the Instance property of <paramref name="obj"/> is equal to the current Instance; otherwise, false.</returns>
public override bool Equals(object obj)
{
PSObjectTypeDescriptor other = obj as PSObjectTypeDescriptor;
if (other == null)
if (!(obj is PSObjectTypeDescriptor other))
{
return false;
}

View file

@ -844,8 +844,7 @@ namespace System.Management.Automation
return 1;
}
var v = version as SemanticVersion;
if (v == null)
if (!(version is SemanticVersion v))
{
throw PSTraceSource.NewArgumentException(nameof(version));
}

View file

@ -1841,9 +1841,7 @@ namespace System.Management.Automation
return;
}
string childName = childNameObjects[index].BaseObject as string;
if (childName == null)
if (!(childNameObjects[index].BaseObject is string childName))
{
continue;
}
@ -2588,9 +2586,7 @@ namespace System.Management.Automation
return;
}
string name = result.BaseObject as string;
if (name == null)
if (!(result.BaseObject is string name))
{
continue;
}
@ -2638,9 +2634,7 @@ namespace System.Management.Automation
return;
}
string name = result.BaseObject as string;
if (name == null)
if (!(result.BaseObject is string name))
{
continue;
}

View file

@ -350,10 +350,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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);

View file

@ -35,10 +35,7 @@ namespace System.Management.Automation
throw PSTraceSource.NewArgumentNullException(nameof(providerInstance));
}
ISecurityDescriptorCmdletProvider permissionCmdletProvider =
providerInstance as ISecurityDescriptorCmdletProvider;
if (permissionCmdletProvider == null)
if (!(providerInstance is ISecurityDescriptorCmdletProvider permissionCmdletProvider))
{
throw
PSTraceSource.NewNotSupportedException(

View file

@ -3970,8 +3970,7 @@ namespace System.Management.Automation.Runspaces
}
PSMemberSet settings = typeMembers[PSStandardMembers] as PSMemberSet;
PSPropertySet typeProperties = settings?.Members[PropertySerializationSet] as PSPropertySet;
if (typeProperties == null)
if (!(settings?.Members[PropertySerializationSet] is PSPropertySet typeProperties))
{
continue;
}

View file

@ -1674,8 +1674,7 @@ namespace System.Management.Automation
try
{
var scriptBlock = ScriptBlock.Create(command);
var scriptBlockAst = scriptBlock.Ast as ScriptBlockAst;
if (scriptBlockAst == null)
if (!(scriptBlock.Ast is ScriptBlockAst scriptBlockAst))
{
return false;
}

View file

@ -2319,8 +2319,7 @@ namespace System.Management.Automation
//
// 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 @@ namespace System.Management.Automation
}
// 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 @@ namespace System.Management.Automation
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)

View file

@ -1434,8 +1434,7 @@ namespace Microsoft.PowerShell.Commands
break;
}
// Read CommandLine property
string commandLine = GetPropertyValue(mshObject, "CommandLine") as string;
if (commandLine == null)
if (!(GetPropertyValue(mshObject, "CommandLine") is string commandLine))
{
break;
}

View file

@ -309,8 +309,7 @@ namespace System.Management.Automation
internal static List<string> GetSuggestion(Runspace runspace)
{
LocalRunspace localRunspace = runspace as LocalRunspace;
if (localRunspace == null) { return new List<string>(); }
if (!(runspace is LocalRunspace localRunspace)) { return new List<string>(); }
// Get the last value of $?
bool questionMarkVariableValue = localRunspace.ExecutionContext.QuestionMarkVariableValue;

View file

@ -448,8 +448,7 @@ namespace System.Management.Automation.Internal.Host
/// </summary>
private IHostSupportsInteractiveSession GetIHostSupportsInteractiveSession()
{
IHostSupportsInteractiveSession host = _externalHostRef.Value as IHostSupportsInteractiveSession;
if (host == null)
if (!(_externalHostRef.Value is IHostSupportsInteractiveSession host))
{
throw new PSNotImplementedException();
}

View file

@ -219,8 +219,7 @@ namespace System.Management.Automation
collectionToUpdate = PSObject.Base(collectionToUpdate);
IList list = collectionToUpdate as IList;
if (list == null)
if (!(collectionToUpdate is IList list))
{
throw PSTraceSource.NewInvalidOperationException(PSListModifierStrings.UpdateFailed);
}

View file

@ -336,9 +336,7 @@ namespace System.Management.Automation
throw PSTraceSource.NewArgumentNullException(nameof(info));
}
IList<T> listToUse = info.GetValue("Data", typeof(IList<T>)) as IList<T>;
if (listToUse == null)
if (!(info.GetValue("Data", typeof(IList<T>)) is IList<T> listToUse))
{
throw PSTraceSource.NewArgumentNullException(nameof(info));
}

View file

@ -1370,9 +1370,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
/// </exception>
private IAsyncResult BeginBatchInvoke<TInput, TOutput>(PSDataCollection<TInput> input, PSDataCollection<TOutput> output, PSInvocationSettings settings, AsyncCallback callback, object state)
{
PSDataCollection<PSObject> asyncOutput = (object)output as PSDataCollection<PSObject>;
if (asyncOutput == null)
if (!((object)output is PSDataCollection<PSObject> asyncOutput))
{
throw PSTraceSource.NewInvalidOperationException();
}

View file

@ -1297,8 +1297,7 @@ namespace System.Management.Automation.Interpreter
private void DefineBlockLabels(Expression node)
{
var block = node as BlockExpression;
if (block == null)
if (!(node is BlockExpression block))
{
return;
}

View file

@ -1466,8 +1466,7 @@ namespace System.Management.Automation
return string.Empty;
}
PSObject mshObj = obj as PSObject;
if (mshObj == null)
if (!(obj is PSObject mshObj))
{
return obj.GetType().FullName;
}
@ -1571,9 +1570,7 @@ namespace System.Management.Automation
// 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);

View file

@ -5933,14 +5933,12 @@ namespace System.Management.Automation.Language
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;
}

View file

@ -160,8 +160,7 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
return false;
}
var member = memberExpressionAst.Member as StringConstantExpressionAst;
if (member == null)
if (!(memberExpressionAst.Member is StringConstantExpressionAst member))
{
return false;
}

View file

@ -732,8 +732,7 @@ namespace System.Management.Automation.Language
return false;
}
var pipelineAst = statements[0] as PipelineAst;
if (pipelineAst == null)
if (!(statements[0] is PipelineAst pipelineAst))
{
return false;
}
@ -744,8 +743,7 @@ namespace System.Management.Automation.Language
return false;
}
var hashTableAst = expr as HashtableAst;
if (hashTableAst == null)
if (!(expr is HashtableAst hashTableAst))
{
return false;
}

View file

@ -571,8 +571,7 @@ namespace System.Management.Automation.Language
public override bool Equals(object obj)
{
IScriptExtent otherPosition = obj as IScriptExtent;
if (otherPosition == null)
if (!(obj is IScriptExtent otherPosition))
{
return false;
}

View file

@ -693,8 +693,7 @@ namespace System.Management.Automation.Language
private void CheckForReturnStatement(ReturnStatementAst ast)
{
var functionMemberAst = _memberScopeStack.Peek() as FunctionMemberAst;
if (functionMemberAst == null)
if (!(_memberScopeStack.Peek() is FunctionMemberAst functionMemberAst))
{
return;
}
@ -1592,8 +1591,7 @@ namespace System.Management.Automation.Language
foreach (var baseType in typeDefinitionAst.BaseTypes)
{
var baseTypeName = baseType.TypeName as TypeName;
if (baseTypeName == null)
if (!(baseType.TypeName is TypeName baseTypeName))
{
continue;
}

View file

@ -316,8 +316,7 @@ namespace System.Management.Automation
// 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 @@ namespace System.Management.Automation
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<PSTypeName>();
}
@ -1728,8 +1726,7 @@ namespace System.Management.Automation
PSTypeName[] exprType;
if (isStatic)
{
var exprAsType = expression as TypeExpressionAst;
if (exprAsType == null)
if (!(expression is TypeExpressionAst exprAsType))
{
return null;
}
@ -2281,8 +2278,7 @@ namespace System.Management.Automation
private void GetInferredTypeFromScriptBlockParameter(AstParameterArgumentPair argument, List<PSTypeName> inferredTypes)
{
var argumentPair = argument as AstPair;
var scriptBlockExpressionAst = argumentPair?.Argument as ScriptBlockExpressionAst;
if (scriptBlockExpressionAst == null)
if (!(argumentPair?.Argument is ScriptBlockExpressionAst scriptBlockExpressionAst))
{
return;
}

View file

@ -615,9 +615,7 @@ namespace System.Management.Automation.Language
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)

View file

@ -7213,8 +7213,7 @@ namespace System.Management.Automation.Language
PSTraceSource.NewInvalidOperationException();
}
var commandExpr = this.Parent as CommandExpressionAst;
if (commandExpr == null)
if (!(this.Parent is CommandExpressionAst commandExpr))
{
return false;
}
@ -7726,8 +7725,7 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
/// <summary/>
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 @@ namespace System.Management.Automation.Language
/// <summary/>
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 @@ namespace System.Management.Automation.Language
/// <summary/>
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 @@ namespace System.Management.Automation.Language
/// <summary/>
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;
}

View file

@ -134,8 +134,7 @@ namespace System.Management.Automation.Remoting
/// </summary>
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

View file

@ -750,12 +750,10 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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);

View file

@ -415,8 +415,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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);
}
}

View file

@ -1237,11 +1237,9 @@ namespace System.Management.Automation.Runspaces.Internal
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();
}

View file

@ -1753,8 +1753,7 @@ else
}
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);
}

View file

@ -1007,8 +1007,7 @@ namespace Microsoft.PowerShell.Commands
// 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.

View file

@ -1158,8 +1158,7 @@ namespace Microsoft.PowerShell.Commands
/// <returns>PSSession disconnected runspace object.</returns>
private PSSession TryGetSessionFromServer(PSSession session)
{
RemoteRunspace remoteRunspace = session.Runspace as RemoteRunspace;
if (remoteRunspace == null)
if (!(session.Runspace is RemoteRunspace remoteRunspace))
{
return null;
}

View file

@ -1124,8 +1124,7 @@ namespace System.Management.Automation.Runspaces
internal static T ExtractPropertyAsWsManConnectionInfo<T>(RunspaceConnectionInfo rsCI,
string property, T defaultValue)
{
WSManConnectionInfo wsCI = rsCI as WSManConnectionInfo;
if (wsCI == null)
if (!(rsCI is WSManConnectionInfo wsCI))
{
return defaultValue;
}

View file

@ -2088,8 +2088,7 @@ namespace System.Management.Automation
/// <returns>PSInvocationInfo.</returns>
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 @@ namespace System.Management.Automation
/// <returns>RemoteSessionCapability object.</returns>
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);

View file

@ -2804,9 +2804,7 @@ namespace System.Management.Automation.Remoting
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;
}

View file

@ -327,8 +327,7 @@ namespace System.Management.Automation.Remoting
throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostAlreadyPushed);
}
RemoteRunspace remoteRunspace = runspace as RemoteRunspace;
if (remoteRunspace == null)
if (!(runspace is RemoteRunspace remoteRunspace))
{
throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostNotRemoteRunspace);
}

View file

@ -193,8 +193,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
return errorHandler(AutomationExceptions.CantConvertScriptBlockWithTrap);
}
var pipeAst = statements[0] as PipelineAst;
if (pipeAst == null)
if (!(statements[0] is PipelineAst pipeAst))
{
return errorHandler(AutomationExceptions.CanOnlyConvertOnePipeline);
}

View file

@ -1280,8 +1280,7 @@ namespace System.Management.Automation
}
catch (Exception exception)
{
var rte = exception as RuntimeException;
if (rte == null)
if (!(exception is RuntimeException rte))
{
throw ExceptionHandlingOps.ConvertToRuntimeException(exception, functionDefinitionAst.Extent);
}

View file

@ -386,8 +386,7 @@ namespace System.Management.Automation
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);

View file

@ -1982,8 +1982,7 @@ namespace System.Management.Automation
foreach (PSMemberInfo info in propertyCollection)
{
PSProperty prop = info as PSProperty;
if (prop == null)
if (!(info is PSProperty prop))
{
continue;
}
@ -3331,32 +3330,28 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
{
foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.AdaptedMembers)
{
PSPropertyInfo deserializedProperty = deserializedMemberInfo as PSPropertyInfo;
if (deserializedProperty == null)
if (!(deserializedMemberInfo is PSPropertyInfo deserializedProperty))
{
continue;
}
@ -3494,8 +3488,7 @@ namespace System.Management.Automation
// 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 @@ namespace Microsoft.PowerShell
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 @@ namespace Microsoft.PowerShell
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 @@ namespace Microsoft.PowerShell
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));
}

View file

@ -765,9 +765,7 @@ namespace System.Management.Automation
if (helpInfo == null)
return;
MamlCommandHelpInfo commandHelpInfo = helpInfo as MamlCommandHelpInfo;
if (commandHelpInfo == null)
if (!(helpInfo is MamlCommandHelpInfo commandHelpInfo))
return;
commandHelpInfo.AddUserDefinedData(userDefinedHelpData);

View file

@ -108,11 +108,9 @@ namespace System.Management.Automation
// 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;
}

View file

@ -258,9 +258,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@ -298,9 +296,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IPropertyCmdletProvider propertyProvider))
{
return null;
}
@ -329,9 +325,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@ -369,9 +363,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IPropertyCmdletProvider propertyProvider))
{
return null;
}
@ -403,9 +395,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@ -443,9 +433,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IPropertyCmdletProvider propertyProvider))
{
return null;
}
@ -489,9 +477,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@ -536,9 +522,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
return null;
}
@ -570,9 +554,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@ -609,9 +591,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
return null;
}
@ -647,9 +627,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@ -690,9 +668,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
return null;
}
@ -732,9 +708,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@ -779,9 +753,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
return null;
}
@ -821,9 +793,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@ -868,9 +838,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider;
if (propertyProvider == null)
if (!(this is IDynamicPropertyCmdletProvider propertyProvider))
{
return null;
}
@ -901,9 +869,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
if (contentProvider == null)
if (!(this is IContentCmdletProvider contentProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@ -936,9 +902,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
if (contentProvider == null)
if (!(this is IContentCmdletProvider contentProvider))
{
return null;
}
@ -965,9 +929,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
if (contentProvider == null)
if (!(this is IContentCmdletProvider contentProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@ -1000,9 +962,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
if (contentProvider == null)
if (!(this is IContentCmdletProvider contentProvider))
{
return null;
}
@ -1026,9 +986,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
if (contentProvider == null)
if (!(this is IContentCmdletProvider contentProvider))
{
throw
PSTraceSource.NewNotSupportedException(
@ -1061,9 +1019,7 @@ namespace System.Management.Automation.Provider
{
Context = cmdletProviderContext;
IContentCmdletProvider contentProvider = this as IContentCmdletProvider;
if (contentProvider == null)
if (!(this is IContentCmdletProvider contentProvider))
{
return null;
}

View file

@ -386,8 +386,7 @@ namespace System.Management.Automation
ex.Message);
}
var retResult = evaluationResult as Hashtable;
if (retResult == null)
if (!(evaluationResult is Hashtable retResult))
{
throw PSTraceSource.NewInvalidOperationException(
ParserStrings.InvalidPowerShellDataFile,
@ -539,16 +538,14 @@ namespace System.Management.Automation
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.

View file

@ -240,8 +240,7 @@ namespace System.Management.Automation
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)