diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs index dc11617d89ed09..b559a7f2075f56 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs @@ -793,21 +793,21 @@ internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr fieldHandle = default; object handle = m_scope[token] ?? throw new InvalidProgramException(); - if (handle is RuntimeTypeHandle) + if (handle is RuntimeTypeHandle runtimeTypeHandle) { - typeHandle = ((RuntimeTypeHandle)handle).Value; + typeHandle = runtimeTypeHandle.Value; return; } - if (handle is RuntimeMethodHandle) + if (handle is RuntimeMethodHandle runtimeMethodHandle) { - methodHandle = ((RuntimeMethodHandle)handle).Value; + methodHandle = runtimeMethodHandle.Value; return; } - if (handle is RuntimeFieldHandle) + if (handle is RuntimeFieldHandle runtimeFieldHandle) { - fieldHandle = ((RuntimeFieldHandle)handle).Value; + fieldHandle = runtimeFieldHandle.Value; return; } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs index fdeb781f4575de..dc4f91cbd3651e 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs @@ -496,9 +496,9 @@ private void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst { CorElementType type = CorElementType.ELEMENT_TYPE_MAX; - if (clsArgument is RuntimeType) + if (clsArgument is RuntimeType runtimeType) { - type = ((RuntimeType)clsArgument).GetCorElementType(); + type = runtimeType.GetCorElementType(); // GetCorElementType returns CorElementType.ELEMENT_TYPE_CLASS for both object and string if (type == CorElementType.ELEMENT_TYPE_CLASS) diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs index b83ea2328385ea..2723ab2c76f5ef 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs @@ -109,9 +109,9 @@ public static unsafe int QueryContextAttributes(SafeDeleteContext phContext, Int if (status == 0 && refHandle != null) { - if (refHandle is SafeFreeContextBuffer) + if (refHandle is SafeFreeContextBuffer safeFreeContextBuffer) { - ((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer); + safeFreeContextBuffer.Set(*(IntPtr*)buffer); } else { diff --git a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs index a57f06fc3b9db1..c9bb96f28593d2 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs @@ -75,7 +75,7 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) { ArgumentNullException.ThrowIfNull(asnEncodedData); - if (!(asnEncodedData is Pkcs9AttributeObject)) + if (asnEncodedData is not Pkcs9AttributeObject) throw new ArgumentException(SR.Cryptography_Pkcs9_AttributeMismatch); base.CopyFrom(asnEncodedData); diff --git a/src/libraries/Common/src/System/Security/Cryptography/RsaPaddingProcessor.cs b/src/libraries/Common/src/System/Security/Cryptography/RsaPaddingProcessor.cs index e40fcf54ac1c7c..d978b42e220669 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RsaPaddingProcessor.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RsaPaddingProcessor.cs @@ -365,7 +365,7 @@ internal static unsafe void PadOaep( destination[0] = 0; } } - catch (Exception e) when (!(e is CryptographicException)) + catch (Exception e) when (e is not CryptographicException) { Debug.Fail("Bad exception produced from OAEP padding: " + e); throw new CryptographicException(); diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinder.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinder.cs index 4aaf894cab1f4c..f8fc175b1c2e62 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinder.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinder.cs @@ -621,7 +621,7 @@ private static ExprMemberGroup CreateMemberGroupExpr( ExprMemberGroup memgroup = ExprFactory.CreateMemGroup( // Tree flags, name, typeArgumentsAsTypeArray, kind, callingType, null, new CMemberLookupResults(TypeArray.Allocate(callingTypes.ToArray()), name)); - if (!(callingObject is ExprClass)) + if (callingObject is not ExprClass) { memgroup.OptionalObject = callingObject; } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinderExtensions.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinderExtensions.cs index 27731058c76c7c..88901236693692 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinderExtensions.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinderExtensions.cs @@ -138,7 +138,7 @@ private static bool IsGenericallyEqual(this Type t1, Type t2) // i.e if the inputs are (T, int, C, C) then this will return true. private static bool IsGenericallyEquivalentTo(this Type t1, Type t2, MemberInfo member1, MemberInfo member2) { - Debug.Assert(!(member1 is MethodBase) || + Debug.Assert(member1 is not MethodBase || !((MethodBase)member1).IsGenericMethod || (((MethodBase)member1).IsGenericMethodDefinition && ((MethodBase)member2).IsGenericMethodDefinition)); @@ -226,12 +226,12 @@ private static bool IsTypeParameterEquivalentToTypeInst(this Type typeParam, Typ { // The type param is from a generic method. Since only methods can be generic, anything else // here means they are not equivalent. - if (!(member is MethodBase)) + if (member is not MethodBase methodBase) { return false; } - MethodBase method = (MethodBase)member; + MethodBase method = methodBase; int position = typeParam.GenericParameterPosition; Type[] args = method.IsGenericMethod ? method.GetGenericArguments() : null; diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Binding/Better.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Binding/Better.cs index 29f7a6b43570ab..806338658e7055 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Binding/Better.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Binding/Better.cs @@ -213,7 +213,7 @@ private static TypeArray RearrangeNamedArguments(TypeArray pta, MethPropWithInst // If we've no args we can skip. If the last argument isn't named then either we // have no named arguments, and we can skip, or we have non-trailing named arguments // and we MUST skip! - if (args.carg == 0 || !(args.prgexpr[args.carg - 1] is ExprNamedArgumentSpecification)) + if (args.carg == 0 || args.prgexpr[args.carg - 1] is not ExprNamedArgumentSpecification) { return pta; } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs index ab1902e592592a..52305fc58c08e4 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs @@ -367,7 +367,7 @@ private bool canConvert(Expr expr, CType dest, CONVERTTYPE flags) => [RequiresDynamicCode(Binder.DynamicCodeWarning)] private Expr mustConvertCore(Expr expr, CType dest, CONVERTTYPE flags) { - Debug.Assert(!(expr is ExprMemberGroup)); + Debug.Assert(expr is not ExprMemberGroup); if (BindImplicitConversion(expr, expr.Type, dest, out Expr exprResult, flags)) { @@ -453,7 +453,7 @@ private Expr tryConvert(Expr expr, CType dest, CONVERTTYPE flags) [RequiresDynamicCode(Binder.DynamicCodeWarning)] private Expr mustCastCore(Expr expr, CType dest, CONVERTTYPE flags) { - Debug.Assert(!(expr is ExprMemberGroup)); + Debug.Assert(expr is not ExprMemberGroup); Debug.Assert(dest != null); CSemanticChecker.CheckForStaticClass(dest); @@ -1014,7 +1014,7 @@ private bool bindUserDefinedConversion(Expr exprSrc, CType typeSrc, CType typeDs Expr exprDst; Expr pTransformedArgument = exprSrc; - if (ctypeLiftBest > 0 && !(typeFrom is NullableType) && fDstHasNull) + if (ctypeLiftBest > 0 && typeFrom is not NullableType && fDstHasNull) { // Create the memgroup. ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwiBest); diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversions.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversions.cs index 220c6c76428286..510f4c7943ab03 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversions.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversions.cs @@ -185,7 +185,7 @@ public static bool FExpRefConv(CType typeSrc, CType typeDst) CType typeArr = arrayDest.ElementType; CType typeLst = aggtypeSrc.TypeArgsAll[0]; - Debug.Assert(!(typeArr is MethodGroupType)); + Debug.Assert(typeArr is not MethodGroupType); return typeArr == typeLst || FExpRefConv(typeArr, typeLst); } if (HasGenericDelegateExplicitReferenceConversion(typeSrc, typeDst)) diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExplicitConversion.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExplicitConversion.cs index d8a6dc3e751b15..d38b21f5476fb8 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExplicitConversion.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExplicitConversion.cs @@ -297,7 +297,7 @@ private bool bindExplicitConversionFromIListToArray(ArrayType arrayDest) CType typeArr = arrayDest.ElementType; CType typeLst = aggSrc.TypeArgsAll[0]; - Debug.Assert(!(typeArr is MethodGroupType)); + Debug.Assert(typeArr is not MethodGroupType); if (typeArr != typeLst && !CConversions.FExpRefConv(typeArr, typeLst)) { return false; @@ -723,7 +723,7 @@ private AggCastResult bindExplicitConversionFromPointerToInt(AggregateType aggTy // // * From any pointer-type to sbyte, byte, short, ushort, int, uint, long, or ulong. - if (!(_typeSrc is PointerType) || aggTypeDest.FundamentalType > FUNDTYPE.FT_LASTINTEGRAL || !aggTypeDest.IsNumericType) + if (_typeSrc is not PointerType || aggTypeDest.FundamentalType > FUNDTYPE.FT_LASTINTEGRAL || !aggTypeDest.IsNumericType) { return AggCastResult.Failure; } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExpressionBinder.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExpressionBinder.cs index 2f7457ba42ddd8..3afca6e5b88d3e 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExpressionBinder.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExpressionBinder.cs @@ -665,7 +665,7 @@ internal Expr bindUDUnop(ExpressionKind ek, Expr arg) private ExprCall BindLiftedUDUnop(Expr arg, CType typeArg, MethPropWithInst mpwi) { CType typeRaw = typeArg.StripNubs(); - if (!(arg.Type is NullableType) || !canConvert(arg.Type.StripNubs(), typeRaw, CONVERTTYPE.NOUDC)) + if (arg.Type is not NullableType || !canConvert(arg.Type.StripNubs(), typeRaw, CONVERTTYPE.NOUDC)) { // Convert then lift. arg = mustConvert(arg, typeArg); @@ -673,7 +673,7 @@ private ExprCall BindLiftedUDUnop(Expr arg, CType typeArg, MethPropWithInst mpwi Debug.Assert(arg.Type is NullableType); CType typeRet = TypeManager.SubstType(mpwi.Meth().RetType, mpwi.GetType()); - if (!(typeRet is NullableType)) + if (typeRet is not NullableType) { typeRet = TypeManager.GetNullable(typeRet); } @@ -792,7 +792,7 @@ private static NamedArgumentsKind FindNamedArgumentsType(Expr args) list = null; } - if (!(arg is ExprNamedArgumentSpecification)) + if (arg is not ExprNamedArgumentSpecification) { return NamedArgumentsKind.NonTrailing; } @@ -882,8 +882,8 @@ private void CheckLvalue(Expr expr, CheckLvalueKind kind) return; } - Debug.Assert(!(expr is ExprLocal)); - Debug.Assert(!(expr is ExprMemberGroup)); + Debug.Assert(expr is not ExprLocal); + Debug.Assert(expr is not ExprMemberGroup); switch (expr.Kind) { diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/GroupToArgsBinder.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/GroupToArgsBinder.cs index 6fd4483e6d73fd..fb2d1e777b1e22 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/GroupToArgsBinder.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/GroupToArgsBinder.cs @@ -434,7 +434,7 @@ internal static bool ReOrderArgsForNamedArguments( // Positional. if (index < pArguments.carg && - !(pArguments.prgexpr[index] is ExprNamedArgumentSpecification) && + pArguments.prgexpr[index] is not ExprNamedArgumentSpecification && !(pArguments.prgexpr[index] is ExprArrayInit arrayInitPos && arrayInitPos.GeneratedForParamArray)) { pExprArguments[index] = pArguments.prgexpr[index++]; @@ -1222,7 +1222,7 @@ private RuntimeBinderException ReportErrorsOnFailure() if (0 != (_pGroup.Flags & EXPRFLAG.EXF_CTOR)) { - Debug.Assert(!(_pGroup.ParentType is TypeParameterType)); + Debug.Assert(_pGroup.ParentType is not TypeParameterType); return ErrorHandling.Error(ErrorCode.ERR_BadCtorArgCount, _pGroup.ParentType, _pArguments.carg); } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ImplicitConversion.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ImplicitConversion.cs index 485b9e648e6af8..3ed5361bab4f6b 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ImplicitConversion.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ImplicitConversion.cs @@ -93,7 +93,7 @@ public bool Bind() { case TypeKind.TK_NullType: // Can only convert to the null type if src is null. - if (!(_typeSrc is NullType)) + if (_typeSrc is not NullType) { return false; } @@ -581,7 +581,7 @@ private bool bindImplicitConversionToBase(AggregateType pSource) // * From any delegate-type to System.Delegate. // * From any delegate-type to System.ICloneable. - if (!(_typeDest is AggregateType) || !SymbolLoader.HasBaseConversion(pSource, _typeDest)) + if (_typeDest is not AggregateType || !SymbolLoader.HasBaseConversion(pSource, _typeDest)) { return false; } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MemberLookup.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MemberLookup.cs index 3648b9237f5daf..ad8d5208b1b516 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MemberLookup.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MemberLookup.cs @@ -115,7 +115,7 @@ private bool SearchSingleType(AggregateType typeCur, out bool pfHideByName) symCur != null; symCur = symCur.LookupNext(symbmask_t.MASK_Member)) { - Debug.Assert(!(symCur is AggregateSymbol)); + Debug.Assert(symCur is not AggregateSymbol); // Check for arity. // For non-zero arity, only methods of the correct arity are considered. // For zero arity, don't filter out any methods since we do type argument @@ -176,7 +176,7 @@ private bool SearchSingleType(AggregateType typeCur, out bool pfHideByName) // Make sure that whether we're seeing a ctor, operator, or indexer is consistent with the flags. if (((_flags & MemLookFlags.Ctor) == 0) != (meth == null || !meth.IsConstructor()) || ((_flags & MemLookFlags.Operator) == 0) != (meth == null || !meth.isOperator) || - ((_flags & MemLookFlags.Indexer) == 0) != !(prop is IndexerSymbol)) + ((_flags & MemLookFlags.Indexer) == 0) != (prop is not IndexerSymbol)) { if (!_swtBad) { @@ -188,7 +188,7 @@ private bool SearchSingleType(AggregateType typeCur, out bool pfHideByName) // We can't call CheckBogus on methods or indexers because if the method has the wrong // number of parameters people don't think they should have to /r the assemblies containing // the parameter types and they complain about the resulting CS0012 errors. - if (!(symCur is MethodSymbol) && (_flags & MemLookFlags.Indexer) == 0 && CSemanticChecker.CheckBogus(symCur)) + if (symCur is not MethodSymbol && (_flags & MemLookFlags.Indexer) == 0 && CSemanticChecker.CheckBogus(symCur)) { // A bogus member - we can't use these, so only record them for error reporting. if (!_swtBogus) @@ -267,7 +267,7 @@ private bool SearchSingleType(AggregateType typeCur, out bool pfHideByName) else if (!_fMulti) { // Give method groups priority. - if (!(symCur is MethodSymbol)) + if (symCur is not MethodSymbol) goto LAmbig; // Erase previous results so we'll record this method as the first. _prgtype = new List(); @@ -280,7 +280,7 @@ private bool SearchSingleType(AggregateType typeCur, out bool pfHideByName) if (!typeCur.DiffHidden) { // Give method groups priority. - if (!(_swtFirst.Sym is MethodSymbol)) + if (_swtFirst.Sym is not MethodSymbol) goto LAmbig; } // This one is hidden by another. This one also hides any more in base types. @@ -644,7 +644,7 @@ public Exception ReportErrors() if (_swtBadArity) { Debug.Assert(_arity != 0); - Debug.Assert(!(_swtBadArity.Sym is AggregateSymbol)); + Debug.Assert(_swtBadArity.Sym is not AggregateSymbol); if (_swtBadArity.Sym is MethodSymbol badMeth) { int cvar = badMeth.typeVars.Count; diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodIterator.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodIterator.cs index 69920a519fedff..37d2abc8326ab2 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodIterator.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodIterator.cs @@ -65,7 +65,7 @@ public bool CanUseCurrentSymbol if (_mask == symbmask_t.MASK_MethodSymbol && ( 0 == (_flags & EXPRFLAG.EXF_CTOR) != !((MethodSymbol)CurrentSymbol).IsConstructor() || 0 == (_flags & EXPRFLAG.EXF_OPERATOR) != !((MethodSymbol)CurrentSymbol).isOperator) || - _mask == symbmask_t.MASK_PropertySymbol && !(CurrentSymbol is IndexerSymbol)) + _mask == symbmask_t.MASK_PropertySymbol && CurrentSymbol is not IndexerSymbol) { // Get the next symbol. return false; diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodTypeInferrer.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodTypeInferrer.cs index cb9091130d4418..bd4db7300c4f76 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodTypeInferrer.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodTypeInferrer.cs @@ -242,7 +242,7 @@ private bool InferTypeArgs() //////////////////////////////////////////////////////////////////////////////// private static bool IsReallyAType(CType pType) => - !(pType is NullType) && !(pType is VoidType) && !(pType is MethodGroupType); + pType is not NullType && pType is not VoidType && pType is not MethodGroupType; //////////////////////////////////////////////////////////////////////////////// // diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Nullable.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Nullable.cs index fe03e124c3f0c0..8b3ccaa1febf49 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Nullable.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Nullable.cs @@ -28,7 +28,7 @@ private static Expr StripNullableConstructor(Expr pExpr) while (IsNullableConstructor(pExpr, out ExprCall call)) { pExpr = call.OptionalArguments; - Debug.Assert(pExpr != null && !(pExpr is ExprList)); + Debug.Assert(pExpr != null && pExpr is not ExprList); } return pExpr; @@ -45,7 +45,7 @@ private static Expr BindNubValue(Expr exprSrc) if (IsNullableConstructor(exprSrc, out ExprCall call)) { Expr args = call.OptionalArguments; - Debug.Assert(args != null && !(args is ExprList)); + Debug.Assert(args != null && args is not ExprList); return args; } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Operators.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Operators.cs index 615fcab9d74e1a..a304c4bf70dbdf 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Operators.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Operators.cs @@ -652,7 +652,7 @@ private ExprBinOp BindLiftedStandardBinOp(BinOpArgInfo info, BinOpFullSig bofs, ? GetEnumBinOpType(ek, nonLiftedArg1.Type, nonLiftedArg2.Type, out _) : pArgument1.Type; - if (!(resultType is NullableType)) + if (resultType is not NullableType) { resultType = TypeManager.GetNullable(resultType); } @@ -753,7 +753,7 @@ private bool CanConvertArg1(BinOpArgInfo info, CType typeDst, out LiftFlags pgrf { ptypeSig1 = null; ptypeSig2 = null; - Debug.Assert(!(typeDst is NullableType)); + Debug.Assert(typeDst is not NullableType); if (canConvert(info.arg1, typeDst)) pgrflt = LiftFlags.None; @@ -787,7 +787,7 @@ Same as CanConvertArg1 but with the indices interchanged! private bool CanConvertArg2(BinOpArgInfo info, CType typeDst, out LiftFlags pgrflt, out CType ptypeSig1, out CType ptypeSig2) { - Debug.Assert(!(typeDst is NullableType)); + Debug.Assert(typeDst is not NullableType); ptypeSig1 = null; ptypeSig2 = null; @@ -1368,7 +1368,7 @@ private UnaryOperatorSignatureFindResult PopulateSignatureList(Expr pArgument, U } else if (unaryOpKind == UnaOpKind.IncDec) { - Debug.Assert(!(pArgumentType is PointerType)); + Debug.Assert(pArgumentType is not PointerType); // Check for user defined inc/dec ExprMultiGet exprGet = ExprFactory.CreateMultiGet(0, pArgumentType, null); @@ -1448,7 +1448,7 @@ private bool FindApplicableSignatures( continue; case ConvKind.Explicit: - if (!(pArgument is ExprConstant)) + if (pArgument is not ExprConstant) { continue; } @@ -1745,7 +1745,7 @@ private ExprMulti BindNonliftedIncOp(ExpressionKind ek, EXPRFLAG flags, Expr arg ExprMultiGet exprGet = ExprFactory.CreateMultiGet(EXPRFLAG.EXF_ASSGOP, arg.Type, null); Expr exprVal = exprGet; CType type = uofs.GetType(); - Debug.Assert(!(type is NullableType)); + Debug.Assert(type is not NullableType); // These used to be converts, but we're making them casts now - this is because // we need to remove the ability to call inc(sbyte) etc for all types smaller than int. @@ -1923,7 +1923,7 @@ private ExprOperator BindBoolBitwiseOp(ExpressionKind ek, EXPRFLAG flags, Expr e Expr nonLiftedArg2 = StripNullableConstructor(expr2); Expr nonLiftedResult = null; - if (!(nonLiftedArg1.Type is NullableType) && !(nonLiftedArg2.Type is NullableType)) + if (nonLiftedArg1.Type is not NullableType && nonLiftedArg2.Type is not NullableType) { nonLiftedResult = BindBoolBinOp(this, ek, flags, nonLiftedArg1, nonLiftedArg2); } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Symbols/SymbolLoader.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Symbols/SymbolLoader.cs index afdf1a32668114..371fc64233867b 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Symbols/SymbolLoader.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Symbols/SymbolLoader.cs @@ -173,7 +173,7 @@ private static bool HasImplicitReferenceConversion(CType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); - Debug.Assert(!(pSource is TypeParameterType)); + Debug.Assert(pSource is not TypeParameterType); // The implicit reference conversions are: // * From any reference type to Object. @@ -418,7 +418,7 @@ private static bool HasImplicitBoxingConversion(CType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); - Debug.Assert(!(pSource is TypeParameterType)); + Debug.Assert(pSource is not TypeParameterType); // The rest of the boxing conversions only operate when going from a value type // to a reference type. diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/EXPR.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/EXPR.cs index f60ef0a6e68966..13023eccad81b7 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/EXPR.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/EXPR.cs @@ -31,7 +31,7 @@ public CType Type { get { - Debug.Assert(!(this is ExprList)); + Debug.Assert(this is not ExprList); Debug.Assert(_type != null); return _type; } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/TypeBind.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/TypeBind.cs index e0de4a45620831..a8df9c101f35ae 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/TypeBind.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/TypeBind.cs @@ -165,7 +165,7 @@ private static bool CheckConstraintsCore(Symbol symErr, TypeArray typeVars, Type [RequiresDynamicCode(Binder.DynamicCodeWarning)] private static bool CheckSingleConstraint(Symbol symErr, TypeParameterType var, CType arg, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags) { - Debug.Assert(!(arg is PointerType)); + Debug.Assert(arg is not PointerType); Debug.Assert(!arg.IsStaticClass); bool fReportErrors = 0 == (flags & CheckConstraintsFlags.NoErrors); diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs index 3da4c9012c8a22..700be66c983740 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs @@ -154,7 +154,7 @@ public static PointerType GetPointer(CType baseType) [RequiresDynamicCode(Binder.DynamicCodeWarning)] public static NullableType GetNullable(CType pUnderlyingType) { - Debug.Assert(!(pUnderlyingType is NullableType), "Attempt to make nullable of nullable"); + Debug.Assert(pUnderlyingType is not NullableType, "Attempt to make nullable of nullable"); NullableType pNullableType = TypeTable.LookupNullable(pUnderlyingType); if (pNullableType == null) @@ -619,8 +619,8 @@ internal static CType GetBestAccessibleType(AggregateSymbol context, CType typeS // The new type is returned in an out parameter. The result will be true (and the out param // non-null) only when the algorithm could find a suitable accessible type. Debug.Assert(typeSrc != null); - Debug.Assert(!(typeSrc is ParameterModifierType)); - Debug.Assert(!(typeSrc is PointerType)); + Debug.Assert(typeSrc is not ParameterModifierType); + Debug.Assert(typeSrc is not PointerType); if (CSemanticChecker.CheckTypeAccess(typeSrc, context)) { @@ -629,7 +629,7 @@ internal static CType GetBestAccessibleType(AggregateSymbol context, CType typeS } // These guys have no accessibility concerns. - Debug.Assert(!(typeSrc is VoidType) && !(typeSrc is TypeParameterType)); + Debug.Assert(typeSrc is not VoidType && typeSrc is not TypeParameterType); if (typeSrc is AggregateType aggSrc) { diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeTable.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeTable.cs index b88d4e1e98d8ee..320fb91a101696 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeTable.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeTable.cs @@ -31,12 +31,12 @@ public bool Equals(KeyPair other) => public override bool Equals(object obj) { Debug.Fail("Sub-optimal overload called. Check if this can be avoided."); - if (!(obj is KeyPair)) + if (obj is not KeyPair keyPair) { return false; } - return Equals((KeyPair)obj); + return Equals(keyPair); } public override int GetHashCode() diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs index 559fa6ffdb0bd8..4eecb7c8c4e46a 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs @@ -620,7 +620,7 @@ private static CType LoadSymbolsFromType(Type type) CType ctype = ProcessSpecialTypeInChain(current, t); if (ctype != null) { - Debug.Assert(!(ctype is AggregateType)); + Debug.Assert(ctype is not AggregateType); return ctype; } @@ -1800,7 +1800,7 @@ private static void AddConversionsForOneType(Type type) // there are any conversions. CType t = GetCTypeFromType(type); - if (!(t is AggregateType)) + if (t is not AggregateType) { CType endT; while ((endT = t.BaseOrParameterOrElementType) != null) diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs index 4db21ab5b66077..910d44ecc0c6e2 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs @@ -74,13 +74,13 @@ private int Indent set => _output.Indent = value; } - private bool IsCurrentInterface => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; + private bool IsCurrentInterface => _currentClass != null && _currentClass is not CodeTypeDelegate ? _currentClass.IsInterface : false; - private bool IsCurrentClass => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsClass : false; + private bool IsCurrentClass => _currentClass != null && _currentClass is not CodeTypeDelegate ? _currentClass.IsClass : false; - private bool IsCurrentStruct => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsStruct : false; + private bool IsCurrentStruct => _currentClass != null && _currentClass is not CodeTypeDelegate ? _currentClass.IsStruct : false; - private bool IsCurrentEnum => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; + private bool IsCurrentEnum => _currentClass != null && _currentClass is not CodeTypeDelegate ? _currentClass.IsEnum : false; private bool IsCurrentDelegate => _currentClass != null && _currentClass is CodeTypeDelegate; @@ -340,7 +340,7 @@ private void GenerateEvents(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeMemberEvent) + if (current is CodeMemberEvent codeMemberEvent) { _currentMember = current; @@ -353,7 +353,7 @@ private void GenerateEvents(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeMemberEvent imp = (CodeMemberEvent)current; + CodeMemberEvent imp = codeMemberEvent; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateEvent(imp); if (imp.LinePragma != null) GenerateLinePragmaEnd(); @@ -369,7 +369,7 @@ private void GenerateFields(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeMemberField) + if (current is CodeMemberField codeMemberField) { _currentMember = current; @@ -382,7 +382,7 @@ private void GenerateFields(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeMemberField imp = (CodeMemberField)current; + CodeMemberField imp = codeMemberField; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateField(imp); if (imp.LinePragma != null) GenerateLinePragmaEnd(); @@ -541,39 +541,39 @@ private void GenerateStatement(CodeStatement e) GenerateLinePragmaStart(e.LinePragma); } - if (e is CodeCommentStatement) + if (e is CodeCommentStatement codeCommentStatement) { - GenerateCommentStatement((CodeCommentStatement)e); + GenerateCommentStatement(codeCommentStatement); } - else if (e is CodeMethodReturnStatement) + else if (e is CodeMethodReturnStatement codeMethodReturnStatement) { - GenerateMethodReturnStatement((CodeMethodReturnStatement)e); + GenerateMethodReturnStatement(codeMethodReturnStatement); } - else if (e is CodeConditionStatement) + else if (e is CodeConditionStatement codeConditionStatement) { - GenerateConditionStatement((CodeConditionStatement)e); + GenerateConditionStatement(codeConditionStatement); } - else if (e is CodeTryCatchFinallyStatement) + else if (e is CodeTryCatchFinallyStatement codeTryCatchFinallyStatement) { - GenerateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e); + GenerateTryCatchFinallyStatement(codeTryCatchFinallyStatement); } - else if (e is CodeAssignStatement) + else if (e is CodeAssignStatement codeAssignStatement) { - GenerateAssignStatement((CodeAssignStatement)e); + GenerateAssignStatement(codeAssignStatement); } - else if (e is CodeExpressionStatement) + else if (e is CodeExpressionStatement codeExpressionStatement) { - GenerateExpressionStatement((CodeExpressionStatement)e); + GenerateExpressionStatement(codeExpressionStatement); } - else if (e is CodeIterationStatement) + else if (e is CodeIterationStatement codeIterationStatement) { - GenerateIterationStatement((CodeIterationStatement)e); + GenerateIterationStatement(codeIterationStatement); } - else if (e is CodeThrowExceptionStatement) + else if (e is CodeThrowExceptionStatement codeThrowExceptionStatement) { - GenerateThrowExceptionStatement((CodeThrowExceptionStatement)e); + GenerateThrowExceptionStatement(codeThrowExceptionStatement); } - else if (e is CodeSnippetStatement) + else if (e is CodeSnippetStatement codeSnippetStatement) { // Don't indent snippet statements, in order to preserve the column // information from the original code. This improves the debugging @@ -581,30 +581,30 @@ private void GenerateStatement(CodeStatement e) int savedIndent = Indent; Indent = 0; - GenerateSnippetStatement((CodeSnippetStatement)e); + GenerateSnippetStatement(codeSnippetStatement); // Restore the indent Indent = savedIndent; } - else if (e is CodeVariableDeclarationStatement) + else if (e is CodeVariableDeclarationStatement codeVariableDeclarationStatement) { - GenerateVariableDeclarationStatement((CodeVariableDeclarationStatement)e); + GenerateVariableDeclarationStatement(codeVariableDeclarationStatement); } - else if (e is CodeAttachEventStatement) + else if (e is CodeAttachEventStatement codeAttachEventStatement) { - GenerateAttachEventStatement((CodeAttachEventStatement)e); + GenerateAttachEventStatement(codeAttachEventStatement); } - else if (e is CodeRemoveEventStatement) + else if (e is CodeRemoveEventStatement codeRemoveEventStatement) { - GenerateRemoveEventStatement((CodeRemoveEventStatement)e); + GenerateRemoveEventStatement(codeRemoveEventStatement); } - else if (e is CodeGotoStatement) + else if (e is CodeGotoStatement codeGotoStatement) { - GenerateGotoStatement((CodeGotoStatement)e); + GenerateGotoStatement(codeGotoStatement); } - else if (e is CodeLabeledStatement) + else if (e is CodeLabeledStatement codeLabeledStatement) { - GenerateLabeledStatement((CodeLabeledStatement)e); + GenerateLabeledStatement(codeLabeledStatement); } else { @@ -671,70 +671,70 @@ private void GenerateObjectCreateExpression(CodeObjectCreateExpression e) private void GeneratePrimitiveExpression(CodePrimitiveExpression e) { - if (e.Value is char) + if (e.Value is char ch) { - GeneratePrimitiveChar((char)e.Value); + GeneratePrimitiveChar(ch); } - else if (e.Value is sbyte) + else if (e.Value is sbyte sb) { // C# has no literal marker for types smaller than Int32 - Output.Write(((sbyte)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(sb.ToString(CultureInfo.InvariantCulture)); } - else if (e.Value is ushort) + else if (e.Value is ushort num6) { // C# has no literal marker for types smaller than Int32, and you will // get a conversion error if you use "u" here. - Output.Write(((ushort)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num6.ToString(CultureInfo.InvariantCulture)); } - else if (e.Value is uint) + else if (e.Value is uint num5) { - Output.Write(((uint)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num5.ToString(CultureInfo.InvariantCulture)); Output.Write('u'); } - else if (e.Value is ulong) + else if (e.Value is ulong num4) { - Output.Write(((ulong)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num4.ToString(CultureInfo.InvariantCulture)); Output.Write("ul"); } else if (e.Value == null) { Output.Write(NullToken); } - else if (e.Value is string) + else if (e.Value is string str) { - Output.Write(QuoteSnippetString((string)e.Value)); + Output.Write(QuoteSnippetString(str)); } - else if (e.Value is byte) + else if (e.Value is byte b2) { - Output.Write(((byte)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(b2.ToString(CultureInfo.InvariantCulture)); } - else if (e.Value is short) + else if (e.Value is short num3) { - Output.Write(((short)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num3.ToString(CultureInfo.InvariantCulture)); } - else if (e.Value is int) + else if (e.Value is int num2) { - Output.Write(((int)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num2.ToString(CultureInfo.InvariantCulture)); } - else if (e.Value is long) + else if (e.Value is long num) { - Output.Write(((long)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num.ToString(CultureInfo.InvariantCulture)); } - else if (e.Value is float) + else if (e.Value is float f) { - GenerateSingleFloatValue((float)e.Value); + GenerateSingleFloatValue(f); } - else if (e.Value is double) + else if (e.Value is double d2) { - GenerateDoubleValue((double)e.Value); + GenerateDoubleValue(d2); } - else if (e.Value is decimal) + else if (e.Value is decimal d) { - GenerateDecimalValue((decimal)e.Value); + GenerateDecimalValue(d); } - else if (e.Value is bool) + else if (e.Value is bool b) { - if ((bool)e.Value) + if (b) { Output.Write("true"); } @@ -1126,85 +1126,85 @@ private void GenerateEvent(CodeMemberEvent e) private void GenerateExpression(CodeExpression e) { - if (e is CodeArrayCreateExpression) + if (e is CodeArrayCreateExpression codeArrayCreateExpression) { - GenerateArrayCreateExpression((CodeArrayCreateExpression)e); + GenerateArrayCreateExpression(codeArrayCreateExpression); } else if (e is CodeBaseReferenceExpression) { GenerateBaseReferenceExpression(); } - else if (e is CodeBinaryOperatorExpression) + else if (e is CodeBinaryOperatorExpression codeBinaryOperatorExpression) { - GenerateBinaryOperatorExpression((CodeBinaryOperatorExpression)e); + GenerateBinaryOperatorExpression(codeBinaryOperatorExpression); } - else if (e is CodeCastExpression) + else if (e is CodeCastExpression codeCastExpression) { - GenerateCastExpression((CodeCastExpression)e); + GenerateCastExpression(codeCastExpression); } - else if (e is CodeDelegateCreateExpression) + else if (e is CodeDelegateCreateExpression codeDelegateCreateExpression) { - GenerateDelegateCreateExpression((CodeDelegateCreateExpression)e); + GenerateDelegateCreateExpression(codeDelegateCreateExpression); } - else if (e is CodeFieldReferenceExpression) + else if (e is CodeFieldReferenceExpression codeFieldReferenceExpression) { - GenerateFieldReferenceExpression((CodeFieldReferenceExpression)e); + GenerateFieldReferenceExpression(codeFieldReferenceExpression); } - else if (e is CodeArgumentReferenceExpression) + else if (e is CodeArgumentReferenceExpression codeArgumentReferenceExpression) { - GenerateArgumentReferenceExpression((CodeArgumentReferenceExpression)e); + GenerateArgumentReferenceExpression(codeArgumentReferenceExpression); } - else if (e is CodeVariableReferenceExpression) + else if (e is CodeVariableReferenceExpression codeVariableReferenceExpression) { - GenerateVariableReferenceExpression((CodeVariableReferenceExpression)e); + GenerateVariableReferenceExpression(codeVariableReferenceExpression); } - else if (e is CodeIndexerExpression) + else if (e is CodeIndexerExpression codeIndexerExpression) { - GenerateIndexerExpression((CodeIndexerExpression)e); + GenerateIndexerExpression(codeIndexerExpression); } - else if (e is CodeArrayIndexerExpression) + else if (e is CodeArrayIndexerExpression codeArrayIndexerExpression) { - GenerateArrayIndexerExpression((CodeArrayIndexerExpression)e); + GenerateArrayIndexerExpression(codeArrayIndexerExpression); } - else if (e is CodeSnippetExpression) + else if (e is CodeSnippetExpression codeSnippetExpression) { - GenerateSnippetExpression((CodeSnippetExpression)e); + GenerateSnippetExpression(codeSnippetExpression); } - else if (e is CodeMethodInvokeExpression) + else if (e is CodeMethodInvokeExpression codeMethodInvokeExpression) { - GenerateMethodInvokeExpression((CodeMethodInvokeExpression)e); + GenerateMethodInvokeExpression(codeMethodInvokeExpression); } - else if (e is CodeMethodReferenceExpression) + else if (e is CodeMethodReferenceExpression codeMethodReferenceExpression) { - GenerateMethodReferenceExpression((CodeMethodReferenceExpression)e); + GenerateMethodReferenceExpression(codeMethodReferenceExpression); } - else if (e is CodeEventReferenceExpression) + else if (e is CodeEventReferenceExpression codeEventReferenceExpression) { - GenerateEventReferenceExpression((CodeEventReferenceExpression)e); + GenerateEventReferenceExpression(codeEventReferenceExpression); } - else if (e is CodeDelegateInvokeExpression) + else if (e is CodeDelegateInvokeExpression codeDelegateInvokeExpression) { - GenerateDelegateInvokeExpression((CodeDelegateInvokeExpression)e); + GenerateDelegateInvokeExpression(codeDelegateInvokeExpression); } - else if (e is CodeObjectCreateExpression) + else if (e is CodeObjectCreateExpression codeObjectCreateExpression) { - GenerateObjectCreateExpression((CodeObjectCreateExpression)e); + GenerateObjectCreateExpression(codeObjectCreateExpression); } - else if (e is CodeParameterDeclarationExpression) + else if (e is CodeParameterDeclarationExpression codeParameterDeclarationExpression) { - GenerateParameterDeclarationExpression((CodeParameterDeclarationExpression)e); + GenerateParameterDeclarationExpression(codeParameterDeclarationExpression); } - else if (e is CodeDirectionExpression) + else if (e is CodeDirectionExpression codeDirectionExpression) { - GenerateDirectionExpression((CodeDirectionExpression)e); + GenerateDirectionExpression(codeDirectionExpression); } - else if (e is CodePrimitiveExpression) + else if (e is CodePrimitiveExpression codePrimitiveExpression) { - GeneratePrimitiveExpression((CodePrimitiveExpression)e); + GeneratePrimitiveExpression(codePrimitiveExpression); } - else if (e is CodePropertyReferenceExpression) + else if (e is CodePropertyReferenceExpression codePropertyReferenceExpression) { - GeneratePropertyReferenceExpression((CodePropertyReferenceExpression)e); + GeneratePropertyReferenceExpression(codePropertyReferenceExpression); } else if (e is CodePropertySetValueReferenceExpression) { @@ -1214,17 +1214,17 @@ private void GenerateExpression(CodeExpression e) { GenerateThisReferenceExpression(); } - else if (e is CodeTypeReferenceExpression) + else if (e is CodeTypeReferenceExpression codeTypeReferenceExpression) { - GenerateTypeReferenceExpression((CodeTypeReferenceExpression)e); + GenerateTypeReferenceExpression(codeTypeReferenceExpression); } - else if (e is CodeTypeOfExpression) + else if (e is CodeTypeOfExpression codeTypeOfExpression) { - GenerateTypeOfExpression((CodeTypeOfExpression)e); + GenerateTypeOfExpression(codeTypeOfExpression); } - else if (e is CodeDefaultValueExpression) + else if (e is CodeDefaultValueExpression codeDefaultValueExpression) { - GenerateDefaultValueExpression((CodeDefaultValueExpression)e); + GenerateDefaultValueExpression(codeDefaultValueExpression); } else { @@ -1308,7 +1308,7 @@ private void GenerateMethods(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeMemberMethod && !(current is CodeTypeConstructor) && !(current is CodeConstructor)) + if (current is CodeMemberMethod && current is not CodeTypeConstructor && current is not CodeConstructor) { _currentMember = current; @@ -1323,9 +1323,9 @@ private void GenerateMethods(CodeTypeDeclaration e) GenerateCommentStatements(_currentMember.Comments); CodeMemberMethod imp = (CodeMemberMethod)current; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); - if (current is CodeEntryPointMethod) + if (current is CodeEntryPointMethod codeEntryPointMethod) { - GenerateEntryPointMethod((CodeEntryPointMethod)current); + GenerateEntryPointMethod(codeEntryPointMethod); } else { @@ -1405,7 +1405,7 @@ private void GenerateProperties(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeMemberProperty) + if (current is CodeMemberProperty codeMemberProperty) { _currentMember = current; @@ -1418,7 +1418,7 @@ private void GenerateProperties(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeMemberProperty imp = (CodeMemberProperty)current; + CodeMemberProperty imp = codeMemberProperty; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateProperty(imp); if (imp.LinePragma != null) GenerateLinePragmaEnd(); @@ -1717,7 +1717,7 @@ private void GenerateConstructors(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeConstructor) + if (current is CodeConstructor codeConstructor) { _currentMember = current; @@ -1730,7 +1730,7 @@ private void GenerateConstructors(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeConstructor imp = (CodeConstructor)current; + CodeConstructor imp = codeConstructor; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateConstructor(imp); if (imp.LinePragma != null) GenerateLinePragmaEnd(); @@ -1947,9 +1947,9 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla Output.WriteLine(); } - if (member is CodeTypeDeclaration) + if (member is CodeTypeDeclaration codeTypeDeclaration) { - ((ICodeGenerator)this).GenerateCodeFromType((CodeTypeDeclaration)member, _output.InnerWriter, _options); + ((ICodeGenerator)this).GenerateCodeFromType(codeTypeDeclaration, _output.InnerWriter, _options); // Nested types clobber the current class, so reset it. _currentClass = declaredType; @@ -1970,38 +1970,38 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla GenerateLinePragmaStart(member.LinePragma); } - if (member is CodeMemberField) + if (member is CodeMemberField codeMemberField) { - GenerateField((CodeMemberField)member); + GenerateField(codeMemberField); } - else if (member is CodeMemberProperty) + else if (member is CodeMemberProperty codeMemberProperty) { - GenerateProperty((CodeMemberProperty)member); + GenerateProperty(codeMemberProperty); } - else if (member is CodeMemberMethod) + else if (member is CodeMemberMethod codeMemberMethod) { - if (member is CodeConstructor) + if (member is CodeConstructor codeConstructor) { - GenerateConstructor((CodeConstructor)member); + GenerateConstructor(codeConstructor); } - else if (member is CodeTypeConstructor) + else if (member is CodeTypeConstructor codeTypeConstructor) { - GenerateTypeConstructor((CodeTypeConstructor)member); + GenerateTypeConstructor(codeTypeConstructor); } - else if (member is CodeEntryPointMethod) + else if (member is CodeEntryPointMethod codeEntryPointMethod) { - GenerateEntryPointMethod((CodeEntryPointMethod)member); + GenerateEntryPointMethod(codeEntryPointMethod); } else { - GenerateMethod((CodeMemberMethod)member); + GenerateMethod(codeMemberMethod); } } - else if (member is CodeMemberEvent) + else if (member is CodeMemberEvent codeMemberEvent) { - GenerateEvent((CodeMemberEvent)member); + GenerateEvent(codeMemberEvent); } - else if (member is CodeSnippetTypeMember) + else if (member is CodeSnippetTypeMember codeSnippetTypeMember) { // Don't indent snippets, in order to preserve the column // information from the original code. This improves the debugging @@ -2009,7 +2009,7 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla int savedIndent = Indent; Indent = 0; - GenerateSnippetMember((CodeSnippetTypeMember)member); + GenerateSnippetMember(codeSnippetTypeMember); // Restore the indent Indent = savedIndent; @@ -2035,7 +2035,7 @@ private void GenerateTypeConstructors(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeTypeConstructor) + if (current is CodeTypeConstructor codeTypeConstructor) { _currentMember = current; @@ -2048,7 +2048,7 @@ private void GenerateTypeConstructors(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeTypeConstructor imp = (CodeTypeConstructor)current; + CodeTypeConstructor imp = codeTypeConstructor; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateTypeConstructor(imp); if (imp.LinePragma != null) GenerateLinePragmaEnd(); @@ -2065,7 +2065,7 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) bool hasSnippet = false; foreach (CodeTypeMember current in e.Members) { - if (current is CodeSnippetTypeMember) + if (current is CodeSnippetTypeMember codeSnippetTypeMember) { hasSnippet = true; _currentMember = current; @@ -2079,7 +2079,7 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeSnippetTypeMember imp = (CodeSnippetTypeMember)current; + CodeSnippetTypeMember imp = codeSnippetTypeMember; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); // Don't indent snippets, in order to preserve the column @@ -2113,13 +2113,13 @@ private void GenerateNestedTypes(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeTypeDeclaration) + if (current is CodeTypeDeclaration codeTypeDeclaration) { if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } - CodeTypeDeclaration currentClass = (CodeTypeDeclaration)current; + CodeTypeDeclaration currentClass = codeTypeDeclaration; ((ICodeGenerator)this).GenerateCodeFromType(currentClass, _output.InnerWriter, _options); } } @@ -2494,13 +2494,13 @@ private void GenerateDirectives(CodeDirectiveCollection directives) for (int i = 0; i < directives.Count; i++) { CodeDirective directive = directives[i]; - if (directive is CodeChecksumPragma) + if (directive is CodeChecksumPragma codeChecksumPragma) { - GenerateChecksumPragma((CodeChecksumPragma)directive); + GenerateChecksumPragma(codeChecksumPragma); } - else if (directive is CodeRegionDirective) + else if (directive is CodeRegionDirective codeRegionDirective) { - GenerateCodeRegionDirective((CodeRegionDirective)directive); + GenerateCodeRegionDirective(codeRegionDirective); } } } @@ -3164,9 +3164,9 @@ void ICodeGenerator.GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, try { - if (e is CodeSnippetCompileUnit) + if (e is CodeSnippetCompileUnit codeSnippetCompileUnit) { - GenerateSnippetCompileUnit((CodeSnippetCompileUnit)e); + GenerateSnippetCompileUnit(codeSnippetCompileUnit); } else { diff --git a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs index f607ca6142b213..f38bf97eca10cb 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs @@ -813,25 +813,25 @@ protected override void GeneratePrimitiveExpression(CodePrimitiveExpression e) { Output.Write("Global.Microsoft.VisualBasic.ChrW(" + ((IConvertible)e.Value).ToInt32(CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture) + ")"); } - else if (e.Value is sbyte) + else if (e.Value is sbyte sb) { Output.Write("CSByte("); - Output.Write(((sbyte)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(sb.ToString(CultureInfo.InvariantCulture)); Output.Write(')'); } - else if (e.Value is ushort) + else if (e.Value is ushort num3) { - Output.Write(((ushort)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num3.ToString(CultureInfo.InvariantCulture)); Output.Write("US"); } - else if (e.Value is uint) + else if (e.Value is uint num2) { - Output.Write(((uint)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num2.ToString(CultureInfo.InvariantCulture)); Output.Write("UI"); } - else if (e.Value is ulong) + else if (e.Value is ulong num) { - Output.Write(((ulong)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num.ToString(CultureInfo.InvariantCulture)); Output.Write("UL"); } else @@ -1124,7 +1124,7 @@ private void GenerateFormalEventReferenceExpression(CodeEventReferenceExpression if (e.TargetObject != null) { // Visual Basic Compiler does not like the me reference like this. - if (!(e.TargetObject is CodeThisReferenceExpression)) + if (e.TargetObject is not CodeThisReferenceExpression) { GenerateExpression(e.TargetObject); Output.Write('.'); @@ -1137,10 +1137,10 @@ protected override void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpre { if (e.TargetObject != null) { - if (e.TargetObject is CodeEventReferenceExpression) + if (e.TargetObject is CodeEventReferenceExpression codeEventReferenceExpression) { Output.Write("RaiseEvent "); - GenerateFormalEventReferenceExpression((CodeEventReferenceExpression)e.TargetObject); + GenerateFormalEventReferenceExpression(codeEventReferenceExpression); } else { @@ -1548,11 +1548,11 @@ private static bool MethodIsOverloaded(CodeMemberMethod e, CodeTypeDeclaration c } foreach (var current in c.Members) { - if (!(current is CodeMemberMethod)) + if (current is not CodeMemberMethod codeMemberMethod) continue; - CodeMemberMethod meth = (CodeMemberMethod)current; + CodeMemberMethod meth = codeMemberMethod; - if (!(current is CodeTypeConstructor) && !(current is CodeConstructor) + if (current is not CodeTypeConstructor && current is not CodeConstructor && meth != e && meth.Name.Equals(e.Name, StringComparison.OrdinalIgnoreCase) && meth.PrivateImplementationType == null) @@ -1710,9 +1710,9 @@ private static bool PropertyIsOverloaded(CodeMemberProperty e, CodeTypeDeclarati } foreach (var current in c.Members) { - if (!(current is CodeMemberProperty)) + if (current is not CodeMemberProperty codeMemberProperty) continue; - CodeMemberProperty prop = (CodeMemberProperty)current; + CodeMemberProperty prop = codeMemberProperty; if (prop != e && prop.Name.Equals(e.Name, StringComparison.OrdinalIgnoreCase) && prop.PrivateImplementationType == null) @@ -2265,13 +2265,13 @@ protected override void GenerateDirectives(CodeDirectiveCollection directives) for (int i = 0; i < directives.Count; i++) { CodeDirective directive = directives[i]; - if (directive is CodeChecksumPragma) + if (directive is CodeChecksumPragma codeChecksumPragma) { - GenerateChecksumPragma((CodeChecksumPragma)directive); + GenerateChecksumPragma(codeChecksumPragma); } - else if (directive is CodeRegionDirective) + else if (directive is CodeRegionDirective codeRegionDirective) { - GenerateCodeRegionDirective((CodeRegionDirective)directive); + GenerateCodeRegionDirective(codeRegionDirective); } } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs index 87f4f92ddac3bd..bf7b2b044355c6 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs @@ -26,13 +26,13 @@ public abstract class CodeGenerator : ICodeGenerator protected string CurrentMemberName => _currentMember != null ? _currentMember.Name : "<% unknown %>"; - protected bool IsCurrentInterface => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; + protected bool IsCurrentInterface => _currentClass != null && _currentClass is not CodeTypeDelegate ? _currentClass.IsInterface : false; - protected bool IsCurrentClass => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsClass : false; + protected bool IsCurrentClass => _currentClass != null && _currentClass is not CodeTypeDelegate ? _currentClass.IsClass : false; - protected bool IsCurrentStruct => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsStruct : false; + protected bool IsCurrentStruct => _currentClass != null && _currentClass is not CodeTypeDelegate ? _currentClass.IsStruct : false; - protected bool IsCurrentEnum => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; + protected bool IsCurrentEnum => _currentClass != null && _currentClass is not CodeTypeDelegate ? _currentClass.IsEnum : false; protected bool IsCurrentDelegate => _currentClass != null && _currentClass is CodeTypeDelegate; @@ -111,9 +111,9 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla Output.WriteLine(); } - if (member is CodeTypeDeclaration) + if (member is CodeTypeDeclaration codeTypeDeclaration) { - ((ICodeGenerator)this).GenerateCodeFromType((CodeTypeDeclaration)member, _output.InnerWriter, _options); + ((ICodeGenerator)this).GenerateCodeFromType(codeTypeDeclaration, _output.InnerWriter, _options); // Nested types clobber the current class, so reset it. _currentClass = declaredType; @@ -134,38 +134,38 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla GenerateLinePragmaStart(member.LinePragma); } - if (member is CodeMemberField) + if (member is CodeMemberField codeMemberField) { - GenerateField((CodeMemberField)member); + GenerateField(codeMemberField); } - else if (member is CodeMemberProperty) + else if (member is CodeMemberProperty codeMemberProperty) { - GenerateProperty((CodeMemberProperty)member, declaredType); + GenerateProperty(codeMemberProperty, declaredType); } - else if (member is CodeMemberMethod) + else if (member is CodeMemberMethod codeMemberMethod) { - if (member is CodeConstructor) + if (member is CodeConstructor codeConstructor) { - GenerateConstructor((CodeConstructor)member, declaredType); + GenerateConstructor(codeConstructor, declaredType); } - else if (member is CodeTypeConstructor) + else if (member is CodeTypeConstructor codeTypeConstructor) { - GenerateTypeConstructor((CodeTypeConstructor)member); + GenerateTypeConstructor(codeTypeConstructor); } - else if (member is CodeEntryPointMethod) + else if (member is CodeEntryPointMethod codeEntryPointMethod) { - GenerateEntryPointMethod((CodeEntryPointMethod)member, declaredType); + GenerateEntryPointMethod(codeEntryPointMethod, declaredType); } else { - GenerateMethod((CodeMemberMethod)member, declaredType); + GenerateMethod(codeMemberMethod, declaredType); } } - else if (member is CodeMemberEvent) + else if (member is CodeMemberEvent codeMemberEvent) { - GenerateEvent((CodeMemberEvent)member, declaredType); + GenerateEvent(codeMemberEvent, declaredType); } - else if (member is CodeSnippetTypeMember) + else if (member is CodeSnippetTypeMember codeSnippetTypeMember) { // Don't indent snippets, in order to preserve the column // information from the original code. This improves the debugging @@ -173,7 +173,7 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla int savedIndent = Indent; Indent = 0; - GenerateSnippetMember((CodeSnippetTypeMember)member); + GenerateSnippetMember(codeSnippetTypeMember); // Restore the indent Indent = savedIndent; @@ -199,7 +199,7 @@ private void GenerateTypeConstructors(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeTypeConstructor) + if (current is CodeTypeConstructor codeTypeConstructor) { _currentMember = current; @@ -212,7 +212,7 @@ private void GenerateTypeConstructors(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeTypeConstructor imp = (CodeTypeConstructor)current; + CodeTypeConstructor imp = codeTypeConstructor; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateTypeConstructor(imp); if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); @@ -320,9 +320,9 @@ void ICodeGenerator.GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, try { - if (e is CodeSnippetCompileUnit) + if (e is CodeSnippetCompileUnit codeSnippetCompileUnit) { - GenerateSnippetCompileUnit((CodeSnippetCompileUnit)e); + GenerateSnippetCompileUnit(codeSnippetCompileUnit); } else { @@ -434,7 +434,7 @@ private void GenerateConstructors(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeConstructor) + if (current is CodeConstructor codeConstructor) { _currentMember = current; @@ -447,7 +447,7 @@ private void GenerateConstructors(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeConstructor imp = (CodeConstructor)current; + CodeConstructor imp = codeConstructor; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); @@ -469,7 +469,7 @@ private void GenerateEvents(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeMemberEvent) + if (current is CodeMemberEvent codeMemberEvent) { _currentMember = current; @@ -482,7 +482,7 @@ private void GenerateEvents(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeMemberEvent imp = (CodeMemberEvent)current; + CodeMemberEvent imp = codeMemberEvent; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); @@ -502,105 +502,105 @@ private void GenerateEvents(CodeTypeDeclaration e) protected void GenerateExpression(CodeExpression e) { - if (e is CodeArrayCreateExpression) + if (e is CodeArrayCreateExpression codeArrayCreateExpression) { - GenerateArrayCreateExpression((CodeArrayCreateExpression)e); + GenerateArrayCreateExpression(codeArrayCreateExpression); } - else if (e is CodeBaseReferenceExpression) + else if (e is CodeBaseReferenceExpression codeBaseReferenceExpression) { - GenerateBaseReferenceExpression((CodeBaseReferenceExpression)e); + GenerateBaseReferenceExpression(codeBaseReferenceExpression); } - else if (e is CodeBinaryOperatorExpression) + else if (e is CodeBinaryOperatorExpression codeBinaryOperatorExpression) { - GenerateBinaryOperatorExpression((CodeBinaryOperatorExpression)e); + GenerateBinaryOperatorExpression(codeBinaryOperatorExpression); } - else if (e is CodeCastExpression) + else if (e is CodeCastExpression codeCastExpression) { - GenerateCastExpression((CodeCastExpression)e); + GenerateCastExpression(codeCastExpression); } - else if (e is CodeDelegateCreateExpression) + else if (e is CodeDelegateCreateExpression codeDelegateCreateExpression) { - GenerateDelegateCreateExpression((CodeDelegateCreateExpression)e); + GenerateDelegateCreateExpression(codeDelegateCreateExpression); } - else if (e is CodeFieldReferenceExpression) + else if (e is CodeFieldReferenceExpression codeFieldReferenceExpression) { - GenerateFieldReferenceExpression((CodeFieldReferenceExpression)e); + GenerateFieldReferenceExpression(codeFieldReferenceExpression); } - else if (e is CodeArgumentReferenceExpression) + else if (e is CodeArgumentReferenceExpression codeArgumentReferenceExpression) { - GenerateArgumentReferenceExpression((CodeArgumentReferenceExpression)e); + GenerateArgumentReferenceExpression(codeArgumentReferenceExpression); } - else if (e is CodeVariableReferenceExpression) + else if (e is CodeVariableReferenceExpression codeVariableReferenceExpression) { - GenerateVariableReferenceExpression((CodeVariableReferenceExpression)e); + GenerateVariableReferenceExpression(codeVariableReferenceExpression); } - else if (e is CodeIndexerExpression) + else if (e is CodeIndexerExpression codeIndexerExpression) { - GenerateIndexerExpression((CodeIndexerExpression)e); + GenerateIndexerExpression(codeIndexerExpression); } - else if (e is CodeArrayIndexerExpression) + else if (e is CodeArrayIndexerExpression codeArrayIndexerExpression) { - GenerateArrayIndexerExpression((CodeArrayIndexerExpression)e); + GenerateArrayIndexerExpression(codeArrayIndexerExpression); } - else if (e is CodeSnippetExpression) + else if (e is CodeSnippetExpression codeSnippetExpression) { - GenerateSnippetExpression((CodeSnippetExpression)e); + GenerateSnippetExpression(codeSnippetExpression); } - else if (e is CodeMethodInvokeExpression) + else if (e is CodeMethodInvokeExpression codeMethodInvokeExpression) { - GenerateMethodInvokeExpression((CodeMethodInvokeExpression)e); + GenerateMethodInvokeExpression(codeMethodInvokeExpression); } - else if (e is CodeMethodReferenceExpression) + else if (e is CodeMethodReferenceExpression codeMethodReferenceExpression) { - GenerateMethodReferenceExpression((CodeMethodReferenceExpression)e); + GenerateMethodReferenceExpression(codeMethodReferenceExpression); } - else if (e is CodeEventReferenceExpression) + else if (e is CodeEventReferenceExpression codeEventReferenceExpression) { - GenerateEventReferenceExpression((CodeEventReferenceExpression)e); + GenerateEventReferenceExpression(codeEventReferenceExpression); } - else if (e is CodeDelegateInvokeExpression) + else if (e is CodeDelegateInvokeExpression codeDelegateInvokeExpression) { - GenerateDelegateInvokeExpression((CodeDelegateInvokeExpression)e); + GenerateDelegateInvokeExpression(codeDelegateInvokeExpression); } - else if (e is CodeObjectCreateExpression) + else if (e is CodeObjectCreateExpression codeObjectCreateExpression) { - GenerateObjectCreateExpression((CodeObjectCreateExpression)e); + GenerateObjectCreateExpression(codeObjectCreateExpression); } - else if (e is CodeParameterDeclarationExpression) + else if (e is CodeParameterDeclarationExpression codeParameterDeclarationExpression) { - GenerateParameterDeclarationExpression((CodeParameterDeclarationExpression)e); + GenerateParameterDeclarationExpression(codeParameterDeclarationExpression); } - else if (e is CodeDirectionExpression) + else if (e is CodeDirectionExpression codeDirectionExpression) { - GenerateDirectionExpression((CodeDirectionExpression)e); + GenerateDirectionExpression(codeDirectionExpression); } - else if (e is CodePrimitiveExpression) + else if (e is CodePrimitiveExpression codePrimitiveExpression) { - GeneratePrimitiveExpression((CodePrimitiveExpression)e); + GeneratePrimitiveExpression(codePrimitiveExpression); } - else if (e is CodePropertyReferenceExpression) + else if (e is CodePropertyReferenceExpression codePropertyReferenceExpression) { - GeneratePropertyReferenceExpression((CodePropertyReferenceExpression)e); + GeneratePropertyReferenceExpression(codePropertyReferenceExpression); } - else if (e is CodePropertySetValueReferenceExpression) + else if (e is CodePropertySetValueReferenceExpression codePropertySetValueReferenceExpression) { - GeneratePropertySetValueReferenceExpression((CodePropertySetValueReferenceExpression)e); + GeneratePropertySetValueReferenceExpression(codePropertySetValueReferenceExpression); } - else if (e is CodeThisReferenceExpression) + else if (e is CodeThisReferenceExpression codeThisReferenceExpression) { - GenerateThisReferenceExpression((CodeThisReferenceExpression)e); + GenerateThisReferenceExpression(codeThisReferenceExpression); } - else if (e is CodeTypeReferenceExpression) + else if (e is CodeTypeReferenceExpression codeTypeReferenceExpression) { - GenerateTypeReferenceExpression((CodeTypeReferenceExpression)e); + GenerateTypeReferenceExpression(codeTypeReferenceExpression); } - else if (e is CodeTypeOfExpression) + else if (e is CodeTypeOfExpression codeTypeOfExpression) { - GenerateTypeOfExpression((CodeTypeOfExpression)e); + GenerateTypeOfExpression(codeTypeOfExpression); } - else if (e is CodeDefaultValueExpression) + else if (e is CodeDefaultValueExpression codeDefaultValueExpression) { - GenerateDefaultValueExpression((CodeDefaultValueExpression)e); + GenerateDefaultValueExpression(codeDefaultValueExpression); } else { @@ -613,7 +613,7 @@ private void GenerateFields(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeMemberField) + if (current is CodeMemberField codeMemberField) { _currentMember = current; @@ -626,7 +626,7 @@ private void GenerateFields(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeMemberField imp = (CodeMemberField)current; + CodeMemberField imp = codeMemberField; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); @@ -649,7 +649,7 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) bool hasSnippet = false; foreach (CodeTypeMember current in e.Members) { - if (current is CodeSnippetTypeMember) + if (current is CodeSnippetTypeMember codeSnippetTypeMember) { hasSnippet = true; _currentMember = current; @@ -663,7 +663,7 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeSnippetTypeMember imp = (CodeSnippetTypeMember)current; + CodeSnippetTypeMember imp = codeSnippetTypeMember; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); @@ -725,7 +725,7 @@ private void GenerateMethods(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeMemberMethod && !(current is CodeTypeConstructor) && !(current is CodeConstructor)) + if (current is CodeMemberMethod && current is not CodeTypeConstructor && current is not CodeConstructor) { _currentMember = current; @@ -743,9 +743,9 @@ private void GenerateMethods(CodeTypeDeclaration e) { GenerateLinePragmaStart(imp.LinePragma); } - if (current is CodeEntryPointMethod) + if (current is CodeEntryPointMethod codeEntryPointMethod) { - GenerateEntryPointMethod((CodeEntryPointMethod)current, e); + GenerateEntryPointMethod(codeEntryPointMethod, e); } else { @@ -767,13 +767,13 @@ private void GenerateNestedTypes(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeTypeDeclaration) + if (current is CodeTypeDeclaration codeTypeDeclaration) { if (_options.BlankLinesBetweenMembers) { Output.WriteLine(); } - CodeTypeDeclaration currentClass = (CodeTypeDeclaration)current; + CodeTypeDeclaration currentClass = codeTypeDeclaration; ((ICodeGenerator)this).GenerateCodeFromType(currentClass, _output.InnerWriter, _options); } } @@ -823,7 +823,7 @@ private void GenerateProperties(CodeTypeDeclaration e) { foreach (CodeTypeMember current in e.Members) { - if (current is CodeMemberProperty) + if (current is CodeMemberProperty codeMemberProperty) { _currentMember = current; @@ -836,7 +836,7 @@ private void GenerateProperties(CodeTypeDeclaration e) GenerateDirectives(_currentMember.StartDirectives); } GenerateCommentStatements(_currentMember.Comments); - CodeMemberProperty imp = (CodeMemberProperty)current; + CodeMemberProperty imp = codeMemberProperty; if (imp.LinePragma != null) { GenerateLinePragmaStart(imp.LinePragma); @@ -868,39 +868,39 @@ protected void GenerateStatement(CodeStatement e) GenerateLinePragmaStart(e.LinePragma); } - if (e is CodeCommentStatement) + if (e is CodeCommentStatement codeCommentStatement) { - GenerateCommentStatement((CodeCommentStatement)e); + GenerateCommentStatement(codeCommentStatement); } - else if (e is CodeMethodReturnStatement) + else if (e is CodeMethodReturnStatement codeMethodReturnStatement) { - GenerateMethodReturnStatement((CodeMethodReturnStatement)e); + GenerateMethodReturnStatement(codeMethodReturnStatement); } - else if (e is CodeConditionStatement) + else if (e is CodeConditionStatement codeConditionStatement) { - GenerateConditionStatement((CodeConditionStatement)e); + GenerateConditionStatement(codeConditionStatement); } - else if (e is CodeTryCatchFinallyStatement) + else if (e is CodeTryCatchFinallyStatement codeTryCatchFinallyStatement) { - GenerateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e); + GenerateTryCatchFinallyStatement(codeTryCatchFinallyStatement); } - else if (e is CodeAssignStatement) + else if (e is CodeAssignStatement codeAssignStatement) { - GenerateAssignStatement((CodeAssignStatement)e); + GenerateAssignStatement(codeAssignStatement); } - else if (e is CodeExpressionStatement) + else if (e is CodeExpressionStatement codeExpressionStatement) { - GenerateExpressionStatement((CodeExpressionStatement)e); + GenerateExpressionStatement(codeExpressionStatement); } - else if (e is CodeIterationStatement) + else if (e is CodeIterationStatement codeIterationStatement) { - GenerateIterationStatement((CodeIterationStatement)e); + GenerateIterationStatement(codeIterationStatement); } - else if (e is CodeThrowExceptionStatement) + else if (e is CodeThrowExceptionStatement codeThrowExceptionStatement) { - GenerateThrowExceptionStatement((CodeThrowExceptionStatement)e); + GenerateThrowExceptionStatement(codeThrowExceptionStatement); } - else if (e is CodeSnippetStatement) + else if (e is CodeSnippetStatement codeSnippetStatement) { // Don't indent snippet statements, in order to preserve the column // information from the original code. This improves the debugging @@ -908,30 +908,30 @@ protected void GenerateStatement(CodeStatement e) int savedIndent = Indent; Indent = 0; - GenerateSnippetStatement((CodeSnippetStatement)e); + GenerateSnippetStatement(codeSnippetStatement); // Restore the indent Indent = savedIndent; } - else if (e is CodeVariableDeclarationStatement) + else if (e is CodeVariableDeclarationStatement codeVariableDeclarationStatement) { - GenerateVariableDeclarationStatement((CodeVariableDeclarationStatement)e); + GenerateVariableDeclarationStatement(codeVariableDeclarationStatement); } - else if (e is CodeAttachEventStatement) + else if (e is CodeAttachEventStatement codeAttachEventStatement) { - GenerateAttachEventStatement((CodeAttachEventStatement)e); + GenerateAttachEventStatement(codeAttachEventStatement); } - else if (e is CodeRemoveEventStatement) + else if (e is CodeRemoveEventStatement codeRemoveEventStatement) { - GenerateRemoveEventStatement((CodeRemoveEventStatement)e); + GenerateRemoveEventStatement(codeRemoveEventStatement); } - else if (e is CodeGotoStatement) + else if (e is CodeGotoStatement codeGotoStatement) { - GenerateGotoStatement((CodeGotoStatement)e); + GenerateGotoStatement(codeGotoStatement); } - else if (e is CodeLabeledStatement) + else if (e is CodeLabeledStatement codeLabeledStatement) { - GenerateLabeledStatement((CodeLabeledStatement)e); + GenerateLabeledStatement(codeLabeledStatement); } else { @@ -1374,45 +1374,45 @@ protected virtual void GeneratePrimitiveExpression(CodePrimitiveExpression e) { Output.Write(NullToken); } - else if (e.Value is string) + else if (e.Value is string str) { - Output.Write(QuoteSnippetString((string)e.Value)); + Output.Write(QuoteSnippetString(str)); } else if (e.Value is char) { Output.Write("'" + e.Value.ToString() + "'"); } - else if (e.Value is byte) + else if (e.Value is byte b2) { - Output.Write(((byte)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(b2.ToString(CultureInfo.InvariantCulture)); } - else if (e.Value is short) + else if (e.Value is short num3) { - Output.Write(((short)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num3.ToString(CultureInfo.InvariantCulture)); } - else if (e.Value is int) + else if (e.Value is int num2) { - Output.Write(((int)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num2.ToString(CultureInfo.InvariantCulture)); } - else if (e.Value is long) + else if (e.Value is long num) { - Output.Write(((long)e.Value).ToString(CultureInfo.InvariantCulture)); + Output.Write(num.ToString(CultureInfo.InvariantCulture)); } - else if (e.Value is float) + else if (e.Value is float f) { - GenerateSingleFloatValue((float)e.Value); + GenerateSingleFloatValue(f); } - else if (e.Value is double) + else if (e.Value is double d2) { - GenerateDoubleValue((double)e.Value); + GenerateDoubleValue(d2); } - else if (e.Value is decimal) + else if (e.Value is decimal d) { - GenerateDecimalValue((decimal)e.Value); + GenerateDecimalValue(d); } - else if (e.Value is bool) + else if (e.Value is bool b) { - if ((bool)e.Value) + if (b) { Output.Write("true"); } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs index 5f8f8ae7e750bb..2074ecd7143f38 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs @@ -20,41 +20,41 @@ internal sealed class CodeValidator internal void ValidateIdentifiers(CodeObject e) { - if (e is CodeCompileUnit) + if (e is CodeCompileUnit codeCompileUnit) { - ValidateCodeCompileUnit((CodeCompileUnit)e); + ValidateCodeCompileUnit(codeCompileUnit); } else if (e is CodeComment) { // do nothing } - else if (e is CodeExpression) + else if (e is CodeExpression codeExpression) { - ValidateExpression((CodeExpression)e); + ValidateExpression(codeExpression); } - else if (e is CodeNamespace) + else if (e is CodeNamespace codeNamespace) { - ValidateNamespace((CodeNamespace)e); + ValidateNamespace(codeNamespace); } - else if (e is CodeNamespaceImport) + else if (e is CodeNamespaceImport codeNamespaceImport) { - ValidateNamespaceImport((CodeNamespaceImport)e); + ValidateNamespaceImport(codeNamespaceImport); } - else if (e is CodeStatement) + else if (e is CodeStatement codeStatement) { - ValidateStatement((CodeStatement)e); + ValidateStatement(codeStatement); } - else if (e is CodeTypeMember) + else if (e is CodeTypeMember codeTypeMember) { - ValidateTypeMember((CodeTypeMember)e); + ValidateTypeMember(codeTypeMember); } - else if (e is CodeTypeReference) + else if (e is CodeTypeReference codeTypeReference) { - ValidateTypeReference((CodeTypeReference)e); + ValidateTypeReference(codeTypeReference); } - else if (e is CodeDirective) + else if (e is CodeDirective codeDirective) { - ValidateCodeDirective((CodeDirective)e); + ValidateCodeDirective(codeDirective); } else { @@ -68,29 +68,29 @@ private void ValidateTypeMember(CodeTypeMember e) ValidateCodeDirectives(e.StartDirectives); ValidateCodeDirectives(e.EndDirectives); - if (e is CodeMemberEvent) + if (e is CodeMemberEvent codeMemberEvent) { - ValidateEvent((CodeMemberEvent)e); + ValidateEvent(codeMemberEvent); } - else if (e is CodeMemberField) + else if (e is CodeMemberField codeMemberField) { - ValidateField((CodeMemberField)e); + ValidateField(codeMemberField); } - else if (e is CodeMemberMethod) + else if (e is CodeMemberMethod codeMemberMethod) { - ValidateMemberMethod((CodeMemberMethod)e); + ValidateMemberMethod(codeMemberMethod); } - else if (e is CodeMemberProperty) + else if (e is CodeMemberProperty codeMemberProperty) { - ValidateProperty((CodeMemberProperty)e); + ValidateProperty(codeMemberProperty); } else if (e is CodeSnippetTypeMember) { // do nothing } - else if (e is CodeTypeDeclaration) + else if (e is CodeTypeDeclaration codeTypeDeclaration) { - ValidateTypeDeclaration((CodeTypeDeclaration)e); + ValidateTypeDeclaration(codeTypeDeclaration); } else { @@ -318,17 +318,17 @@ private void ValidateMemberMethod(CodeMemberMethod e) ValidateTypeParameters(e.TypeParameters); ValidateTypeReferences(e.ImplementationTypes); - if (e is CodeEntryPointMethod) + if (e is CodeEntryPointMethod codeEntryPointMethod) { - ValidateStatements(((CodeEntryPointMethod)e).Statements); + ValidateStatements(codeEntryPointMethod.Statements); } - else if (e is CodeConstructor) + else if (e is CodeConstructor codeConstructor) { - ValidateConstructor((CodeConstructor)e); + ValidateConstructor(codeConstructor); } - else if (e is CodeTypeConstructor) + else if (e is CodeTypeConstructor codeTypeConstructor) { - ValidateTypeConstructor((CodeTypeConstructor)e); + ValidateTypeConstructor(codeTypeConstructor); } else { @@ -401,57 +401,57 @@ private void ValidateStatement(CodeStatement e) { // nothing } - else if (e is CodeMethodReturnStatement) + else if (e is CodeMethodReturnStatement codeMethodReturnStatement) { - ValidateMethodReturnStatement((CodeMethodReturnStatement)e); + ValidateMethodReturnStatement(codeMethodReturnStatement); } - else if (e is CodeConditionStatement) + else if (e is CodeConditionStatement codeConditionStatement) { - ValidateConditionStatement((CodeConditionStatement)e); + ValidateConditionStatement(codeConditionStatement); } - else if (e is CodeTryCatchFinallyStatement) + else if (e is CodeTryCatchFinallyStatement codeTryCatchFinallyStatement) { - ValidateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e); + ValidateTryCatchFinallyStatement(codeTryCatchFinallyStatement); } - else if (e is CodeAssignStatement) + else if (e is CodeAssignStatement codeAssignStatement) { - ValidateAssignStatement((CodeAssignStatement)e); + ValidateAssignStatement(codeAssignStatement); } - else if (e is CodeExpressionStatement) + else if (e is CodeExpressionStatement codeExpressionStatement) { - ValidateExpressionStatement((CodeExpressionStatement)e); + ValidateExpressionStatement(codeExpressionStatement); } - else if (e is CodeIterationStatement) + else if (e is CodeIterationStatement codeIterationStatement) { - ValidateIterationStatement((CodeIterationStatement)e); + ValidateIterationStatement(codeIterationStatement); } - else if (e is CodeThrowExceptionStatement) + else if (e is CodeThrowExceptionStatement codeThrowExceptionStatement) { - ValidateThrowExceptionStatement((CodeThrowExceptionStatement)e); + ValidateThrowExceptionStatement(codeThrowExceptionStatement); } else if (e is CodeSnippetStatement) { // do nothing } - else if (e is CodeVariableDeclarationStatement) + else if (e is CodeVariableDeclarationStatement codeVariableDeclarationStatement) { - ValidateVariableDeclarationStatement((CodeVariableDeclarationStatement)e); + ValidateVariableDeclarationStatement(codeVariableDeclarationStatement); } - else if (e is CodeAttachEventStatement) + else if (e is CodeAttachEventStatement codeAttachEventStatement) { - ValidateAttachEventStatement((CodeAttachEventStatement)e); + ValidateAttachEventStatement(codeAttachEventStatement); } - else if (e is CodeRemoveEventStatement) + else if (e is CodeRemoveEventStatement codeRemoveEventStatement) { - ValidateRemoveEventStatement((CodeRemoveEventStatement)e); + ValidateRemoveEventStatement(codeRemoveEventStatement); } - else if (e is CodeGotoStatement) + else if (e is CodeGotoStatement codeGotoStatement) { - ValidateGotoStatement((CodeGotoStatement)e); + ValidateGotoStatement(codeGotoStatement); } - else if (e is CodeLabeledStatement) + else if (e is CodeLabeledStatement codeLabeledStatement) { - ValidateLabeledStatement((CodeLabeledStatement)e); + ValidateLabeledStatement(codeLabeledStatement); } else { @@ -665,89 +665,89 @@ private static void ValidateIdentifier(object e, string propertyName, string ide private void ValidateExpression(CodeExpression e) { - if (e is CodeArrayCreateExpression) + if (e is CodeArrayCreateExpression codeArrayCreateExpression) { - ValidateArrayCreateExpression((CodeArrayCreateExpression)e); + ValidateArrayCreateExpression(codeArrayCreateExpression); } else if (e is CodeBaseReferenceExpression) { // Nothing to validate } - else if (e is CodeBinaryOperatorExpression) + else if (e is CodeBinaryOperatorExpression codeBinaryOperatorExpression) { - ValidateBinaryOperatorExpression((CodeBinaryOperatorExpression)e); + ValidateBinaryOperatorExpression(codeBinaryOperatorExpression); } - else if (e is CodeCastExpression) + else if (e is CodeCastExpression codeCastExpression) { - ValidateCastExpression((CodeCastExpression)e); + ValidateCastExpression(codeCastExpression); } - else if (e is CodeDefaultValueExpression) + else if (e is CodeDefaultValueExpression codeDefaultValueExpression) { - ValidateDefaultValueExpression((CodeDefaultValueExpression)e); + ValidateDefaultValueExpression(codeDefaultValueExpression); } - else if (e is CodeDelegateCreateExpression) + else if (e is CodeDelegateCreateExpression codeDelegateCreateExpression) { - ValidateDelegateCreateExpression((CodeDelegateCreateExpression)e); + ValidateDelegateCreateExpression(codeDelegateCreateExpression); } - else if (e is CodeFieldReferenceExpression) + else if (e is CodeFieldReferenceExpression codeFieldReferenceExpression) { - ValidateFieldReferenceExpression((CodeFieldReferenceExpression)e); + ValidateFieldReferenceExpression(codeFieldReferenceExpression); } - else if (e is CodeArgumentReferenceExpression) + else if (e is CodeArgumentReferenceExpression codeArgumentReferenceExpression) { - ValidateArgumentReferenceExpression((CodeArgumentReferenceExpression)e); + ValidateArgumentReferenceExpression(codeArgumentReferenceExpression); } - else if (e is CodeVariableReferenceExpression) + else if (e is CodeVariableReferenceExpression codeVariableReferenceExpression) { - ValidateVariableReferenceExpression((CodeVariableReferenceExpression)e); + ValidateVariableReferenceExpression(codeVariableReferenceExpression); } - else if (e is CodeIndexerExpression) + else if (e is CodeIndexerExpression codeIndexerExpression) { - ValidateIndexerExpression((CodeIndexerExpression)e); + ValidateIndexerExpression(codeIndexerExpression); } - else if (e is CodeArrayIndexerExpression) + else if (e is CodeArrayIndexerExpression codeArrayIndexerExpression) { - ValidateArrayIndexerExpression((CodeArrayIndexerExpression)e); + ValidateArrayIndexerExpression(codeArrayIndexerExpression); } else if (e is CodeSnippetExpression) { // do nothing } - else if (e is CodeMethodInvokeExpression) + else if (e is CodeMethodInvokeExpression codeMethodInvokeExpression) { - ValidateMethodInvokeExpression((CodeMethodInvokeExpression)e); + ValidateMethodInvokeExpression(codeMethodInvokeExpression); } - else if (e is CodeMethodReferenceExpression) + else if (e is CodeMethodReferenceExpression codeMethodReferenceExpression) { - ValidateMethodReferenceExpression((CodeMethodReferenceExpression)e); + ValidateMethodReferenceExpression(codeMethodReferenceExpression); } - else if (e is CodeEventReferenceExpression) + else if (e is CodeEventReferenceExpression codeEventReferenceExpression) { - ValidateEventReferenceExpression((CodeEventReferenceExpression)e); + ValidateEventReferenceExpression(codeEventReferenceExpression); } - else if (e is CodeDelegateInvokeExpression) + else if (e is CodeDelegateInvokeExpression codeDelegateInvokeExpression) { - ValidateDelegateInvokeExpression((CodeDelegateInvokeExpression)e); + ValidateDelegateInvokeExpression(codeDelegateInvokeExpression); } - else if (e is CodeObjectCreateExpression) + else if (e is CodeObjectCreateExpression codeObjectCreateExpression) { - ValidateObjectCreateExpression((CodeObjectCreateExpression)e); + ValidateObjectCreateExpression(codeObjectCreateExpression); } - else if (e is CodeParameterDeclarationExpression) + else if (e is CodeParameterDeclarationExpression codeParameterDeclarationExpression) { - ValidateParameterDeclarationExpression((CodeParameterDeclarationExpression)e); + ValidateParameterDeclarationExpression(codeParameterDeclarationExpression); } - else if (e is CodeDirectionExpression) + else if (e is CodeDirectionExpression codeDirectionExpression) { - ValidateDirectionExpression((CodeDirectionExpression)e); + ValidateDirectionExpression(codeDirectionExpression); } else if (e is CodePrimitiveExpression) { // do nothing } - else if (e is CodePropertyReferenceExpression) + else if (e is CodePropertyReferenceExpression codePropertyReferenceExpression) { - ValidatePropertyReferenceExpression((CodePropertyReferenceExpression)e); + ValidatePropertyReferenceExpression(codePropertyReferenceExpression); } else if (e is CodePropertySetValueReferenceExpression) { @@ -757,13 +757,13 @@ private void ValidateExpression(CodeExpression e) { // Do nothing } - else if (e is CodeTypeReferenceExpression) + else if (e is CodeTypeReferenceExpression codeTypeReferenceExpression) { - ValidateTypeReference(((CodeTypeReferenceExpression)e).Type); + ValidateTypeReference(codeTypeReferenceExpression.Type); } - else if (e is CodeTypeOfExpression) + else if (e is CodeTypeOfExpression codeTypeOfExpression) { - ValidateTypeOfExpression((CodeTypeOfExpression)e); + ValidateTypeOfExpression(codeTypeOfExpression); } else { @@ -928,13 +928,13 @@ private static void ValidateCodeDirectives(CodeDirectiveCollection e) private static void ValidateCodeDirective(CodeDirective e) { - if (e is CodeChecksumPragma) + if (e is CodeChecksumPragma codeChecksumPragma) { - ValidateChecksumPragma((CodeChecksumPragma)e); + ValidateChecksumPragma(codeChecksumPragma); } - else if (e is CodeRegionDirective) + else if (e is CodeRegionDirective codeRegionDirective) { - ValidateRegionDirective((CodeRegionDirective)e); + ValidateRegionDirective(codeRegionDirective); } else { @@ -954,8 +954,8 @@ private static void ValidateRegionDirective(CodeRegionDirective e) throw new ArgumentException(SR.Format(SR.InvalidRegion, e.RegionText), nameof(e)); } - private bool IsCurrentInterface => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; + private bool IsCurrentInterface => _currentClass != null && _currentClass is not CodeTypeDelegate ? _currentClass.IsInterface : false; - private bool IsCurrentEnum => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; + private bool IsCurrentEnum => _currentClass != null && _currentClass is not CodeTypeDelegate ? _currentClass.IsEnum : false; } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray.cs index ba632420ee08da..20a4aa3e86408c 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray.cs @@ -425,9 +425,9 @@ public static ImmutableArray.Builder CreateBuilder(int initialCapacity) /// An immutable array containing the specified items. public static ImmutableArray ToImmutableArray(this IEnumerable items) { - if (items is ImmutableArray) + if (items is ImmutableArray immutableArray) { - return (ImmutableArray)items; + return immutableArray; } return CreateRange(items); diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs index 9b010bbca060bd..e9229d16b6d158 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs @@ -269,13 +269,13 @@ void IDictionary.Add(object key, object? value) if (default(TValue) != null) // null is an invalid value for Value types ArgumentNullException.ThrowIfNull(value); - if (!(key is TKey)) + if (key is not TKey tKey) throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key)); - if (!(value is TValue) && value != null) // null is a valid value for Reference Types + if (value is not TValue && value != null) // null is a valid value for Reference Types throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); - Add((TKey)key, (TValue)value!); + Add(tKey, (TValue)value!); } // Returns the number of entries in this sorted list. diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs index 33f34d7552a6e3..db75b8529d9332 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs @@ -89,7 +89,7 @@ public SortedSet(IEnumerable collection, IComparer? comparer) // These are explicit type checks in the mold of HashSet. It would have worked better with // something like an ISorted interface. (We could make this work for SortedList.Keys, etc.) SortedSet? sortedSet = collection as SortedSet; - if (sortedSet != null && !(sortedSet is TreeSubSet) && HasEqualComparer(sortedSet)) + if (sortedSet != null && sortedSet is not TreeSubSet && HasEqualComparer(sortedSet)) { if (sortedSet.Count > 0) { diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs index 13862e30745547..68489cbbc0f362 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs @@ -143,15 +143,15 @@ protected override IEnumerable GetCustomAttributes(System.Reflection.Mem attributeList = element.Item2; if (attributeList != null) { - if (element.Item1 is MemberInfo) + if (element.Item1 is MemberInfo memberInfo) { List memberAttributes; - switch (((MemberInfo)element.Item1).MemberType) + switch (memberInfo.MemberType) { case MemberTypes.Constructor: - if (!_memberInfos.TryGetValue((MemberInfo)element.Item1, out memberAttributes)) + if (!_memberInfos.TryGetValue(memberInfo, out memberAttributes)) { - _memberInfos.Add((MemberInfo)element.Item1, element.Item2); + _memberInfos.Add(memberInfo, element.Item2); } else { @@ -161,9 +161,9 @@ protected override IEnumerable GetCustomAttributes(System.Reflection.Mem case MemberTypes.TypeInfo: case MemberTypes.NestedType: case MemberTypes.Property: - if (!_memberInfos.TryGetValue((MemberInfo)element.Item1, out memberAttributes)) + if (!_memberInfos.TryGetValue(memberInfo, out memberAttributes)) { - _memberInfos.Add((MemberInfo)element.Item1, element.Item2); + _memberInfos.Add(memberInfo, element.Item2); } else { @@ -176,12 +176,12 @@ protected override IEnumerable GetCustomAttributes(System.Reflection.Mem } else { - if (!(element.Item1 is ParameterInfo)) + if (element.Item1 is not ParameterInfo parameterInfo) throw new Exception(SR.Diagnostic_InternalExceptionMessage); // Item contains as Constructor parameter to configure - if (!_parameters.TryGetValue((ParameterInfo)element.Item1, out List parameterAttributes)) + if (!_parameters.TryGetValue(parameterInfo, out List parameterAttributes)) { - _parameters.Add((ParameterInfo)element.Item1, element.Item2); + _parameters.Add(parameterInfo, element.Item2); } else { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs index 44d5bd954f6277..3e75f425c6a03c 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs @@ -127,9 +127,9 @@ private void ApplyResources(object value, Type typeFromValue, string objectName, } bool componentReflect = false; - if (value is IComponent) + if (value is IComponent component) { - ISite? site = ((IComponent)value).Site; + ISite? site = component.Site; if (site != null && site.DesignMode) { componentReflect = true; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/InstanceDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/InstanceDescriptor.cs index 34b4ebd330eb39..3b2b17e1e5f91b 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/InstanceDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/InstanceDescriptor.cs @@ -125,21 +125,21 @@ public InstanceDescriptor(MemberInfo? member, ICollection? arguments, bool isCom } } - if (MemberInfo is ConstructorInfo) + if (MemberInfo is ConstructorInfo constructorInfo) { - return ((ConstructorInfo)MemberInfo).Invoke(translatedArguments); + return constructorInfo.Invoke(translatedArguments); } - else if (MemberInfo is MethodInfo) + else if (MemberInfo is MethodInfo methodInfo) { - return ((MethodInfo)MemberInfo).Invoke(null, translatedArguments); + return methodInfo.Invoke(null, translatedArguments); } - else if (MemberInfo is PropertyInfo) + else if (MemberInfo is PropertyInfo propertyInfo) { - return ((PropertyInfo)MemberInfo).GetValue(null, translatedArguments); + return propertyInfo.GetValue(null, translatedArguments); } - else if (MemberInfo is FieldInfo) + else if (MemberInfo is FieldInfo fieldInfo) { - return ((FieldInfo)MemberInfo).GetValue(null); + return fieldInfo.GetValue(null); } return null; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs index a574915f74108d..fb8731009e31a4 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs @@ -80,7 +80,7 @@ public virtual void AddService(Type serviceType, object serviceInstance, bool pr // ArgumentNullException.ThrowIfNull(serviceType); ArgumentNullException.ThrowIfNull(serviceInstance); - if (!(serviceInstance is ServiceCreatorCallback) && !serviceInstance.GetType().IsCOMObject && !serviceType.IsInstanceOfType(serviceInstance)) + if (serviceInstance is not ServiceCreatorCallback && !serviceInstance.GetType().IsCOMObject && !serviceType.IsInstanceOfType(serviceInstance)) { throw new ArgumentException(SR.Format(SR.ErrorInvalidServiceInstance, serviceType.FullName)); } @@ -153,9 +153,9 @@ protected virtual void Dispose(bool disposing) { foreach (object? o in serviceCollection.Values) { - if (o is IDisposable) + if (o is IDisposable disposable) { - ((IDisposable)o).Dispose(); + disposable.Dispose(); } } } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs index 11f0c1c6aab08c..4888f2dcdb673d 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs @@ -103,11 +103,11 @@ private static long GetEnumValue(bool isUnderlyingTypeUInt64, object enumVal, Cu throw new FormatException(SR.Format(SR.ConvertInvalidPrimitive, (string)value, EnumType.Name), e); } } - else if (value is Enum[]) + else if (value is Enum[] enums) { bool isUnderlyingTypeUInt64 = Enum.GetUnderlyingType(EnumType) == typeof(ulong); long finalValue = 0; - foreach (Enum e in (Enum[])value) + foreach (Enum e in enums) { finalValue |= GetEnumValue(isUnderlyingTypeUInt64, e, culture); } @@ -147,9 +147,9 @@ private static long GetEnumValue(bool isUnderlyingTypeUInt64, object enumVal, Cu // a ToObject call on enum. // Type underlyingType = Enum.GetUnderlyingType(EnumType); - if (value is IConvertible) + if (value is IConvertible convertible) { - object convertedValue = ((IConvertible)value).ToType(underlyingType, culture); + object convertedValue = convertible.ToType(underlyingType, culture); MethodInfo? method = typeof(Enum).GetMethod("ToObject", new Type[] { typeof(Type), underlyingType }); if (method != null) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InheritanceAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InheritanceAttribute.cs index fb45a60626af01..a5f808e9378316 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InheritanceAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InheritanceAttribute.cs @@ -84,12 +84,12 @@ public override bool Equals([NotNullWhen(true)] object? value) return true; } - if (!(value is InheritanceAttribute)) + if (value is not InheritanceAttribute inheritanceAttribute) { return false; } - InheritanceLevel valueLevel = ((InheritanceAttribute)value).InheritanceLevel; + InheritanceLevel valueLevel = inheritanceAttribute.InheritanceLevel; return (valueLevel == InheritanceLevel); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PasswordPropertyTextAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PasswordPropertyTextAttribute.cs index 0299f4ad471616..52ffd0134443e4 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PasswordPropertyTextAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PasswordPropertyTextAttribute.cs @@ -56,9 +56,9 @@ public PasswordPropertyTextAttribute(bool password) /// public override bool Equals([NotNullWhen(true)] object? o) { - if (o is PasswordPropertyTextAttribute) + if (o is PasswordPropertyTextAttribute passwordPropertyTextAttribute) { - return ((PasswordPropertyTextAttribute)o).Password == Password; + return passwordPropertyTextAttribute.Password == Password; } return false; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptorCollection.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptorCollection.cs index e76ffff05bca76..9caae6717bd837 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptorCollection.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptorCollection.cs @@ -424,9 +424,9 @@ void IDictionary.Add(object key, object? value) bool IDictionary.Contains(object key) { - if (key is string) + if (key is string str) { - return this[(string)key] != null; + return this[str] != null; } return false; } @@ -441,9 +441,9 @@ bool IDictionary.Contains(object key) { get { - if (key is string) + if (key is string str) { - return this[(string)key]; + return this[str]; } return null; } @@ -455,27 +455,27 @@ bool IDictionary.Contains(object key) throw new NotSupportedException(); } - if (value != null && !(value is PropertyDescriptor)) + if (value != null && value is not PropertyDescriptor) { throw new ArgumentException(nameof(value)); } int index = -1; - if (key is int) + if (key is int num) { - index = (int)key; + index = num; if (index < 0 || index >= Count) { throw new IndexOutOfRangeException(); } } - else if (key is string) + else if (key is string str) { for (int i = 0; i < Count; i++) { - if (_properties[i]!.Name.Equals((string)key)) + if (_properties[i]!.Name.Equals(str)) { index = i; break; @@ -536,9 +536,9 @@ ICollection IDictionary.Values void IDictionary.Remove(object key) { - if (key is string) + if (key is string str) { - PropertyDescriptor? pd = this[(string)key]; + PropertyDescriptor? pd = this[str]; if (pd != null) { ((IList)this).Remove(pd); @@ -576,7 +576,7 @@ void IDictionary.Remove(object key) } - if (value != null && !(value is PropertyDescriptor)) + if (value != null && value is not PropertyDescriptor) { throw new ArgumentException(nameof(value)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/StringConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/StringConverter.cs index 2421a54a6f6826..56e4ad37aceda1 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/StringConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/StringConverter.cs @@ -25,9 +25,9 @@ public override bool CanConvertFrom(ITypeDescriptorContext? context, Type source /// public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object? value) { - if (value is string) + if (value is string str) { - return (string)value; + return str; } if (value == null) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs index 28b3c08e31061a..2f5c79fabf39dc 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs @@ -2339,7 +2339,7 @@ private static void Refresh(object component, bool refreshReflectionProvider) if (nodeType != null && type.IsAssignableFrom(nodeType) || nodeType == typeof(object)) { TypeDescriptionNode? node = (TypeDescriptionNode?)kvp.Value; - while (node != null && !(node.Provider is ReflectTypeDescriptionProvider)) + while (node != null && node.Provider is not ReflectTypeDescriptionProvider) { found = true; node = node.Next; @@ -2419,7 +2419,7 @@ public static void Refresh(Type type) if (nodeType != null && type.IsAssignableFrom(nodeType) || nodeType == typeof(object)) { TypeDescriptionNode? node = (TypeDescriptionNode?)kvp.Value; - while (node != null && !(node.Provider is ReflectTypeDescriptionProvider)) + while (node != null && node.Provider is not ReflectTypeDescriptionProvider) { found = true; node = node.Next; @@ -2477,7 +2477,7 @@ public static void Refresh(Module module) if (nodeType != null && nodeType.Module.Equals(module) || nodeType == typeof(object)) { TypeDescriptionNode? node = (TypeDescriptionNode?)kvp.Value; - while (node != null && !(node.Provider is ReflectTypeDescriptionProvider)) + while (node != null && node.Provider is not ReflectTypeDescriptionProvider) { refreshedTypes ??= new Hashtable(); refreshedTypes[nodeType] = nodeType; @@ -2596,7 +2596,7 @@ public static IComNativeDescriptorHandler? ComNativeDescriptorHandler set { TypeDescriptionNode? typeDescriptionNode = NodeFor(ComObjectType); - while (typeDescriptionNode != null && !(typeDescriptionNode.Provider is ComNativeDescriptionProvider)) + while (typeDescriptionNode != null && typeDescriptionNode.Provider is not ComNativeDescriptionProvider) { typeDescriptionNode = typeDescriptionNode.Next; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs index bf69e52414a17e..f64490bfb1a3f2 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs @@ -92,7 +92,7 @@ public override object CreateInstance(ITypeDescriptorContext? context, IDictiona object? x = propertyValues["X"]; object? y = propertyValues["Y"]; - if (x == null || y == null || !(x is int) || !(y is int)) + if (x == null || y == null || x is not int || y is not int) { throw new ArgumentException(SR.PropertyValueInvalidEntry); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs index 4a27a012b1d309..a6871654f464d3 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs @@ -102,7 +102,7 @@ public override object CreateInstance(ITypeDescriptorContext? context, IDictiona object? height = propertyValues["Height"]; if (x == null || y == null || width == null || height == null || - !(x is int) || !(y is int) || !(width is int) || !(height is int)) + x is not int || y is not int || width is not int || height is not int) { throw new ArgumentException(SR.PropertyValueInvalidEntry); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs index 74d189c26bf902..e5a471fe2e7c29 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs @@ -92,7 +92,7 @@ public override object CreateInstance(ITypeDescriptorContext? context, IDictiona object? width = propertyValues["Width"]; object? height = propertyValues["Height"]; - if (width == null || height == null || !(width is int) || !(height is int)) + if (width == null || height == null || width is not int || height is not int) { throw new ArgumentException(SR.PropertyValueInvalidEntry); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs index c53054b30fe73c..8bfef8bcc0cf7d 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs @@ -90,7 +90,7 @@ public override object CreateInstance(ITypeDescriptorContext? context, IDictiona object? width = propertyValues["Width"]; object? height = propertyValues["Height"]; - if (width == null || height == null || !(width is float) || !(height is float)) + if (width == null || height == null || width is not float || height is not float) { throw new ArgumentException(SR.PropertyValueInvalidEntry); } diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs index 424c03d8a9026a..f0fd74d7f51d5c 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs @@ -221,7 +221,7 @@ public override IEnumerable GetCustomAttributes(Type reflectedType, S } IEnumerable appliedAttributes; - if (!(member is TypeInfo) && member.DeclaringType != reflectedType) + if (member is not TypeInfo && member.DeclaringType != reflectedType) appliedAttributes = Enumerable.Empty(); else appliedAttributes = member.GetCustomAttributes(false); diff --git a/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs b/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs index 9dd45fdd66aef9..44dbf89ab4bb14 100644 --- a/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs +++ b/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs @@ -151,10 +151,10 @@ public bool TryUnwrapMetadataConstraint(string constraintName, out T constrai if (!_metadataConstraints.TryGetValue(constraintName, out object value)) return false; - if (!(value is T)) + if (value is not T t) return false; - constraintValue = (T)value; + constraintValue = t; if (_metadataConstraints.Count == 1) { remainingContract = new CompositionContract(_contractType, _contractName); @@ -195,7 +195,7 @@ internal static bool ConstraintEqual(IDictionary first, IDiction } else { - if (firstItem.Value is IEnumerable firstEnumerable && !(firstEnumerable is string)) + if (firstItem.Value is IEnumerable firstEnumerable && firstEnumerable is not string) { var secondEnumerable = secondValue as IEnumerable; if (secondEnumerable == null || !Enumerable.SequenceEqual(firstEnumerable.Cast(), secondEnumerable.Cast())) diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs index 8dd0b5cdc379b0..ead65896952d3f 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs @@ -14,7 +14,7 @@ public override IEnumerable GetCustomAttributes(Type reflectedType, R if (reflectedType == null) throw new ArgumentNullException(nameof(reflectedType)); if (member == null) throw new ArgumentNullException(nameof(member)); - if (!(member is TypeInfo) && member.DeclaringType != reflectedType) + if (member is not TypeInfo && member.DeclaringType != reflectedType) return Array.Empty(); return Attribute.GetCustomAttributes(member, false); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs index 8956757a223ba1..d1164fc0c8e0a3 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs @@ -453,17 +453,17 @@ private SettingsProperty CreateSetting(PropertyInfo propertyInfo) if (attribute == null) continue; - if (attribute is DefaultSettingValueAttribute) + if (attribute is DefaultSettingValueAttribute defaultSettingValueAttribute) { - settingsProperty.DefaultValue = ((DefaultSettingValueAttribute)attribute).Value; + settingsProperty.DefaultValue = defaultSettingValueAttribute.Value; } else if (attribute is ReadOnlyAttribute) { settingsProperty.IsReadOnly = true; } - else if (attribute is SettingsProviderAttribute) + else if (attribute is SettingsProviderAttribute settingsProviderAttribute) { - string providerTypeName = ((SettingsProviderAttribute)attribute).ProviderTypeName; + string providerTypeName = settingsProviderAttribute.ProviderTypeName; Type providerType = Type.GetType(providerTypeName); if (providerType == null) { @@ -490,9 +490,9 @@ private SettingsProperty CreateSetting(PropertyInfo propertyInfo) settingsProperty.Provider = settingsProvider; } - else if (attribute is SettingsSerializeAsAttribute) + else if (attribute is SettingsSerializeAsAttribute settingsSerializeAsAttribute) { - settingsProperty.SerializeAs = ((SettingsSerializeAsAttribute)attribute).SerializeAs; + settingsProperty.SerializeAs = settingsSerializeAsAttribute.SerializeAs; explicitSerialize = true; } else @@ -602,14 +602,14 @@ private SettingsProperty Initializer { _init.IsReadOnly = true; } - else if (attr is SettingsGroupNameAttribute) + else if (attr is SettingsGroupNameAttribute settingsGroupNameAttribute) { _context ??= new SettingsContext(); - _context["GroupName"] = ((SettingsGroupNameAttribute)attr).GroupName; + _context["GroupName"] = settingsGroupNameAttribute.GroupName; } - else if (attr is SettingsProviderAttribute) + else if (attr is SettingsProviderAttribute settingsProviderAttribute) { - string providerTypeName = ((SettingsProviderAttribute)attr).ProviderTypeName; + string providerTypeName = settingsProviderAttribute.ProviderTypeName; Type providerType = Type.GetType(providerTypeName); if (providerType != null) { @@ -628,9 +628,9 @@ private SettingsProperty Initializer throw new ConfigurationErrorsException(SR.Format(SR.ProviderTypeLoadFailed, providerTypeName)); } } - else if (attr is SettingsSerializeAsAttribute) + else if (attr is SettingsSerializeAsAttribute settingsSerializeAsAttribute) { - _init.SerializeAs = ((SettingsSerializeAsAttribute)attr).SerializeAs; + _init.SerializeAs = settingsSerializeAsAttribute.SerializeAs; _explicitSerializeOnClass = true; } else diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs index 37e722516d37ba..af6249509a4f4d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs @@ -155,7 +155,7 @@ protected internal object this[ConfigurationProperty prop] } // If its an invalid value - throw the error now - if (o is InvalidPropValue) throw ((InvalidPropValue)o).Error; + if (o is InvalidPropValue invalidPropValue) throw invalidPropValue.Error; return o; } @@ -1089,7 +1089,7 @@ protected internal virtual bool SerializeElement(XmlWriter writer, bool serializ string xmlValue; // If this was an invalid string value and was cached - write it out as is - if (value is InvalidPropValue) xmlValue = ((InvalidPropValue)value).Value; + if (value is InvalidPropValue invalidPropValue) xmlValue = invalidPropValue.Value; else { prop.Validate(value); @@ -1135,7 +1135,7 @@ protected internal virtual bool SerializeElement(XmlWriter writer, bool serializ ConfigurationProperty prop = props[key]; // if we are writing a remove and the sub element is not part of the key don't write it. - if ((serializeCollectionKey && !prop.IsKey) || !(value is ConfigurationElement)) + if ((serializeCollectionKey && !prop.IsKey) || value is not ConfigurationElement) continue; if (((_lockedElementsList != null) && _lockedElementsList.DefinedInParent(key)) || @@ -1788,9 +1788,9 @@ internal static void ValidateElement(ConfigurationElement elem, ConfigurationVal // At deserializtion time the per-element validator for collection items will get executed as part of their deserialization logic // However we dont perform validation in the serialization logic ( because at that time the object is unmerged and not all data is present ) // so we have to do that validation here. - if (elem is ConfigurationElementCollection) + if (elem is ConfigurationElementCollection configurationElementCollection) { - IEnumerator it = ((ConfigurationElementCollection)elem).GetElementsEnumerator(); + IEnumerator it = configurationElementCollection.GetElementsEnumerator(); while (it.MoveNext()) ValidateElement((ConfigurationElement)it.Current, null, true); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs index f0da80518597ae..12500222fd9690 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs @@ -35,14 +35,14 @@ public static NameValueCollection AppSettings get { object section = GetSection("appSettings"); - if (!(section is NameValueCollection)) + if (section is not NameValueCollection nameValueCollection) { // If config is null or not the type we expect, the declaration was changed. // Treat it as a configuration error. throw new ConfigurationErrorsException(SR.Config_appsettings_declaration_invalid); } - return (NameValueCollection)section; + return nameValueCollection; } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs index 01d6d7db418252..a0b0d41e7240eb 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs @@ -82,15 +82,15 @@ internal ConfigurationProperty(PropertyInfo info) // Look for relevant attributes foreach (Attribute attribute in Attribute.GetCustomAttributes(info)) { - if (attribute is TypeConverterAttribute) + if (attribute is TypeConverterAttribute typeConverterAttribute) { - typeConverter = TypeUtil.CreateInstance(((TypeConverterAttribute)attribute).ConverterTypeName); + typeConverter = TypeUtil.CreateInstance(typeConverterAttribute.ConverterTypeName); } - else if (attribute is ConfigurationPropertyAttribute) + else if (attribute is ConfigurationPropertyAttribute configurationPropertyAttribute) { - propertyAttribute = (ConfigurationPropertyAttribute)attribute; + propertyAttribute = configurationPropertyAttribute; } - else if (attribute is ConfigurationValidatorAttribute) + else if (attribute is ConfigurationValidatorAttribute configurationValidatorAttribute) { if (validator != null) { @@ -103,17 +103,17 @@ internal ConfigurationProperty(PropertyInfo info) SR.Format(SR.Validator_multiple_validator_attributes, info.Name)); } - ConfigurationValidatorAttribute validatorAttribute = (ConfigurationValidatorAttribute)attribute; + ConfigurationValidatorAttribute validatorAttribute = configurationValidatorAttribute; validatorAttribute.SetDeclaringType(info.DeclaringType); validator = validatorAttribute.ValidatorInstance; } - else if (attribute is DescriptionAttribute) + else if (attribute is DescriptionAttribute descriptionAttribute2) { - descriptionAttribute = (DescriptionAttribute)attribute; + descriptionAttribute = descriptionAttribute2; } - else if (attribute is DefaultValueAttribute) + else if (attribute is DefaultValueAttribute defaultValueAttribute2) { - defaultValueAttribute = (DefaultValueAttribute)attribute; + defaultValueAttribute = defaultValueAttribute2; } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs index 2ac516a5097fe6..a113745413edb4 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationValues.cs @@ -91,10 +91,10 @@ private ConfigurationValue CreateConfigValue(object value, ConfigurationValueFla { if (value != null) { - if (value is ConfigurationElement) + if (value is ConfigurationElement configurationElement) { _containsElement = true; - ((ConfigurationElement)value).AssociateContext(_configRecord); + configurationElement.AssociateContext(_configRecord); } else { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs index b2a2ee7085f080..6602059ad25bd1 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs @@ -496,7 +496,7 @@ private void Upgrade(SettingsContext context, SettingsPropertyCollection propert SettingsPropertyCollection upgradeProperties = new SettingsPropertyCollection(); foreach (SettingsProperty sp in properties) { - if (!(sp.Attributes[typeof(NoSettingsVersionUpgradeAttribute)] is NoSettingsVersionUpgradeAttribute)) + if (sp.Attributes[typeof(NoSettingsVersionUpgradeAttribute)] is not NoSettingsVersionUpgradeAttribute) { upgradeProperties.Add(sp); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs index 757bae6c65b6db..34301eb3841fd9 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs @@ -13,7 +13,7 @@ public override void Add(ProviderBase provider) { ArgumentNullException.ThrowIfNull(provider); - if (!(provider is ProtectedConfigurationProvider)) + if (provider is not ProtectedConfigurationProvider) { throw new ArgumentException( SR.Format(SR.Config_provider_must_implement_type, diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs index 894ca9122b9dd3..db29e85bb14d7d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs @@ -38,7 +38,7 @@ public object PropertyValue Deserialized = true; } - if (_value != null && !Property.PropertyType.IsPrimitive && !(_value is string) && !(_value is DateTime)) + if (_value != null && !Property.PropertyType.IsPrimitive && _value is not string && _value is not DateTime) { UsingDefaultValue = false; _changedSinceLastSerialized = true; @@ -85,9 +85,9 @@ private object Deserialize() bool throwBinaryFormatterDeprecationException = false; try { - if (SerializedValue is string) + if (SerializedValue is string str) { - value = GetObjectFromString(Property.PropertyType, Property.SerializeAs, (string)SerializedValue); + value = GetObjectFromString(Property.PropertyType, Property.SerializeAs, str); } else if (SerializedValue is byte[] serializedBytes) { @@ -130,7 +130,7 @@ private object Deserialize() else return null; } - if (!(Property.DefaultValue is string)) + if (Property.DefaultValue is not string) { value = Property.DefaultValue; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValueCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValueCollection.cs index 3563b1628c17ed..28904cdba137ea 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValueCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValueCollection.cs @@ -42,7 +42,7 @@ public void Remove(string name) object pos = _indices[name]; - if (pos == null || !(pos is int)) + if (pos == null || pos is not int) return; int ipos = (int)pos; @@ -69,7 +69,7 @@ public SettingsPropertyValue this[string name] { object pos = _indices[name]; - if (pos == null || !(pos is int)) + if (pos == null || pos is not int) return null; int ipos = (int)pos; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs index 61548282e0490e..d4035bc6726fe6 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs @@ -11,7 +11,7 @@ public override void Add(ProviderBase provider) { ArgumentNullException.ThrowIfNull(provider); - if (!(provider is SettingsProvider)) + if (provider is not SettingsProvider) { throw new ArgumentException(SR.Format(SR.Config_provider_must_implement_type, typeof(SettingsProvider)), nameof(provider)); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SubclassTypeValidator.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SubclassTypeValidator.cs index 6fcde53396b382..101e893ad5e511 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SubclassTypeValidator.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SubclassTypeValidator.cs @@ -26,7 +26,7 @@ public override void Validate(object value) if (value == null) return; // Make a check here since value.GetType() returns RuntimeType rather then Type - if (!(value is Type)) ValidatorUtils.HelperParamValidation(value, typeof(Type)); + if (value is not Type) ValidatorUtils.HelperParamValidation(value, typeof(Type)); if (!_base.IsAssignableFrom((Type)value)) { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeNameConverter.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeNameConverter.cs index 6fc28afe5b6fab..0f35996f83f65e 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeNameConverter.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/TypeNameConverter.cs @@ -11,7 +11,7 @@ public sealed class TypeNameConverter : ConfigurationConverterBase public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { // Make the check here since for some reason value.GetType is not System.Type but RuntimeType - if (!(value is Type)) ValidateType(value, typeof(Type)); + if (value is not Type) ValidateType(value, typeof(Type)); string result = null; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs index 2a540c4a3d9292..4a606d2b87e11f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs @@ -69,10 +69,10 @@ public override int CompareValueTo(int recordNo1, object? value) { object valueNo1 = Get(recordNo1); - if (valueNo1 is IComparable) + if (valueNo1 is IComparable comparable) { if (value!.GetType() == valueNo1.GetType()) - return ((IComparable)valueNo1).CompareTo(value); + return comparable.CompareTo(value); } if (valueNo1 == value) @@ -108,11 +108,11 @@ private int CompareTo(object? valueNo1, object? valueNo2) if (valueNo2 == _nullValue) return 1; - if (valueNo1 is IComparable) + if (valueNo1 is IComparable comparable) { try { - return ((IComparable)valueNo1).CompareTo(valueNo2); + return comparable.CompareTo(valueNo2); } catch (ArgumentException e) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs index bba7cf4dc34143..fce182ec08bda2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SQLConvert.cs @@ -352,9 +352,9 @@ public static object ChangeTypeForDefaultValue(object value, Type type, IFormatP if ((DBNull.Value == value) || (null == value)) { return DBNull.Value; } return BigIntegerStorage.ConvertToBigInteger(value, formatProvider); } - else if (value is System.Numerics.BigInteger) + else if (value is System.Numerics.BigInteger bigInteger) { - return BigIntegerStorage.ConvertFromBigInteger((System.Numerics.BigInteger)value, type, formatProvider); + return BigIntegerStorage.ConvertFromBigInteger(bigInteger, type, formatProvider); } return ChangeType2(value, DataStorage.GetStorageType(type), type, formatProvider); diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs index 7c3fb20e2e8af0..c8712186ca936e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs @@ -102,16 +102,16 @@ internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign) } } - if (constraint is UniqueConstraint) + if (constraint is UniqueConstraint uniqueConstraint) { - if (((UniqueConstraint)constraint)._bPrimaryKey) + if (uniqueConstraint._bPrimaryKey) { if (Table._primaryKey != null) { throw ExceptionBuilder.AddPrimaryKeyConstraint(); } } - AddUniqueConstraint((UniqueConstraint)constraint); + AddUniqueConstraint(uniqueConstraint); } else if (constraint is ForeignKeyConstraint fk) { @@ -135,11 +135,11 @@ internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign) ArrayAdd(constraint); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, constraint)); - if (constraint is UniqueConstraint) + if (constraint is UniqueConstraint uniqueConstraint2) { - if (((UniqueConstraint)constraint)._bPrimaryKey) + if (uniqueConstraint2._bPrimaryKey) { - Table.PrimaryKey = ((UniqueConstraint)constraint).ColumnsReference; + Table.PrimaryKey = uniqueConstraint2.ColumnsReference; } } } @@ -381,7 +381,7 @@ private void BaseRemove(Constraint constraint) UnregisterName(constraint.ConstraintName); constraint.InCollection = false; - if (constraint is UniqueConstraint) + if (constraint is UniqueConstraint uniqueConstraint) { for (int i = 0; i < Table.ChildRelations.Count; i++) { @@ -389,7 +389,7 @@ private void BaseRemove(Constraint constraint) if (rel.ParentKeyConstraint == constraint) rel.SetParentKeyConstraint(null); } - ((UniqueConstraint)constraint).ConstraintIndexClear(); + uniqueConstraint.ConstraintIndexClear(); } else if (constraint is ForeignKeyConstraint) { diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs index 407125f8d43e50..335a55099d547f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs @@ -34,9 +34,9 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( if (destinationType == typeof(InstanceDescriptor) && value is Constraint) { - if (value is UniqueConstraint) + if (value is UniqueConstraint uniqueConstraint) { - UniqueConstraint constr = (UniqueConstraint)value; + UniqueConstraint constr = uniqueConstraint; Reflection.ConstructorInfo ctor = typeof(UniqueConstraint).GetConstructor(new Type[] { typeof(string), typeof(string[]), typeof(bool) })!; if (ctor != null) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs index f65d56ac5cc227..79d306e6929e65 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs @@ -1620,7 +1620,7 @@ private static bool IsColumnMappingValid(StorageType typeCode, MappingType mappi internal static bool IsValueCustomTypeInstance(object value) => // if instance is not a storage supported type (built in or SQL types) - (DataStorage.IsTypeCustomType(value.GetType()) && !(value is Type)); + (DataStorage.IsTypeCustomType(value.GetType()) && value is not Type); internal bool ImplementsIXMLSerializable => _implementsIXMLSerializable; @@ -1953,7 +1953,7 @@ internal override void SetCurrent(object value, IFormatProvider formatProvider) internal override void SetCurrentAndIncrement(object value) { - Debug.Assert(null != value && DataColumn.IsAutoIncrementType(value.GetType()) && !(value is BigInteger), "unexpected value for autoincrement"); + Debug.Assert(null != value && DataColumn.IsAutoIncrementType(value.GetType()) && value is not BigInteger, "unexpected value for autoincrement"); long v = (long)SqlConvert.ChangeType2(value, StorageType.Int64, typeof(long), CultureInfo.InvariantCulture); if (BoundaryCheck(v)) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs index aa283840a1cd4a..2a49fb4023ea35 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -1676,9 +1676,9 @@ internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) return; } - if (reader is XmlTextReader) + if (reader is XmlTextReader xmlTextReader) { - ((XmlTextReader)reader).WhitespaceHandling = WhitespaceHandling.None; + xmlTextReader.WhitespaceHandling = WhitespaceHandling.None; } XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema @@ -2097,9 +2097,9 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) isEmptyDataSet = true; } - if (reader is XmlTextReader) + if (reader is XmlTextReader xmlTextReader) { - ((XmlTextReader)reader).WhitespaceHandling = WhitespaceHandling.Significant; + xmlTextReader.WhitespaceHandling = WhitespaceHandling.Significant; } XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema @@ -2612,9 +2612,9 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol // prepare and cleanup rowDiffId hashtable rowDiffIdUsage.Prepare(this); - if (reader is XmlTextReader) + if (reader is XmlTextReader xmlTextReader) { - ((XmlTextReader)reader).WhitespaceHandling = WhitespaceHandling.Significant; + xmlTextReader.WhitespaceHandling = WhitespaceHandling.Significant; } XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema @@ -3404,16 +3404,16 @@ internal bool ValidateLocaleConstraint() if (baseTable == null) { // the accessor is the table name. if we don't find it, return null. - if (currentProp is DataTablePropertyDescriptor) + if (currentProp is DataTablePropertyDescriptor dataTablePropertyDescriptor) { - return FindTable(((DataTablePropertyDescriptor)currentProp).Table, props, propStart + 1); + return FindTable(dataTablePropertyDescriptor.Table, props, propStart + 1); } return null; } - if (currentProp is DataRelationPropertyDescriptor) + if (currentProp is DataRelationPropertyDescriptor dataRelationPropertyDescriptor) { - return FindTable(((DataRelationPropertyDescriptor)currentProp).Relation.ChildTable, props, propStart + 1); + return FindTable(dataRelationPropertyDescriptor.Relation.ChildTable, props, propStart + 1); } return null; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs index f1c6e04e367646..4248df81bedd84 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -5768,9 +5768,9 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) EnforceConstraints = false; } - if (reader is XmlTextReader) + if (reader is XmlTextReader xmlTextReader) { - ((XmlTextReader)reader).WhitespaceHandling = WhitespaceHandling.Significant; + xmlTextReader.WhitespaceHandling = WhitespaceHandling.Significant; } XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema @@ -6008,8 +6008,8 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol EnforceConstraints = false; } - if (reader is XmlTextReader) - ((XmlTextReader)reader).WhitespaceHandling = WhitespaceHandling.Significant; + if (reader is XmlTextReader xmlTextReader) + xmlTextReader.WhitespaceHandling = WhitespaceHandling.Significant; XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs index a4f0d8e83e1ad8..9f01eef5f1cc7a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs @@ -92,9 +92,9 @@ internal override ExpressionNode Optimize() _op = Operators.IsNot; _right = un._right; } - if (_right is ZeroOpNode) + if (_right is ZeroOpNode zeroOpNode) { - if (((ZeroOpNode)_right)._op != Operators.Null) + if (zeroOpNode._op != Operators.Null) { throw ExprException.InvalidIsSyntax(); } @@ -119,9 +119,9 @@ internal override ExpressionNode Optimize() return new ZeroOpNode(Operators.Null); } - if (val is bool) + if (val is bool b) { - if ((bool)val) + if (b) return new ZeroOpNode(Operators.True); else return new ZeroOpNode(Operators.False); @@ -611,9 +611,9 @@ private object EvalBinaryOp(int op, ExpressionNode left, ExpressionNode right, D } case StorageType.TimeSpan: { - if (vLeft is DateTime) + if (vLeft is DateTime dateTime) { - value = (DateTime)vLeft - (DateTime)vRight; + value = dateTime - (DateTime)vRight; } else value = (TimeSpan)vLeft - (TimeSpan)vRight; @@ -921,16 +921,16 @@ If one of the operands is flase the result is false if ((vLeft == DBNull.Value) || (left.IsSqlColumn && DataStorage.IsObjectSqlNull(vLeft))) return DBNull.Value; - if ((!(vLeft is bool)) && (!(vLeft is SqlBoolean))) + if ((vLeft is not bool) && (vLeft is not SqlBoolean)) { vRight = BinaryNode.Eval(right, row, version, recordNos); typeMismatch = true; break; } - if (vLeft is bool) + if (vLeft is bool b2) { - if (!(bool)vLeft) + if (!b2) { value = false; break; @@ -948,15 +948,15 @@ If one of the operands is flase the result is false if ((vRight == DBNull.Value) || (right.IsSqlColumn && DataStorage.IsObjectSqlNull(vRight))) return DBNull.Value; - if ((!(vRight is bool)) && (!(vRight is SqlBoolean))) + if ((vRight is not bool) && (vRight is not SqlBoolean)) { typeMismatch = true; break; } - if (vRight is bool) + if (vRight is bool b3) { - value = (bool)vRight; + value = b3; break; } else @@ -976,7 +976,7 @@ If one of the operands is true the result is true if ((vLeft != DBNull.Value) && (!DataStorage.IsObjectSqlNull(vLeft))) { - if ((!(vLeft is bool)) && (!(vLeft is SqlBoolean))) + if ((vLeft is not bool) && (vLeft is not SqlBoolean)) { vRight = BinaryNode.Eval(right, row, version, recordNos); typeMismatch = true; @@ -997,7 +997,7 @@ If one of the operands is true the result is true if ((vLeft == DBNull.Value) || (DataStorage.IsObjectSqlNull(vLeft))) return vRight; - if ((!(vRight is bool)) && (!(vRight is SqlBoolean))) + if ((vRight is not bool) && (vRight is not SqlBoolean)) { typeMismatch = true; break; @@ -1084,7 +1084,7 @@ If one of the operands is true the result is true */ - if (!(right is FunctionNode)) + if (right is not FunctionNode functionNode) { // this is more like an Assert: should never happens, so we do not care about "nice" Exseptions throw ExprException.InWithoutParentheses(); @@ -1099,7 +1099,7 @@ If one of the operands is true the result is true value = false; - FunctionNode into = (FunctionNode)right; + FunctionNode into = functionNode; for (int i = 0; i < into._argumentCount; i++) { @@ -1540,7 +1540,7 @@ internal override object Eval(DataRow? row, DataRowVersion version) { object vRight = _right.Eval(row, version); - if (!(vRight is string) && !(vRight is SqlString)) + if (vRight is not string && vRight is not SqlString) { SetTypeMismatchError(_op, vLeft.GetType(), vRight.GetType()); } @@ -1563,7 +1563,7 @@ internal override object Eval(DataRow? row, DataRowVersion version) substring = _pattern; } - if (!(vLeft is string) && !(vLeft is SqlString)) + if (vLeft is not string && vLeft is not SqlString) { SetTypeMismatchError(_op, vLeft.GetType(), typeof(string)); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs index 3c97fb60228937..d03425a9c129b9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs @@ -254,18 +254,18 @@ internal static bool ToBoolean(object value) { if (IsUnknown(value)) return false; - if (value is bool) - return (bool)value; - if (value is SqlBoolean) + if (value is bool b) + return b; + if (value is SqlBoolean sqlBoolean) { - return (((SqlBoolean)value).IsTrue); + return (sqlBoolean.IsTrue); } //check for SqlString is not added, value for true and false should be given with String, not with SqlString - if (value is string) + if (value is string str) { try { - return bool.Parse((string)value); + return bool.Parse(str); } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs index 7ac2e41a04bb34..26ba7871939774 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs @@ -125,13 +125,13 @@ private object EvalUnaryOp(int op, object vl) throw ExprException.TypeMismatch(ToString()!); case Operators.Not: - if (vl is SqlBoolean) + if (vl is SqlBoolean sqlBoolean) { - if (((SqlBoolean)vl).IsFalse) + if (sqlBoolean.IsFalse) { return SqlBoolean.True; } - else if (((SqlBoolean)vl).IsTrue) + else if (sqlBoolean.IsTrue) { return SqlBoolean.False; } diff --git a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs index b8844d62c1f556..b4a46cb55c9d5d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs @@ -856,11 +856,11 @@ public virtual Rule DeleteRule /// public override bool Equals([NotNullWhen(true)] object? key) { - if (!(key is ForeignKeyConstraint)) + if (key is not ForeignKeyConstraint foreignKeyConstraint) { return false; } - ForeignKeyConstraint key2 = (ForeignKeyConstraint)key; + ForeignKeyConstraint key2 = foreignKeyConstraint; // The ParentKey and ChildKey completely identify the ForeignKeyConstraint return ParentKey.ColumnsEqual(key2.ParentKey) && ChildKey.ColumnsEqual(key2.ChildKey); diff --git a/src/libraries/System.Data.Common/src/System/Data/Select.cs b/src/libraries/System.Data.Common/src/System/Data/Select.cs index 6c0c440a80ff79..040dccab9e3799 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Select.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Select.cs @@ -71,9 +71,9 @@ private void AnalyzeExpression(BinaryNode expr) if (expr._op == Operators.And) { bool isLeft = false, isRight = false; - if (expr._left is BinaryNode) + if (expr._left is BinaryNode binaryNode) { - AnalyzeExpression((BinaryNode)expr._left); + AnalyzeExpression(binaryNode); if (_linearExpression == _expression) return; isLeft = true; @@ -99,9 +99,9 @@ private void AnalyzeExpression(BinaryNode expr) } } - if (expr._right is BinaryNode) + if (expr._right is BinaryNode binaryNode2) { - AnalyzeExpression((BinaryNode)expr._right); + AnalyzeExpression(binaryNode2); if (_linearExpression == _expression) return; isRight = true; @@ -504,9 +504,9 @@ public DataRow[] SelectRows() InitCandidateColumns(); Debug.Assert(_candidateColumns != null); - if (_expression is BinaryNode) + if (_expression is BinaryNode binaryNode) { - AnalyzeExpression((BinaryNode)_expression); + AnalyzeExpression(binaryNode); if (!_candidatesForBinarySearch) { _linearExpression = _expression; diff --git a/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs b/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs index 705a0f5a5509d7..8a5b6c06cd5c1b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/UniqueConstraint.cs @@ -391,10 +391,10 @@ private void Create(string? constraintName, DataColumn[] columns) /// public override bool Equals([NotNullWhen(true)] object? key2) { - if (!(key2 is UniqueConstraint)) + if (key2 is not UniqueConstraint uniqueConstraint) return false; - return Key.ColumnsEqual(((UniqueConstraint)key2).Key); + return Key.ColumnsEqual(uniqueConstraint.Key); } public override int GetHashCode() diff --git a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs index f4f2c3549eaece..c8377c4f0dccdf 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs @@ -49,10 +49,10 @@ internal void LoadSchema(XmlElement schemaRoot, DataSet ds) // Walk all the top level Element tags. for (XmlNode? n = schemaRoot.FirstChild; n != null; n = n.NextSibling) { - if (!(n is XmlElement)) + if (n is not XmlElement xmlElement) continue; - XmlElement child = (XmlElement)n; + XmlElement child = xmlElement; if (FEqualIdentity(child, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS)) { @@ -524,12 +524,12 @@ internal void HandleTypeNode(XmlElement typeNode, DataTable table, ArrayList tab for (XmlNode? n = typeNode.FirstChild; n != null; n = n.NextSibling) { - if (!(n is XmlElement)) + if (n is not XmlElement xmlElement) continue; if (FEqualIdentity(n, Keywords.XDR_ELEMENT, Keywords.XDRNS)) { - tableChild = HandleTable((XmlElement)n); + tableChild = HandleTable(xmlElement); if (tableChild != null) { tableChildren.Add(tableChild); @@ -540,7 +540,7 @@ internal void HandleTypeNode(XmlElement typeNode, DataTable table, ArrayList tab if (FEqualIdentity(n, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS) || FEqualIdentity(n, Keywords.XDR_ELEMENT, Keywords.XDRNS)) { - HandleColumn((XmlElement)n, table); + HandleColumn(xmlElement, table); continue; } } diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs index 7fc92eb3f0faf7..648b5b60d3b78b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -182,34 +182,34 @@ private void CollectElementsAnnotations(XmlSchema schema, ArrayList schemaList) foreach (object item in schema.Items) { - if (item is XmlSchemaAnnotation) + if (item is XmlSchemaAnnotation xmlSchemaAnnotation) { - _annotations!.Add((XmlSchemaAnnotation)item); + _annotations!.Add(xmlSchemaAnnotation); } if (item is XmlSchemaElement elem) { _elements!.Add(elem); _elementsTable![elem.QualifiedName] = elem; } - if (item is XmlSchemaAttribute) + if (item is XmlSchemaAttribute xmlSchemaAttribute) { - XmlSchemaAttribute attr = (XmlSchemaAttribute)item; + XmlSchemaAttribute attr = xmlSchemaAttribute; _attributes![attr.QualifiedName] = attr; } - if (item is XmlSchemaAttributeGroup) + if (item is XmlSchemaAttributeGroup xmlSchemaAttributeGroup) { - XmlSchemaAttributeGroup attr = (XmlSchemaAttributeGroup)item; + XmlSchemaAttributeGroup attr = xmlSchemaAttributeGroup; _attributeGroups![attr.QualifiedName] = attr; } - if (item is XmlSchemaType) + if (item is XmlSchemaType xmlSchemaType) { string? MSDATATargetNamespace = null; if (item is XmlSchemaSimpleType) { - MSDATATargetNamespace = XSDSchema.GetMsdataAttribute((XmlSchemaType)item, Keywords.TARGETNAMESPACE); + MSDATATargetNamespace = XSDSchema.GetMsdataAttribute(xmlSchemaType, Keywords.TARGETNAMESPACE); } - XmlSchemaType type = (XmlSchemaType)item; + XmlSchemaType type = xmlSchemaType; _schemaTypes![type.QualifiedName] = type; // if we have a User Defined simple type, cache it so later we may need for mapping @@ -535,28 +535,28 @@ private bool IsDatasetParticle(XmlSchemaParticle pt) foreach (XmlSchemaAnnotated el in items) { - if (el is XmlSchemaElement) + if (el is XmlSchemaElement xmlSchemaElement) { // pushing max occur of choice element to its imidiate children of type xs:elements - if (isChoice && pt.MaxOccurs > decimal.One && (((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType)) // we know frominference condition - ((XmlSchemaElement)el).MaxOccurs = pt.MaxOccurs; + if (isChoice && pt.MaxOccurs > decimal.One && (xmlSchemaElement.SchemaType is XmlSchemaComplexType)) // we know frominference condition + xmlSchemaElement.MaxOccurs = pt.MaxOccurs; - if (((XmlSchemaElement)el).RefName.Name.Length != 0) + if (xmlSchemaElement.RefName.Name.Length != 0) { - if (!FromInference || (((XmlSchemaElement)el).MaxOccurs != decimal.One && !(((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType))) + if (!FromInference || (xmlSchemaElement.MaxOccurs != decimal.One && xmlSchemaElement.SchemaType is not XmlSchemaComplexType)) continue; } - if (!IsTable((XmlSchemaElement)el)) + if (!IsTable(xmlSchemaElement)) return false; continue; } - if (el is XmlSchemaParticle) + if (el is XmlSchemaParticle xmlSchemaParticle) { - if (!IsDatasetParticle((XmlSchemaParticle)el)) + if (!IsDatasetParticle(xmlSchemaParticle)) return false; } } @@ -623,8 +623,8 @@ private static int DatasetElementCount(XmlSchemaObjectCollection elements) return null; // it's a table } - if (ct.BaseXmlSchemaType is XmlSchemaComplexType) - ct = (XmlSchemaComplexType)ct.BaseXmlSchemaType; + if (ct.BaseXmlSchemaType is XmlSchemaComplexType xmlSchemaComplexType) + ct = xmlSchemaComplexType; else break; } @@ -857,9 +857,9 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) private void HandleRelations(XmlSchemaAnnotation ann, bool fNested) { foreach (object __items in ann.Items) - if (__items is XmlSchemaAppInfo) + if (__items is XmlSchemaAppInfo xmlSchemaAppInfo) { - XmlNode[] relations = ((XmlSchemaAppInfo)__items).Markup!; + XmlNode[] relations = xmlSchemaAppInfo.Markup!; for (int i = 0; i < relations.Length; i++) if (FEqualIdentity(relations[i], Keywords.MSD_RELATION, Keywords.MSDNS)) HandleRelation((XmlElement)relations[i], fNested); @@ -868,12 +868,12 @@ private void HandleRelations(XmlSchemaAnnotation ann, bool fNested) internal static XmlSchemaObjectCollection? GetParticleItems(XmlSchemaParticle? pt) { - if (pt is XmlSchemaSequence) - return ((XmlSchemaSequence)pt).Items; - if (pt is XmlSchemaAll) - return ((XmlSchemaAll)pt).Items; - if (pt is XmlSchemaChoice) - return ((XmlSchemaChoice)pt).Items; + if (pt is XmlSchemaSequence xmlSchemaSequence) + return xmlSchemaSequence.Items; + if (pt is XmlSchemaAll xmlSchemaAll) + return xmlSchemaAll.Items; + if (pt is XmlSchemaChoice xmlSchemaChoice) + return xmlSchemaChoice.Items; if (pt is XmlSchemaAny) return null; // the code below is a little hack for the SOM behavior @@ -883,8 +883,8 @@ private void HandleRelations(XmlSchemaAnnotation ann, bool fNested) Items.Add(pt); return Items; } - if (pt is XmlSchemaGroupRef) - return GetParticleItems(((XmlSchemaGroupRef)pt).Particle); + if (pt is XmlSchemaGroupRef xmlSchemaGroupRef) + return GetParticleItems(xmlSchemaGroupRef.Particle); // should never get here. return null; } @@ -985,9 +985,9 @@ internal void HandleAttributes(XmlSchemaObjectCollection attributes, DataTable t { foreach (XmlSchemaObject so in attributes) { - if (so is XmlSchemaAttribute) + if (so is XmlSchemaAttribute xmlSchemaAttribute) { - HandleAttributeColumn((XmlSchemaAttribute)so, table, isBase); + HandleAttributeColumn(xmlSchemaAttribute, table, isBase); } else { // XmlSchemaAttributeGroupRef @@ -1007,9 +1007,9 @@ private void HandleAttributeGroup(XmlSchemaAttributeGroup attributeGroup, DataTa { foreach (XmlSchemaObject obj in attributeGroup.Attributes) { - if (obj is XmlSchemaAttribute) + if (obj is XmlSchemaAttribute xmlSchemaAttribute) { - HandleAttributeColumn((XmlSchemaAttribute)obj, table, isBase); + HandleAttributeColumn(xmlSchemaAttribute, table, isBase); } else { // XmlSchemaAttributeGroupRef @@ -1059,9 +1059,9 @@ internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayL if (!(ct.BaseXmlSchemaType is XmlSchemaComplexType && FromInference)) HandleAttributes(ccExtension.Attributes, table, isBase); - if (ct.BaseXmlSchemaType is XmlSchemaComplexType) + if (ct.BaseXmlSchemaType is XmlSchemaComplexType xmlSchemaComplexType) { - HandleComplexType((XmlSchemaComplexType)ct.BaseXmlSchemaType, table, tableChildren, isNillable); + HandleComplexType(xmlSchemaComplexType, table, tableChildren, isNillable); } else { @@ -1100,9 +1100,9 @@ internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayL if (cContent is XmlSchemaSimpleContentExtension ccExtension) { HandleAttributes(ccExtension.Attributes, table, isBase); - if (ct.BaseXmlSchemaType is XmlSchemaComplexType) + if (ct.BaseXmlSchemaType is XmlSchemaComplexType xmlSchemaComplexType2) { - HandleComplexType((XmlSchemaComplexType)ct.BaseXmlSchemaType, table, tableChildren, isNillable); + HandleComplexType(xmlSchemaComplexType2, table, tableChildren, isNillable); } else { @@ -1143,9 +1143,9 @@ internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayL if (ct.ContentModel is XmlSchemaComplexContent) { XmlSchemaAnnotated cContent = ((XmlSchemaComplexContent)(ct.ContentModel)).Content!; - if (cContent is XmlSchemaComplexContentExtension) + if (cContent is XmlSchemaComplexContentExtension xmlSchemaComplexContentExtension) { - return ((XmlSchemaComplexContentExtension)cContent).Particle; + return xmlSchemaComplexContentExtension.Particle; } else { @@ -2235,9 +2235,9 @@ internal void HandleAttributeColumn(XmlSchemaAttribute attrib, DataTable table, } } } - else if (typeNode is XmlSchemaElement) + else if (typeNode is XmlSchemaElement xmlSchemaElement) { - strType = ((XmlSchemaElement)typeNode).SchemaTypeName.Name; + strType = xmlSchemaElement.SchemaTypeName.Name; type = ParseDataType(strType); } else @@ -2378,15 +2378,15 @@ internal void HandleElementColumn(XmlSchemaElement elem, DataTable table, bool i type = ParseDataType(el.SchemaTypeName.Name); } } - else if (typeNode is XmlSchemaSimpleType) + else if (typeNode is XmlSchemaSimpleType xmlSchemaSimpleType) { XmlSchemaSimpleType? simpleTypeNode = typeNode as XmlSchemaSimpleType; xsdType = new SimpleType(simpleTypeNode!); // ((XmlSchemaSimpleType)typeNode).Name != null && ((XmlSchemaSimpleType)typeNode).Name.Length != 0 check is for annonymos simple type, // it should be user defined Named simple type - if (!string.IsNullOrEmpty(((XmlSchemaSimpleType)typeNode).Name) && ((XmlSchemaSimpleType)typeNode).QualifiedName.Namespace != Keywords.XSDNS) + if (!string.IsNullOrEmpty(xmlSchemaSimpleType.Name) && xmlSchemaSimpleType.QualifiedName.Namespace != Keywords.XSDNS) { - strType = ((XmlSchemaSimpleType)typeNode).QualifiedName.ToString(); // use qualified name + strType = xmlSchemaSimpleType.QualifiedName.ToString(); // use qualified name type = ParseDataType(strType); } else @@ -2411,9 +2411,9 @@ internal void HandleElementColumn(XmlSchemaElement elem, DataTable table, bool i } } } - else if (typeNode is XmlSchemaElement) + else if (typeNode is XmlSchemaElement xmlSchemaElement) { // theoratically no named simpletype should come here - strType = ((XmlSchemaElement)typeNode).SchemaTypeName.Name; + strType = xmlSchemaElement.SchemaTypeName.Name; type = ParseDataType(strType); } else if (typeNode is XmlSchemaComplexType) @@ -2627,9 +2627,9 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) foreach (XmlSchemaAnnotated el in items) { - if (el is XmlSchemaElement) + if (el is XmlSchemaElement xmlSchemaElement2) { - if (((XmlSchemaElement)el).RefName.Name.Length != 0) + if (xmlSchemaElement2.RefName.Name.Length != 0) { if (!FromInference) { @@ -2637,46 +2637,46 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) } else { - DataTable? tempTable = _ds.Tables.GetTable(XmlConvert.DecodeName(GetInstanceName((XmlSchemaElement)el)), node.QualifiedName.Namespace); + DataTable? tempTable = _ds.Tables.GetTable(XmlConvert.DecodeName(GetInstanceName(xmlSchemaElement2)), node.QualifiedName.Namespace); if (tempTable != null) { tableSequenceList.Add(tempTable); // if ref table is created, add it } bool isComplexTypeOrValidElementType = false; - if (node.ElementSchemaType != null || !(((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType)) + if (node.ElementSchemaType != null || xmlSchemaElement2.SchemaType is not XmlSchemaComplexType) { isComplexTypeOrValidElementType = true; } // bool isComplexTypeOrValidElementType = (node.ElementType != null || !(((XmlSchemaElement)el).SchemaType is XmlSchemaComplexType)); - if ((((XmlSchemaElement)el).MaxOccurs != decimal.One) && (!isComplexTypeOrValidElementType)) + if ((xmlSchemaElement2.MaxOccurs != decimal.One) && (!isComplexTypeOrValidElementType)) { continue; } } } - DataTable? child = HandleTable((XmlSchemaElement)el); + DataTable? child = HandleTable(xmlSchemaElement2); child?._fNestedInDataset = true; if (FromInference) { tableSequenceList.Add(child!); } } - else if (el is XmlSchemaChoice) + else if (el is XmlSchemaChoice xmlSchemaChoice) { // should we check for inference? - XmlSchemaObjectCollection choiceItems = ((XmlSchemaChoice)el).Items; + XmlSchemaObjectCollection choiceItems = xmlSchemaChoice.Items; if (choiceItems == null) continue; foreach (XmlSchemaAnnotated choiceEl in choiceItems) { - if (choiceEl is XmlSchemaElement) + if (choiceEl is XmlSchemaElement xmlSchemaElement) { - if (((XmlSchemaParticle)el).MaxOccurs > decimal.One && (((XmlSchemaElement)choiceEl).SchemaType is XmlSchemaComplexType)) // amir - ((XmlSchemaElement)choiceEl).MaxOccurs = ((XmlSchemaParticle)el).MaxOccurs; - if ((((XmlSchemaElement)choiceEl).RefName.Name.Length != 0) && (!FromInference && ((XmlSchemaElement)choiceEl).MaxOccurs != decimal.One && !(((XmlSchemaElement)choiceEl).SchemaType is XmlSchemaComplexType))) + if (((XmlSchemaParticle)el).MaxOccurs > decimal.One && (xmlSchemaElement.SchemaType is XmlSchemaComplexType)) // amir + xmlSchemaElement.MaxOccurs = ((XmlSchemaParticle)el).MaxOccurs; + if ((xmlSchemaElement.RefName.Name.Length != 0) && (!FromInference && xmlSchemaElement.MaxOccurs != decimal.One && xmlSchemaElement.SchemaType is not XmlSchemaComplexType)) continue; - DataTable child = HandleTable((XmlSchemaElement)choiceEl)!; + DataTable child = HandleTable(xmlSchemaElement)!; if (FromInference) { tableSequenceList.Add(child); @@ -2820,7 +2820,7 @@ internal bool IsTable(XmlSchemaElement node) } - if ((typeNode == null) || !(typeNode is XmlSchemaComplexType)) + if ((typeNode == null) || typeNode is not XmlSchemaComplexType) { return false; } diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs index 52ebbb8665c063..fca0faa8e3d76e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs @@ -240,8 +240,8 @@ private bool FIgnoreNamespace(XmlNode node) XmlNode? ownerNode; if (!_fIsXdr) return false; - if (node is XmlAttribute) - ownerNode = ((XmlAttribute)node).OwnerElement!; + if (node is XmlAttribute xmlAttribute) + ownerNode = xmlAttribute.OwnerElement!; else ownerNode = node; if (ownerNode.NamespaceURI.StartsWith("x-schema:#", StringComparison.Ordinal)) diff --git a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs index 51f70149c9c3c3..8db3419f46dec8 100644 --- a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs +++ b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs @@ -84,9 +84,9 @@ internal static void AddExtendedProperties(PropertyCollection? props, XmlElement { v = (string)SqlConvert.ChangeTypeForXML(entry.Value, typeof(string)); } - else if (entry.Value is System.Numerics.BigInteger) + else if (entry.Value is System.Numerics.BigInteger bigInteger) { - v = (string)BigIntegerStorage.ConvertFromBigInteger((System.Numerics.BigInteger)entry.Value, typeof(string), CultureInfo.InvariantCulture); + v = (string)BigIntegerStorage.ConvertFromBigInteger(bigInteger, typeof(string), CultureInfo.InvariantCulture); } else { @@ -137,9 +137,9 @@ internal void AddXdoProperty(PropertyDescriptor pd, object instance, XmlElement bool bIsSqlType = false; bool bImplementsInullable = false; - if (instance is DataColumn) + if (instance is DataColumn dataColumn) { - col = (DataColumn)instance; + col = dataColumn; bisDataColumn = true; bIsSqlType = col.IsSqlType; bImplementsInullable = col.ImplementsINullable; @@ -287,9 +287,9 @@ private void GenerateConstraintNames(DataTable table, bool fromTable) { if (fromTable) { - if (constr is ForeignKeyConstraint) + if (constr is ForeignKeyConstraint foreignKeyConstraint) { // if parent table does not exist , no need to create FKConst - if (!_tables.Contains(((ForeignKeyConstraint)constr).RelatedTable)) + if (!_tables.Contains(foreignKeyConstraint.RelatedTable)) { continue; } @@ -862,9 +862,9 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT { if (genSecondary) { - if (xw is XmlTextWriter) + if (xw is XmlTextWriter xmlTextWriter) { - ((XmlTextWriter)xw).Formatting = Formatting.Indented; + xmlTextWriter.Formatting = Formatting.Indented; } xw.WriteStartDocument(true); } @@ -1578,10 +1578,10 @@ internal void AppendChildWithoutRef(string Namespace, XmlElement el) for (XmlNode? n = node.FirstChild; n != null; n = n.NextSibling) { - if (!(n is XmlElement)) + if (n is not XmlElement xmlElement) continue; - XmlElement child = (XmlElement)n; + XmlElement child = xmlElement; if (XSDSchema.FEqualIdentity(child, Keywords.XSD_ELEMENT, Keywords.XSDNS) || XSDSchema.FEqualIdentity(child, Keywords.XSD_ATTRIBUTE, Keywords.XSDNS) || @@ -3321,7 +3321,7 @@ internal sealed class DataTextReader : XmlReader internal static XmlReader CreateReader(XmlReader xr) { - Debug.Assert(!(xr is DataTextReader), "XmlReader is DataTextReader"); + Debug.Assert(xr is not DataTextReader, "XmlReader is DataTextReader"); return new DataTextReader(xr); } diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs index c36bbd951d7149..225aec0c67d899 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs @@ -613,8 +613,8 @@ internal void Foliate(XmlBoundElement node, ElementState newState) private void Foliate(XmlElement element) { - if (element is XmlBoundElement) - ((XmlBoundElement)element).Foliate(ElementState.WeakFoliation); + if (element is XmlBoundElement xmlBoundElement) + xmlBoundElement.Foliate(ElementState.WeakFoliation); } // Foliate rowElement region if there are DataPointers that points into it @@ -770,7 +770,7 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) break; object? schema = _mapper.GetColumnSchemaForNode(rowElement, node); - if (schema == null || !(schema is DataColumn)) + if (schema == null || schema is not DataColumn) break; // insert location must be before any columns logically after this column @@ -922,9 +922,9 @@ internal bool IgnoreDataSetEvents private bool IsFoliated(XmlElement element) { - if (element is XmlBoundElement) + if (element is XmlBoundElement xmlBoundElement) { - return ((XmlBoundElement)element).IsFoliated; + return xmlBoundElement.IsFoliated; } return true; @@ -2391,7 +2391,7 @@ internal static void SetRowValueFromXmlText(DataRow row, DataColumn col, string { oVal = col.ConvertXmlToObject(xmlText); // This func does not set the field value to null - call SetRowValueToNull in order to do so - Debug.Assert(oVal != null && !(oVal is DBNull)); + Debug.Assert(oVal != null && oVal is not DBNull); } catch (Exception e) when (Data.Common.ADP.IsCatchableExceptionType(e)) { diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs index e7904b01029957..bd0441d3fdc4b6 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs @@ -342,9 +342,9 @@ private int GetColumnSize(object? value, int offset, int ordinal) { cch = 0; } - else if (value is string) + else if (value is string str) { - cch = ((string)value).Length - offset; + cch = str.Length - offset; if ((0 != (ParameterDirection.Output & _internalDirection)) && (0x3fffffff <= _internalSize)) { @@ -370,9 +370,9 @@ private int GetColumnSize(object? value, int offset, int ordinal) cch = System.Text.Encoding.Default.GetMaxByteCount(cch); } } - else if (value is char[]) + else if (value is char[] chars) { - cch = ((char[])value).Length - offset; + cch = chars.Length - offset; if ((0 != (ParameterDirection.Output & _internalDirection)) && (0x3fffffff <= _internalSize)) { cch = Math.Max(cch, 4 * 1024); // MDAC 69224 @@ -384,9 +384,9 @@ private int GetColumnSize(object? value, int offset, int ordinal) cch = System.Text.Encoding.Default.GetMaxByteCount(cch); } } - else if (value is byte[]) + else if (value is byte[] bytes) { - cch = ((byte[])value).Length - offset; + cch = bytes.Length - offset; if ((0 != (ParameterDirection.Output & _internalDirection)) && (0x3fffffff <= _internalSize)) { @@ -425,19 +425,19 @@ private int GetValueSize(object? value, int offset) if (0 >= cch) { bool twobytesperunit = false; - if (value is string) + if (value is string str) { - cch = ((string)value).Length - offset; + cch = str.Length - offset; twobytesperunit = true; } - else if (value is char[]) + else if (value is char[] chars) { - cch = ((char[])value).Length - offset; + cch = chars.Length - offset; twobytesperunit = true; } - else if (value is byte[]) + else if (value is byte[] bytes) { - cch = ((byte[])value).Length - offset; + cch = bytes.Length - offset; } else { @@ -488,17 +488,17 @@ private int GetParameterSize(object? value, int offset, int ordinal) ccb = 0; } } - else if (value is string) + else if (value is string str) { - ccb = (((string)value).Length - offset) * 2 + 2; + ccb = (str.Length - offset) * 2 + 2; } - else if (value is char[]) + else if (value is char[] chars) { - ccb = (((char[])value).Length - offset) * 2 + 2; + ccb = (chars.Length - offset) * 2 + 2; } - else if (value is byte[]) + else if (value is byte[] bytes) { - ccb = ((byte[])value).Length - offset; + ccb = bytes.Length - offset; } #if DEBUG else { Debug.Fail("not expecting this"); } @@ -561,7 +561,7 @@ private byte GetParameterScale(object? value) { // For any value that is not decimal simply return the Scale // - if (!(value is decimal)) + if (value is not decimal d) { return _internalScale; } @@ -570,7 +570,7 @@ private byte GetParameterScale(object? value) // If the user specified a lower scale we return the user specified scale, // otherwise the values scale // - byte s = (byte)((decimal.GetBits((decimal)value)[3] & 0x00ff0000) >> 0x10); + byte s = (byte)((decimal.GetBits(d)[3] & 0x00ff0000) >> 0x10); if ((_internalScale > 0) && (_internalScale < s)) { return _internalScale; @@ -635,23 +635,23 @@ internal void PrepareForBind(OdbcCommand command, short ordinal, ref int paramet // if (offset > 0) { - if (value is string) + if (value is string str) { - if (offset > ((string)value).Length) + if (offset > str.Length) { throw ADP.OffsetOutOfRangeException(); } } - else if (value is char[]) + else if (value is char[] chars) { - if (offset > ((char[])value).Length) + if (offset > chars.Length) { throw ADP.OffsetOutOfRangeException(); } } - else if (value is byte[]) + else if (value is byte[] bytes) { - if (offset > ((byte[])value).Length) + if (offset > bytes.Length) { throw ADP.OffsetOutOfRangeException(); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs index 878237aa050cd9..0277f5bd957c92 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs @@ -217,18 +217,18 @@ public override string ToString() private static byte ValuePrecisionCore(object? value) { - if (value is decimal) + if (value is decimal d) { - return ((System.Data.SqlTypes.SqlDecimal)(decimal)value).Precision; + return ((System.Data.SqlTypes.SqlDecimal)d).Precision; } return 0; } private static byte ValueScaleCore(object? value) { - if (value is decimal) + if (value is decimal d) { - return (byte)((decimal.GetBits((decimal)value)[3] & 0x00ff0000) >> 0x10); + return (byte)((decimal.GetBits(d)[3] & 0x00ff0000) >> 0x10); } return 0; } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs index 2da064b5f6087b..2dd9a6d92ee710 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs @@ -167,16 +167,16 @@ internal void MarshalToNative(int offset, object value, ODBC32.SQL_C sqlctype, i int length; Debug.Assert(value is string || value is char[], "Only string or char[] can be marshaled to WCHAR"); - if (value is string) + if (value is string str) { - length = Math.Max(0, ((string)value).Length - valueOffset); + length = Math.Max(0, str.Length - valueOffset); if ((sizeorprecision > 0) && (sizeorprecision < length)) { length = sizeorprecision; } - rgChars = ((string)value).ToCharArray(valueOffset, length); + rgChars = str.ToCharArray(valueOffset, length); Debug.Assert(rgChars.Length < (base.Length - valueOffset), "attempting to extend parameter buffer!"); WriteCharArray(offset, rgChars, 0, rgChars.Length); diff --git a/src/libraries/System.Data.OleDb/src/ColumnBinding.cs b/src/libraries/System.Data.OleDb/src/ColumnBinding.cs index 8dfe4ff7c4063b..d3e005e1497300 100644 --- a/src/libraries/System.Data.OleDb/src/ColumnBinding.cs +++ b/src/libraries/System.Data.OleDb/src/ColumnBinding.cs @@ -491,9 +491,9 @@ internal void Value(object? value) Value_DECIMAL((decimal)value); break; case NativeDBType.I1: - if (value is short) + if (value is short num) { - Value_I1(Convert.ToSByte((short)value, CultureInfo.InvariantCulture)); + Value_I1(Convert.ToSByte(num, CultureInfo.InvariantCulture)); } else { @@ -504,9 +504,9 @@ internal void Value(object? value) Value_UI1((byte)value); break; case NativeDBType.UI2: - if (value is int) + if (value is int num2) { - Value_UI2(Convert.ToUInt16((int)value, CultureInfo.InvariantCulture)); + Value_UI2(Convert.ToUInt16(num2, CultureInfo.InvariantCulture)); } else { @@ -514,9 +514,9 @@ internal void Value(object? value) } break; case NativeDBType.UI4: - if (value is long) + if (value is long num3) { - Value_UI4(Convert.ToUInt32((long)value, CultureInfo.InvariantCulture)); + Value_UI4(Convert.ToUInt32(num3, CultureInfo.InvariantCulture)); } else { @@ -527,9 +527,9 @@ internal void Value(object? value) Value_I8((long)value); break; case NativeDBType.UI8: - if (value is decimal) + if (value is decimal d) { - Value_UI8(Convert.ToUInt64((decimal)value, CultureInfo.InvariantCulture)); + Value_UI8(Convert.ToUInt64(d, CultureInfo.InvariantCulture)); } else { @@ -546,9 +546,9 @@ internal void Value(object? value) Value_BYTES((byte[])value); break; case NativeDBType.WSTR: - if (value is string) + if (value is string str) { - Value_WSTR((string)value); + Value_WSTR(str); } else { @@ -574,9 +574,9 @@ internal void Value(object? value) Value_ByRefBYTES((byte[])value); break; case (NativeDBType.BYREF | NativeDBType.WSTR): - if (value is string) + if (value is string str2) { - Value_ByRefWSTR((string)value); + Value_ByRefWSTR(str2); } else { @@ -1463,9 +1463,9 @@ internal short ValueInt16() break; case NativeDBType.VARIANT: object variant = ValueVariant(); - if (variant is sbyte) + if (variant is sbyte sb) { - value = (short)(sbyte)variant; + value = (short)sb; } else { @@ -1498,9 +1498,9 @@ internal int ValueInt32() break; case NativeDBType.VARIANT: object variant = ValueVariant(); - if (variant is ushort) + if (variant is ushort num) { - value = (int)(ushort)variant; + value = (int)num; } else { @@ -1533,9 +1533,9 @@ internal long ValueInt64() break; case NativeDBType.VARIANT: object variant = ValueVariant(); - if (variant is uint) + if (variant is uint num) { - value = (long)(uint)variant; + value = (long)num; } else { diff --git a/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs b/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs index d70bff0d9376be..89c3ad4117298a 100644 --- a/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs +++ b/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs @@ -221,18 +221,18 @@ public override string ToString() private static byte ValuePrecisionCore(object? value) { // V1.2.3300 - if (value is decimal) + if (value is decimal d) { - return ((System.Data.SqlTypes.SqlDecimal)(decimal)value).Precision; + return ((System.Data.SqlTypes.SqlDecimal)d).Precision; } return 0; } private static byte ValueScaleCore(object? value) { // V1.2.3300 - if (value is decimal) + if (value is decimal d) { - return (byte)((decimal.GetBits((decimal)value)[3] & 0x00ff0000) >> 0x10); + return (byte)((decimal.GetBits(d)[3] & 0x00ff0000) >> 0x10); } return 0; } diff --git a/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs b/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs index 376e554bda69e0..66f8b2fe8eb9dc 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs @@ -274,9 +274,9 @@ private static OleDbParameter[] DeriveParametersFromStoredProcedure(OleDbConnect case OleDbType.VarChar: case OleDbType.VarWChar: value = dataRow[backendtype!, DataRowVersion.Default]; - if (value is string) + if (value is string str) { - string backendtypename = ((string)value).ToLowerInvariant(); + string backendtypename = str.ToLowerInvariant(); switch (backendtypename) { case "binary": diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs index 08a73afefc7ab7..621b022545d148 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs @@ -300,9 +300,9 @@ internal int QuotedIdentifierCase() int quotedIdentifierCase; object? value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_QUOTEDIDENTIFIERCASE); - if (value is int) + if (value is int num) {// not OleDbPropertyStatus - quotedIdentifierCase = (int)value; + quotedIdentifierCase = num; } else { diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs index 4f5ea1101d0e88..9cc5357ed4ff24 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs @@ -179,9 +179,9 @@ internal int GetSqlSupport(OleDbConnection connection) if (!_hasSqlSupport) { object? value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_SQLSUPPORT); - if (value is int) + if (value is int num) { // not OleDbPropertyStatus - sqlSupport = (int)value; + sqlSupport = num; } _sqlSupport = sqlSupport; _hasSqlSupport = true; @@ -197,7 +197,7 @@ internal bool GetSupportIRow(OleDbCommand command) object? value = command.GetPropertyValue(OleDbPropertySetGuid.Rowset, ODB.DBPROP_IRow); // SQLOLEDB always returns VARIANT_FALSE for DBPROP_IROW, so base the answer on existence - supportIRow = !(value is OleDbPropertyStatus); + supportIRow = value is not OleDbPropertyStatus; _supportIRow = supportIRow; _hasSupportIRow = true; } @@ -210,9 +210,9 @@ internal bool GetSupportMultipleResults(OleDbConnection connection) if (!_hasSupportMultipleResults) { object? value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_MULTIPLERESULTS); - if (value is int) + if (value is int num) {// not OleDbPropertyStatus - supportMultipleResults = (ODB.DBPROPVAL_MR_NOTSUPPORTED != (int)value); + supportMultipleResults = (ODB.DBPROPVAL_MR_NOTSUPPORTED != num); } _supportMultipleResults = supportMultipleResults; _hasSupportMultipleResults = true; @@ -229,9 +229,9 @@ private static int UdlPoolSize if (!UDL._PoolSizeInit) { object? value = ADP.LocalMachineRegistryValue(UDL.Location, UDL.Pooling); - if (value is int) + if (value is int num) { - poolsize = (int)value; + poolsize = num; poolsize = ((0 < poolsize) ? poolsize : 0); UDL._PoolSize = poolsize; } diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs index 8253b092bb7a0d..6dd917f7ba6adb 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs @@ -187,8 +187,8 @@ private int FillFromADODB(object data, object adodb, string? srcTable, bool mult { Debug.Assert(null != data, "FillFromADODB: null data object"); Debug.Assert(null != adodb, "FillFromADODB: null ADODB"); - Debug.Assert(!(adodb is DataTable), "call Fill( (DataTable) value)"); - Debug.Assert(!(adodb is DataSet), "call Fill( (DataSet) value)"); + Debug.Assert(adodb is not DataTable, "call Fill( (DataTable) value)"); + Debug.Assert(adodb is not DataSet, "call Fill( (DataSet) value)"); /* IntPtr adodbptr = ADP.PtrZero; @@ -346,9 +346,9 @@ private int FillFromRecordset(object data, UnsafeNativeMethods.ADORecordsetConst incrementResultCount = (0 < dataReader.FieldCount); if (incrementResultCount) { - if (data is DataTable) + if (data is DataTable dataTable) { - return base.Fill((DataTable)data, dataReader); + return base.Fill(dataTable, dataReader); } else { @@ -394,9 +394,9 @@ private int FillFromRecord(object data, UnsafeNativeMethods.ADORecordConstructio dataReader.InitializeIRow(result, ADP.RecordsUnaffected); dataReader.BuildMetaInfo(); - if (data is DataTable) + if (data is DataTable dataTable) { - return base.Fill((DataTable)data, dataReader); + return base.Fill(dataTable, dataReader); } else { diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs index 59662e12c00ec8..cb69b74709952e 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs @@ -2406,9 +2406,9 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset) } int visibleCount = metainfo.Count; - if (hiddenColumns is int) + if (hiddenColumns is int num) { - visibleCount -= (int)hiddenColumns; + visibleCount -= num; } // if one key column is invalidated, they all need to be invalidated. The SET is the key, diff --git a/src/libraries/System.Data.OleDb/src/OleDbParameter.cs b/src/libraries/System.Data.OleDb/src/OleDbParameter.cs index 81055cf09716d9..8b5ca8095277b6 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbParameter.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbParameter.cs @@ -29,7 +29,7 @@ public OleDbParameter() : base() public OleDbParameter(string? name, object? value) : this() { Debug.Assert(!(value is OleDbType), "use OleDbParameter(string, OleDbType)"); - Debug.Assert(!(value is SqlDbType), "use OleDbParameter(string, OleDbType)"); + Debug.Assert(value is not SqlDbType, "use OleDbParameter(string, OleDbType)"); ParameterName = name; Value = value; diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterCreationDataCollection.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterCreationDataCollection.cs index f44cab190e1aa7..0851a4173ccae8 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterCreationDataCollection.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterCreationDataCollection.cs @@ -89,7 +89,7 @@ protected override void OnValidate(object value) { ArgumentNullException.ThrowIfNull(value); - if (!(value is CounterCreationData)) + if (value is not CounterCreationData) throw new ArgumentException(SR.MustAddCounterCreationData); } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.cs index 96009d99e1054a..49b7c23c650f15 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.cs @@ -105,7 +105,7 @@ public string Arguments // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = envVars.GetEnumerator(); - Debug.Assert(!(e is IDisposable), "Environment.GetEnvironmentVariables should not be IDisposable."); + Debug.Assert(e is not IDisposable, "Environment.GetEnvironmentVariables should not be IDisposable."); while (e.MoveNext()) { DictionaryEntry entry = e.Entry; diff --git a/src/libraries/System.Diagnostics.StackTrace/src/System/Diagnostics/SymbolStore/SymbolToken.cs b/src/libraries/System.Diagnostics.StackTrace/src/System/Diagnostics/SymbolStore/SymbolToken.cs index 8b27f618770fb7..e3d7acb30e2c5f 100644 --- a/src/libraries/System.Diagnostics.StackTrace/src/System/Diagnostics/SymbolStore/SymbolToken.cs +++ b/src/libraries/System.Diagnostics.StackTrace/src/System/Diagnostics/SymbolStore/SymbolToken.cs @@ -20,8 +20,8 @@ public SymbolToken(int val) public override bool Equals([NotNullWhen(true)] object? obj) { - if (obj is SymbolToken) - return Equals((SymbolToken)obj); + if (obj is SymbolToken symbolToken) + return Equals(symbolToken); else return false; } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchAttribute.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchAttribute.cs index e14bf129b37f5e..5723377a678cbc 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchAttribute.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SwitchAttribute.cs @@ -74,7 +74,7 @@ private static void GetAllRecursive([DynamicallyAccessedMembers(DynamicallyAcces foreach (MemberInfo member in members) { // ignore Types here. They will get covered by the top level assembly.GetTypes - if (!(member is Type)) + if (member is not Type) GetAllRecursive(member, switchAttribs); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs index 4deb75cb5a12d8..8251ffdcb32033 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADAMStoreCtx.cs @@ -197,9 +197,9 @@ private void SetupPasswordModification(AuthenticablePrincipal p) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "ADAMStoreCtx", "SetupPasswordModification: caught TargetInvocationException with message " + e.Message); - if (e.InnerException is System.Runtime.InteropServices.COMException) + if (e.InnerException is System.Runtime.InteropServices.COMException cOMException) { - throw (ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e.InnerException)); + throw (ExceptionHelper.GetExceptionFromCOMException(cOMException)); } // Unknown exception. We don't want to suppress it. diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNConstraintLinkedAttrSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNConstraintLinkedAttrSet.cs index 159d59771d9912..52aae30e65e28d 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNConstraintLinkedAttrSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNConstraintLinkedAttrSet.cs @@ -92,8 +92,8 @@ internal override bool MoveNext() { case ConstraintType.ContainerStringMatch: - if (this.current is SearchResult) - dn = ((SearchResult)this.current).Properties["distinguishedName"][0].ToString(); + if (this.current is SearchResult searchResult) + dn = searchResult.Properties["distinguishedName"][0].ToString(); else dn = ((DirectoryEntry)this.current).Properties["distinguishedName"].Value.ToString(); @@ -107,9 +107,9 @@ internal override bool MoveNext() if (resultValidator != null) { dSPropertyCollection resultPropCollection = null; - if (this.current is SearchResult) + if (this.current is SearchResult searchResult2) { - resultPropCollection = new dSPropertyCollection(((SearchResult)this.current).Properties); + resultPropCollection = new dSPropertyCollection(searchResult2.Properties); } else { diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs index 01b09669eb547a..5ea9eb6898f99f 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs @@ -135,8 +135,8 @@ internal override object CurrentAsPrincipal if (this.current != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "CurrentAsPrincipal: using current"); - if (this.current is DirectoryEntry) - return ADUtils.DirectoryEntryAsPrincipal((DirectoryEntry)this.current, _storeCtx); + if (this.current is DirectoryEntry directoryEntry) + return ADUtils.DirectoryEntryAsPrincipal(directoryEntry, _storeCtx); else { return ADUtils.SearchResultAsPrincipal((SearchResult)this.current, _storeCtx, null); @@ -744,7 +744,7 @@ private bool MoveNextForeign(ref bool outerNeedToRetry) } } - if (foreignPrincipal is GroupPrincipal) + if (foreignPrincipal is GroupPrincipal groupPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextForeign: foreign member is a group"); @@ -763,7 +763,7 @@ private bool MoveNextForeign(ref bool outerNeedToRetry) if (!_groupsVisited.Contains(groupDN) && !_groupsToVisit.Contains(groupDN)) { - _foreignGroups.Add((GroupPrincipal)foreignPrincipal); + _foreignGroups.Add(groupPrincipal); } else { diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs index 5bab2733b2375f..ac07e7c3418cdc 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs @@ -424,8 +424,8 @@ internal override void Insert(Principal p) GlobalDebug.WriteLineIf(GlobalDebug.Error, "ADStoreCtx", "Insert, Deletion Failed {0} ", deleteFail.Message); } - if (e is System.Runtime.InteropServices.COMException) - throw ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e); + if (e is System.Runtime.InteropServices.COMException cOMException) + throw ExceptionHelper.GetExceptionFromCOMException(cOMException); else throw; } @@ -1384,7 +1384,7 @@ internal override ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreC // An object exists in the domain that contains links to all the groups it is a member of. bool rootPrincipalExists = true; - if ((foreignContext is ADStoreCtx) && !(foreignContext is ADAMStoreCtx)) + if ((foreignContext is ADStoreCtx) && foreignContext is not ADAMStoreCtx) { // We only need to check forest status for AD stores. Forest concept does not apply to ADAM. ADStoreCtx foreignADStore = (ADStoreCtx)foreignContext; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs index 653c46b4f20a45..38084920bde42c 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs @@ -239,9 +239,9 @@ internal override Principal GetAsPrincipal(object storeObject, object discrimina string path; string distinguishedName; - if (storeObject is DirectoryEntry) + if (storeObject is DirectoryEntry directoryEntry) { - de = (DirectoryEntry)storeObject; + de = directoryEntry; path = de.Path; distinguishedName = (string)de.Properties["distinguishedName"].Value; } @@ -1343,7 +1343,7 @@ protected static void ExtensionCacheToLdapConverter(Principal p, string property ICollection valueCollection; // byte[] gets special treatment (following S.DS and ADSI) - we don't treat it as ICollection but rather as a whole - if (kvp.Value.Value.Length == 1 && kvp.Value.Value[0] is ICollection && !(kvp.Value.Value[0] is byte[])) + if (kvp.Value.Value.Length == 1 && kvp.Value.Value[0] is ICollection && kvp.Value.Value[0] is not byte[]) { valueCollection = (ICollection)kvp.Value.Value[0]; } @@ -1362,7 +1362,7 @@ protected static void ExtensionCacheToLdapConverter(Principal p, string property { if (null != oVal) { - if ((oVal is ICollection || oVal is IList) && !(oVal is byte[])) + if ((oVal is ICollection || oVal is IList) && oVal is not byte[]) throw new ArgumentException(SR.InvalidExtensionCollectionType); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheToLdapConverter - Element Value Type " + oVal.GetType().ToString()); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs index 4fd77c9b45e7d8..39386ab865c0d9 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_Query.cs @@ -982,11 +982,11 @@ protected static string ExtensionCacheConverter(FilterBase filter, string sugges GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter filter type " + type.ToString()); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter match type " + kvp.Value.MatchType.ToString()); - if (kvp.Value.Value is ICollection) + if (kvp.Value.Value is ICollection collection2) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter encountered collection."); - ICollection collection = (ICollection)kvp.Value.Value; + ICollection collection = collection2; foreach (object o in collection) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "ExtensionCacheConverter collection filter type " + o.GetType().ToString()); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreKey.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreKey.cs index 3f3b617413c6ea..e5573e99d25299 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreKey.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreKey.cs @@ -53,10 +53,10 @@ public ADStoreKey(string domainName, byte[] sid) public override bool Equals(object o) { - if (!(o is ADStoreKey)) + if (o is not ADStoreKey aDStoreKey) return false; - ADStoreKey that = (ADStoreKey)o; + ADStoreKey that = aDStoreKey; if (_wellKnownSid != that._wellKnownSid) return false; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSCache.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSCache.cs index 62a3ea9db178a1..f238c3e9333dd2 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSCache.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSCache.cs @@ -105,13 +105,13 @@ public PrincipalContext GetContext(string name, NetCred credentials, ContextOpti object o = credTable[userName]; - if (o is Placeholder) + if (o is Placeholder placeholder) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: credHolder for " + contextName + " has a Placeholder"); // A PrincipalContext is currently being constructed by another thread. // Wait for it. - contextReadyEvent = ((Placeholder)o).contextReadyEvent; + contextReadyEvent = placeholder.contextReadyEvent; continue; } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs index 0844609b383913..bdd6fd32c0680d 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs @@ -208,10 +208,10 @@ internal static void InsertPrincipal( Debug.Assert(storeCtx is ADStoreCtx || storeCtx is SAMStoreCtx); Debug.Assert(p != null); - if ((!(p is UserPrincipal)) && - (!(p is GroupPrincipal)) && - (!(p is AuthenticablePrincipal)) && - (!(p is ComputerPrincipal))) + if ((p is not UserPrincipal) && + (p is not GroupPrincipal) && + (p is not AuthenticablePrincipal) && + (p is not ComputerPrincipal)) { // It's not a type of Principal that we support GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SDSUtils", "InsertPrincipal: Bad principal type:" + p.GetType().ToString()); @@ -317,17 +317,17 @@ internal static void SetPassword(DirectoryEntry de, string newPassword) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "SDSUtils", "SetPassword: caught TargetInvocationException with message " + e.Message); - if (e.InnerException is System.Runtime.InteropServices.COMException) + if (e.InnerException is System.Runtime.InteropServices.COMException cOMException) { - if (((System.Runtime.InteropServices.COMException)e.InnerException).ErrorCode == unchecked((int)ExceptionHelper.ERROR_HRESULT_CONSTRAINT_VIOLATION)) + if (cOMException.ErrorCode == unchecked((int)ExceptionHelper.ERROR_HRESULT_CONSTRAINT_VIOLATION)) { // We have a special case of constraint violation here. We know this is a password failure to convert to this // specialized type instead of the generic InvalidOperationException - throw (new PasswordException(((System.Runtime.InteropServices.COMException)e.InnerException).Message, (System.Runtime.InteropServices.COMException)e.InnerException)); + throw (new PasswordException(cOMException.Message, cOMException)); } else { - throw (ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e.InnerException)); + throw (ExceptionHelper.GetExceptionFromCOMException(cOMException)); } } @@ -351,17 +351,17 @@ internal static void ChangePassword(DirectoryEntry de, string oldPassword, strin { GlobalDebug.WriteLineIf(GlobalDebug.Error, "SDSUtils", "ChangePassword: caught TargetInvocationException with message " + e.Message); - if (e.InnerException is System.Runtime.InteropServices.COMException) + if (e.InnerException is System.Runtime.InteropServices.COMException cOMException) { - if (((System.Runtime.InteropServices.COMException)e.InnerException).ErrorCode == unchecked((int)ExceptionHelper.ERROR_HRESULT_CONSTRAINT_VIOLATION)) + if (cOMException.ErrorCode == unchecked((int)ExceptionHelper.ERROR_HRESULT_CONSTRAINT_VIOLATION)) { // We have a special case of constraint violation here. We know this is a password failure to convert to this // specialized type instead of the generic InvalidOperationException - throw (new PasswordException(((System.Runtime.InteropServices.COMException)e.InnerException).Message, (System.Runtime.InteropServices.COMException)e.InnerException)); + throw (new PasswordException(cOMException.Message, cOMException)); } else { - throw (ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e.InnerException)); + throw (ExceptionHelper.GetExceptionFromCOMException(cOMException)); } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs index 36124f08078c1c..ffd9260e08dccb 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs @@ -431,8 +431,8 @@ public void Save(PrincipalContext context) GlobalDebug.WriteLineIf(GlobalDebug.Error, "Principal", "Save(context):, Move back Failed {0} ", deleteFail.Message); } - if (e is System.Runtime.InteropServices.COMException) - throw ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e); + if (e is System.Runtime.InteropServices.COMException cOMException) + throw ExceptionHelper.GetExceptionFromCOMException(cOMException); else throw; } @@ -656,20 +656,20 @@ protected object[] ExtensionGet(string attribute) private void ValidateExtensionObject(object value) { - if (value is object[]) + if (value is object[] objects) { - if (((object[])value).Length == 0) + if (objects.Length == 0) throw new ArgumentException(SR.InvalidExtensionCollectionType); - foreach (object o in (object[])value) + foreach (object o in objects) { if (o is ICollection) throw new ArgumentException(SR.InvalidExtensionCollectionType); } } - if (value is byte[]) + if (value is byte[] bytes) { - if (((byte[])value).Length == 0) + if (bytes.Length == 0) { throw new ArgumentException(SR.InvalidExtensionCollectionType); } @@ -697,8 +697,8 @@ protected void ExtensionSet(string attribute, object value) ValidateExtensionObject(value); - if (value is object[]) - _extensionCache.properties[attribute] = new ExtensionCacheValue((object[])value); + if (value is object[] objects) + _extensionCache.properties[attribute] = new ExtensionCacheValue(objects); else _extensionCache.properties[attribute] = new ExtensionCacheValue(new object[] { value }); @@ -712,8 +712,8 @@ internal void AdvancedFilterSet(string attribute, object value, Type objectType, ValidateExtensionObject(value); - if (value is object[]) - _extensionCache.properties[attribute] = new ExtensionCacheValue((object[])value, objectType, mt); + if (value is object[] objects) + _extensionCache.properties[attribute] = new ExtensionCacheValue(objects, objectType, mt); else _extensionCache.properties[attribute] = new ExtensionCacheValue(new object[] { value }, objectType, mt); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs index 7c22e86110b5d1..cefee0b710ee49 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMMembersSet.cs @@ -285,7 +285,7 @@ private bool MoveNextForeign() // If we're not enumerating recursively, return the principal. // If we are enumerating recursively, and it's a group, save it off for later. - if (!_recursive || !(foreignPrincipal is GroupPrincipal)) + if (!_recursive || foreignPrincipal is not GroupPrincipal) { // Return the principal. GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMMembersSet", "MoveNextForeign: setting currentForeign to {0}", foreignDE.Path); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs index 0403053028ea78..b664617d03b920 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs @@ -396,9 +396,9 @@ internal override bool IsLockedOut(AuthenticablePrincipal p) } catch (System.Reflection.TargetInvocationException e) { - if (e.InnerException is System.Runtime.InteropServices.COMException) + if (e.InnerException is System.Runtime.InteropServices.COMException cOMException) { - throw (ExceptionHelper.GetExceptionFromCOMException((System.Runtime.InteropServices.COMException)e.InnerException)); + throw (ExceptionHelper.GetExceptionFromCOMException(cOMException)); } throw; } @@ -615,7 +615,7 @@ internal override ResultSet GetGroupsMemberOf(Principal p) GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf: is real principal"); // No nested groups or computers as members of groups in SAM - if (!(p is UserPrincipal)) + if (p is not UserPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetGroupsMemberOf: not a user, returning empty set"); return new EmptySet(); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreKey.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreKey.cs index 4d03a2fd5e83a4..aa22460cbb6955 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreKey.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreKey.cs @@ -33,10 +33,10 @@ public SAMStoreKey(string machineName, byte[] sid) public override bool Equals(object o) { - if (!(o is SAMStoreKey)) + if (o is not SAMStoreKey sAMStoreKey) return false; - SAMStoreKey that = (SAMStoreKey)o; + SAMStoreKey that = sAMStoreKey; if (!string.Equals(_machineName, that._machineName, StringComparison.OrdinalIgnoreCase)) return false; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs index e43626d68cd334..1974b813b3ba6e 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs @@ -404,33 +404,33 @@ private void BuildFilterSet(Principal p, string[] propertySet, QbeFilterDescript { ((FilterBase)filter).Value = null; } - else if (value is bool) + else if (value is bool b) { - ((FilterBase)filter).Value = (bool)value; + ((FilterBase)filter).Value = b; } - else if (value is string) + else if (value is string str) { - ((FilterBase)filter).Value = (string)value; + ((FilterBase)filter).Value = str; } - else if (value is GroupScope) + else if (value is GroupScope groupScope) { - ((FilterBase)filter).Value = (GroupScope)value; + ((FilterBase)filter).Value = groupScope; } - else if (value is byte[]) + else if (value is byte[] bytes) { - ((FilterBase)filter).Value = (byte[])value; + ((FilterBase)filter).Value = bytes; } else if (value is Nullable) { ((FilterBase)filter).Value = (Nullable)value; } - else if (value is ExtensionCache) + else if (value is ExtensionCache extensionCache) { - ((FilterBase)filter).Value = (ExtensionCache)value; + ((FilterBase)filter).Value = extensionCache; } - else if (value is QbeMatchType) + else if (value is QbeMatchType qbeMatchType) { - ((FilterBase)filter).Value = (QbeMatchType)value; + ((FilterBase)filter).Value = qbeMatchType; } else { diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs index a0d09e2712921c..9b0cfebaf1761d 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs @@ -59,7 +59,7 @@ public static byte[] Encode(string format, params object[] value) throw new ArgumentException(SR.BerConverterNotMatch); } - if (!(value[valueCount] is int)) + if (value[valueCount] is not int) { // argument is wrong Debug.WriteLine("type should be int\n"); @@ -81,7 +81,7 @@ public static byte[] Encode(string format, params object[] value) throw new ArgumentException(SR.BerConverterNotMatch); } - if (!(value[valueCount] is bool)) + if (value[valueCount] is not bool) { // argument is wrong Debug.WriteLine("type should be boolean\n"); @@ -103,7 +103,7 @@ public static byte[] Encode(string format, params object[] value) throw new ArgumentException(SR.BerConverterNotMatch); } - if (value[valueCount] != null && !(value[valueCount] is string)) + if (value[valueCount] != null && value[valueCount] is not string) { // argument is wrong Debug.WriteLine("type should be string, but receiving value has type of "); @@ -132,7 +132,7 @@ public static byte[] Encode(string format, params object[] value) throw new ArgumentException(SR.BerConverterNotMatch); } - if (value[valueCount] != null && !(value[valueCount] is byte[])) + if (value[valueCount] != null && value[valueCount] is not byte[]) { // argument is wrong Debug.WriteLine("type should be byte[], but receiving value has type of "); @@ -155,7 +155,7 @@ public static byte[] Encode(string format, params object[] value) throw new ArgumentException(SR.BerConverterNotMatch); } - if (value[valueCount] != null && !(value[valueCount] is string[])) + if (value[valueCount] != null && value[valueCount] is not string[]) { // argument is wrong Debug.WriteLine("type should be string[], but receiving value has type of "); @@ -196,7 +196,7 @@ public static byte[] Encode(string format, params object[] value) throw new ArgumentException(SR.BerConverterNotMatch); } - if (value[valueCount] != null && !(value[valueCount] is byte[][])) + if (value[valueCount] != null && value[valueCount] is not byte[][]) { // argument is wrong Debug.WriteLine("type should be byte[][], but receiving value has type of "); @@ -219,7 +219,7 @@ public static byte[] Encode(string format, params object[] value) throw new ArgumentException(SR.BerConverterNotMatch); } - if (!(value[valueCount] is int)) + if (value[valueCount] is not int) { // argument is wrong Debug.WriteLine("type should be int\n"); diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs index 7dea8df33f06c4..99709c61eb6db3 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs @@ -142,7 +142,7 @@ public object this[int index] set { ArgumentNullException.ThrowIfNull(value); - if (!(value is string) && !(value is byte[]) && !(value is Uri)) + if (value is not string && value is not byte[] && value is not Uri) { throw new ArgumentException(SR.ValidValueType, nameof(value)); } @@ -161,7 +161,7 @@ internal int Add(object value) { ArgumentNullException.ThrowIfNull(value); - if (!(value is string) && !(value is byte[]) && !(value is Uri)) + if (value is not string && value is not byte[] && value is not Uri) { throw new ArgumentException(SR.ValidValueType, nameof(value)); } @@ -173,7 +173,7 @@ public void AddRange(object[] values) { ArgumentNullException.ThrowIfNull(values); - if (!(values is string[]) && !(values is byte[][]) && !(values is Uri[])) + if (values is not string[] && values is not byte[][] && values is not Uri[]) { throw new ArgumentException(SR.ValidValuesType, nameof(values)); } @@ -214,7 +214,7 @@ protected override void OnValidate(object value) { ArgumentNullException.ThrowIfNull(value); - if (!(value is string) && !(value is byte[]) && !(value is Uri)) + if (value is not string && value is not byte[] && value is not Uri) { throw new ArgumentException(SR.ValidValueType, nameof(value)); } @@ -351,7 +351,7 @@ protected override void OnValidate(object value) { throw new ArgumentException(SR.NullDirectoryAttributeCollection); } - if (!(value is DirectoryAttribute)) + if (value is not DirectoryAttribute) { throw new ArgumentException(SR.Format(SR.InvalidValueType, nameof(DirectoryAttribute)), nameof(value)); } @@ -430,7 +430,7 @@ protected override void OnValidate(object value) { throw new ArgumentException(SR.NullDirectoryAttributeCollection); } - if (!(value is DirectoryAttributeModification)) + if (value is not DirectoryAttributeModification) { throw new ArgumentException(SR.Format(SR.InvalidValueType, nameof(DirectoryAttributeModification)), nameof(value)); } diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs index 89796775337691..0235eb7b2ad75c 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs @@ -1214,7 +1214,7 @@ protected override void OnValidate(object value) { ArgumentNullException.ThrowIfNull(value); - if (!(value is DirectoryControl)) + if (value is not DirectoryControl) { throw new ArgumentException(SR.Format(SR.InvalidValueType, nameof(DirectoryControl)), nameof(value)); } diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryRequest.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryRequest.cs index 1ec893b44958be..d799347f4f5967 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryRequest.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryRequest.cs @@ -238,7 +238,7 @@ public object Filter get => _directoryFilter; set { - if (value != null && !(value is string)) + if (value != null && value is not string) { throw new ArgumentException(SR.ValidFilterType, nameof(value)); } diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs index c159cf152a3eba..5c6ae41903a9ee 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs @@ -274,7 +274,7 @@ public IAsyncResult BeginSendRequest(DirectoryRequest request, TimeSpan requestT throw new InvalidEnumArgumentException(nameof(partialMode), (int)partialMode, typeof(PartialResultProcessing)); } - if (partialMode != PartialResultProcessing.NoPartialResultSupport && !(request is SearchRequest)) + if (partialMode != PartialResultProcessing.NoPartialResultSupport && request is not SearchRequest) { throw new NotSupportedException(SR.PartialResultsNotSupported); } @@ -386,14 +386,14 @@ public void Abort(IAsyncResult asyncResult) ArgumentNullException.ThrowIfNull(asyncResult); - if (!(asyncResult is LdapAsyncResult)) + if (asyncResult is not LdapAsyncResult ldapAsyncResult) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } int messageId; - LdapAsyncResult result = (LdapAsyncResult)asyncResult; + LdapAsyncResult result = ldapAsyncResult; if (!result._partialResults) { if (!s_asyncResultTable.Contains(asyncResult)) @@ -428,17 +428,17 @@ public PartialResultsCollection GetPartialResults(IAsyncResult asyncResult) ArgumentNullException.ThrowIfNull(asyncResult); - if (!(asyncResult is LdapAsyncResult)) + if (asyncResult is not LdapAsyncResult) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } - if (!(asyncResult is LdapPartialAsyncResult)) + if (asyncResult is not LdapPartialAsyncResult ldapPartialAsyncResult) { throw new InvalidOperationException(SR.NoPartialResults); } - return s_partialResultsProcessor.GetPartialResults((LdapPartialAsyncResult)asyncResult); + return s_partialResultsProcessor.GetPartialResults(ldapPartialAsyncResult); } public DirectoryResponse EndSendRequest(IAsyncResult asyncResult) @@ -450,12 +450,12 @@ public DirectoryResponse EndSendRequest(IAsyncResult asyncResult) ArgumentNullException.ThrowIfNull(asyncResult); - if (!(asyncResult is LdapAsyncResult)) + if (asyncResult is not LdapAsyncResult ldapAsyncResult) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } - LdapAsyncResult result = (LdapAsyncResult)asyncResult; + LdapAsyncResult result = ldapAsyncResult; if (!result._partialResults) { @@ -555,20 +555,20 @@ private unsafe int SendRequestHelper(DirectoryRequest request, ref int messageID pClientControlArray[managedClientControls.Length] = null; } - if (request is DeleteRequest) + if (request is DeleteRequest deleteRequest) { // It is an delete operation. - error = LdapPal.DeleteDirectoryEntry(_ldapHandle, ((DeleteRequest)request).DistinguishedName, serverControlArray, clientControlArray, ref messageID); + error = LdapPal.DeleteDirectoryEntry(_ldapHandle, deleteRequest.DistinguishedName, serverControlArray, clientControlArray, ref messageID); } - else if (request is ModifyDNRequest) + else if (request is ModifyDNRequest modifyDNRequest) { // It is a modify dn operation error = LdapPal.RenameDirectoryEntry( _ldapHandle, - ((ModifyDNRequest)request).DistinguishedName, - ((ModifyDNRequest)request).NewName, - ((ModifyDNRequest)request).NewParentDistinguishedName, - ((ModifyDNRequest)request).DeleteOldRdn ? 1 : 0, + modifyDNRequest.DistinguishedName, + modifyDNRequest.NewName, + modifyDNRequest.NewParentDistinguishedName, + modifyDNRequest.DeleteOldRdn ? 1 : 0, serverControlArray, clientControlArray, ref messageID); } else if (request is CompareRequest compareRequest) @@ -625,9 +625,9 @@ private unsafe int SendRequestHelper(DirectoryRequest request, ref int messageID else if (request is AddRequest || request is ModifyRequest) { // Build the attributes. - if (request is AddRequest) + if (request is AddRequest addRequest) { - modifications = BuildAttributes(((AddRequest)request).Attributes, ptrToFree); + modifications = BuildAttributes(addRequest.Attributes, ptrToFree); } else { @@ -647,11 +647,11 @@ private unsafe int SendRequestHelper(DirectoryRequest request, ref int messageID } pModArray[i] = null; - if (request is AddRequest) + if (request is AddRequest addRequest2) { error = LdapPal.AddDirectoryEntry( _ldapHandle, - ((AddRequest)request).DistinguishedName, + addRequest2.DistinguishedName, modArray, serverControlArray, clientControlArray, ref messageID); } @@ -1243,9 +1243,9 @@ internal static unsafe LdapMod[] BuildAttributes(CollectionBase directoryAttribu DirectoryAttributeModificationCollection modificationCollection = null; DirectoryAttributeCollection attributeCollection = null; - if (directoryAttributes is DirectoryAttributeModificationCollection) + if (directoryAttributes is DirectoryAttributeModificationCollection directoryAttributeModificationCollection) { - modificationCollection = (DirectoryAttributeModificationCollection)directoryAttributes; + modificationCollection = directoryAttributeModificationCollection; } else { @@ -1269,9 +1269,9 @@ internal static unsafe LdapMod[] BuildAttributes(CollectionBase directoryAttribu attributes[i] = new LdapMod(); // Write the operation type. - if (modAttribute is DirectoryAttributeModification) + if (modAttribute is DirectoryAttributeModification directoryAttributeModification) { - attributes[i].type = (int)((DirectoryAttributeModification)modAttribute).Operation; + attributes[i].type = (int)directoryAttributeModification.Operation; } else { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs index e4fc2ba312cf9f..16669e8156b02b 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs @@ -605,9 +605,9 @@ public ActiveDirectorySchemaClassCollection PossibleSuperiors if (!listEmpty) { - if (value is ICollection) + if (value is ICollection collection) { - possibleSuperiorsList.AddRange((ICollection)value); + possibleSuperiorsList.AddRange(collection); } else { @@ -704,9 +704,9 @@ public ActiveDirectorySchemaPropertyCollection MandatoryProperties if (!listEmpty) { - if (value is ICollection) + if (value is ICollection collection) { - mandatoryPropertiesList.AddRange((ICollection)value); + mandatoryPropertiesList.AddRange(collection); } else { @@ -780,9 +780,9 @@ public ActiveDirectorySchemaPropertyCollection OptionalProperties if (!listEmpty) { - if (value is ICollection) + if (value is ICollection collection) { - optionalPropertiesList.AddRange((ICollection)value); + optionalPropertiesList.AddRange(collection); } else { @@ -865,9 +865,9 @@ public ActiveDirectorySchemaClassCollection AuxiliaryClasses if (!listEmpty) { - if (value is ICollection) + if (value is ICollection collection) { - auxiliaryClassesList.AddRange((ICollection)value); + auxiliaryClassesList.AddRange(collection); } else { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs index 92504917d598a4..df4c73098cec9c 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs @@ -324,13 +324,13 @@ protected override void OnValidate(object value) { ArgumentNullException.ThrowIfNull(value); - if (!(value is ActiveDirectorySchemaClass)) + if (value is not ActiveDirectorySchemaClass activeDirectorySchemaClass) { throw new ArgumentException(null, nameof(value)); } - if (!((ActiveDirectorySchemaClass)value).isBound) - throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, ((ActiveDirectorySchemaClass)value).Name)); + if (!activeDirectorySchemaClass.isBound) + throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, activeDirectorySchemaClass.Name)); } internal string[] GetMultiValuedProperty() diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs index 3e55f3d893ad44..35f3682acc1eac 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs @@ -341,11 +341,11 @@ protected override void OnValidate(object value) { ArgumentNullException.ThrowIfNull(value); - if (!(value is ActiveDirectorySchemaProperty)) + if (value is not ActiveDirectorySchemaProperty activeDirectorySchemaProperty) throw new ArgumentException(null, nameof(value)); - if (!((ActiveDirectorySchemaProperty)value).isBound) - throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, ((ActiveDirectorySchemaProperty)value).Name)); + if (!activeDirectorySchemaProperty.isBound) + throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, activeDirectorySchemaProperty.Name)); } internal string[] GetMultiValuedProperty() diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs index 879a0ba5c9862a..3e8513a4d92af0 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs @@ -229,11 +229,11 @@ protected override void OnValidate(object value) { ArgumentNullException.ThrowIfNull(value); - if (!(value is ActiveDirectorySite)) + if (value is not ActiveDirectorySite activeDirectorySite) throw new ArgumentException(null, nameof(value)); - if (!((ActiveDirectorySite)value).existing) - throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, ((ActiveDirectorySite)value).Name)); + if (!activeDirectorySite.existing) + throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, activeDirectorySite.Name)); } } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs index 4556ef69e05a77..021afe28b35d4d 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs @@ -230,11 +230,11 @@ protected override void OnValidate(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); - if (!(value is ActiveDirectorySiteLink)) + if (value is not ActiveDirectorySiteLink activeDirectorySiteLink) throw new ArgumentException(null, nameof(value)); - if (!((ActiveDirectorySiteLink)value).existing) - throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted, ((ActiveDirectorySiteLink)value).Name)); + if (!activeDirectorySiteLink.existing) + throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted, activeDirectorySiteLink.Name)); } } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs index 39522945c39c36..608d4dd18e0541 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs @@ -267,11 +267,11 @@ protected override void OnValidate(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); - if (!(value is ActiveDirectorySubnet)) + if (value is not ActiveDirectorySubnet activeDirectorySubnet) throw new ArgumentException(null, nameof(value)); - if (!((ActiveDirectorySubnet)value).existing) - throw new InvalidOperationException(SR.Format(SR.SubnetNotCommitted, ((ActiveDirectorySubnet)value).Name)); + if (!activeDirectorySubnet.existing) + throw new InvalidOperationException(SR.Format(SR.SubnetNotCommitted, activeDirectorySubnet.Name)); } private string MakePath(string subnetDN) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs index 81f6c5609ef2fa..6a11b0bb62da10 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs @@ -70,12 +70,12 @@ public int Add(DirectoryServer server) { if ((!_isADAM)) { - if (!(server is DomainController)) + if (server is not DomainController domainController) throw new ArgumentException(SR.ServerShouldBeDC, nameof(server)); // verify that the version >= 5.2 // DC should be Win 2003 or higher - if (((DomainController)server).NumericOSVersion < 5.2) + if (domainController.NumericOSVersion < 5.2) { throw new ArgumentException(SR.ServerShouldBeW2K3, nameof(server)); } @@ -171,12 +171,12 @@ public void Insert(int index, DirectoryServer server) { if ((!_isADAM)) { - if (!(server is DomainController)) + if (server is not DomainController domainController) throw new ArgumentException(SR.ServerShouldBeDC, nameof(server)); // verify that the version >= 5.2 // DC should be Win 2003 or higher - if (((DomainController)server).NumericOSVersion < 5.2) + if (domainController.NumericOSVersion < 5.2) { throw new ArgumentException(SR.ServerShouldBeW2K3, nameof(server)); } @@ -379,19 +379,19 @@ protected override void OnValidate(object value) if (_isADAM) { // for adam this should be an ADAMInstance - if (!(value is AdamInstance)) + if (value is not AdamInstance) throw new ArgumentException(SR.ServerShouldBeAI, nameof(value)); } else { // for AD this should be a DomainController - if (!(value is DomainController)) + if (value is not DomainController) throw new ArgumentException(SR.ServerShouldBeDC, nameof(value)); } } else { - if (!(value is DirectoryServer)) + if (value is not DirectoryServer) throw new ArgumentException(null, nameof(value)); } } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs index afe54c0ed7ad5b..8624aa4ab98d19 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs @@ -19,8 +19,8 @@ public string this[int index] { object returnValue = InnerList[index]!; - if (returnValue is Exception) - throw (Exception)returnValue; + if (returnValue is Exception exception) + throw exception; else return (string)returnValue; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs index d7a7e1c6cd8da7..e440ce4ddd8652 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs @@ -941,7 +941,7 @@ private void ValidateTargetAndSourceServer(DirectoryContext context, DirectorySe throw new ArgumentException(SR.DirectoryContextNeedHost, nameof(context)); } - if (targetIsDC && !(sourceServer is DomainController)) + if (targetIsDC && sourceServer is not DomainController) { // target and sourceServer are not of the same type throw new ArgumentException(SR.ConnectionSourcServerShouldBeDC, nameof(sourceServer)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs index d77c4c4748d7e7..c54fb279c1f7cb 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs @@ -445,7 +445,7 @@ public DirectoryEntryConfiguration? Options get { // only LDAP provider supports IADsObjectOptions, so make the check here - if (!(AdsObject is UnsafeNativeMethods.IAdsObjectOptions)) + if (AdsObject is not UnsafeNativeMethods.IAdsObjectOptions) return null; return _options; @@ -454,7 +454,7 @@ public DirectoryEntryConfiguration? Options internal void InitADsObjectOptions() { - if (_adsObject is UnsafeNativeMethods.IAdsObjectOptions2) + if (_adsObject is UnsafeNativeMethods.IAdsObjectOptions2 adsObjectOptions2) { //-------------------------------------------- // Check if ACCUMULATE_MODIFICATION is available @@ -464,7 +464,7 @@ internal void InitADsObjectOptions() // check whether the new option is available // 8 is ADS_OPTION_ACCUMULATIVE_MODIFICATION - unmanagedResult = ((UnsafeNativeMethods.IAdsObjectOptions2)_adsObject).GetOption(8, out o); + unmanagedResult = adsObjectOptions2.GetOption(8, out o); if (unmanagedResult != 0) { // rootdse does not support this option and invalid parameter due to without accumulative change fix in ADSI @@ -480,7 +480,7 @@ internal void InitADsObjectOptions() // the new option is available, set it so we get the new PutEx behavior that will allow multiple changes ComVariant value = ComVariant.Create(true); - ((UnsafeNativeMethods.IAdsObjectOptions2)_adsObject).SetOption(8, value); + adsObjectOptions2.SetOption(8, value); allowMultipleChange = true; } @@ -678,10 +678,10 @@ public DirectoryEntry CopyTo(DirectoryEntry newParent, string? newName) /// public void DeleteTree() { - if (!(AdsObject is UnsafeNativeMethods.IAdsDeleteOps)) + if (AdsObject is not UnsafeNativeMethods.IAdsDeleteOps adsDeleteOps) throw new InvalidOperationException(SR.DSCannotDelete); - UnsafeNativeMethods.IAdsDeleteOps entry = (UnsafeNativeMethods.IAdsDeleteOps)AdsObject; + UnsafeNativeMethods.IAdsDeleteOps entry = adsDeleteOps; try { entry.DeleteObject(0); @@ -869,7 +869,7 @@ public void InvokeSet(string propertyName, params object?[]? args) public void MoveTo(DirectoryEntry newParent, string? newName) { object? newEntry = null; - if (!(newParent.AdsObject is UnsafeNativeMethods.IAdsContainer)) + if (newParent.AdsObject is not UnsafeNativeMethods.IAdsContainer) throw new InvalidOperationException(SR.Format(SR.DSNotAContainer, newParent.Path)); try { @@ -1079,10 +1079,10 @@ private void Unbind() // Get the IAdsPropertyList interface // (Check that the IAdsPropertyList interface is supported) // - if (!(NativeObject is UnsafeNativeMethods.IAdsPropertyList)) + if (NativeObject is not UnsafeNativeMethods.IAdsPropertyList adsPropertyList) throw new NotSupportedException(SR.DSPropertyListUnsupported); - UnsafeNativeMethods.IAdsPropertyList list = (UnsafeNativeMethods.IAdsPropertyList)NativeObject; + UnsafeNativeMethods.IAdsPropertyList list = adsPropertyList; UnsafeNativeMethods.IAdsPropertyEntry propertyEntry = (UnsafeNativeMethods.IAdsPropertyEntry)list.GetPropertyItem(SecurityDescriptorProperty, (int)AdsType.ADSTYPE_OCTET_STRING); GC.KeepAlive(this); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs index cdc2a4951234f4..8048336bfd71a5 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs @@ -611,7 +611,7 @@ private SearchResultCollection FindAll(bool findMoreThanOne) DirectoryEntry clonedRoot = SearchRoot!.CloneBrowsable(); UnsafeNativeMethods.IAds adsObject = clonedRoot.AdsObject; - if (!(adsObject is UnsafeNativeMethods.IDirectorySearch)) + if (adsObject is not UnsafeNativeMethods.IDirectorySearch directorySearch) throw new NotSupportedException(SR.Format(SR.DSSearchUnsupported, SearchRoot.Path)); // this is a little bit hacky, but we need to perform a bind here, so we make sure the LDAP connection that we hold has more than @@ -625,7 +625,7 @@ private SearchResultCollection FindAll(bool findMoreThanOne) SearchRoot.Bind(true); } - UnsafeNativeMethods.IDirectorySearch adsSearch = (UnsafeNativeMethods.IDirectorySearch)adsObject; + UnsafeNativeMethods.IDirectorySearch adsSearch = directorySearch; SetSearchPreferences(adsSearch, findMoreThanOne); string[]? properties = null; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs index 5dbb2c3803820c..16a7042f954b2a 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs @@ -51,12 +51,12 @@ public int Count { get { - if (!(_entry.AdsObject is UnsafeNativeMethods.IAdsPropertyList)) + if (_entry.AdsObject is not UnsafeNativeMethods.IAdsPropertyList adsPropertyList) throw new NotSupportedException(SR.DSCannotCount); _entry.FillCache(""); - UnsafeNativeMethods.IAdsPropertyList propList = (UnsafeNativeMethods.IAdsPropertyList)_entry.AdsObject; + UnsafeNativeMethods.IAdsPropertyList propList = adsPropertyList; return propList.PropertyCount; } @@ -99,7 +99,7 @@ public void CopyTo(PropertyValueCollection[] array, int index) /// public IDictionaryEnumerator GetEnumerator() { - if (!(_entry.AdsObject is UnsafeNativeMethods.IAdsPropertyList)) + if (_entry.AdsObject is not UnsafeNativeMethods.IAdsPropertyList) throw new NotSupportedException(SR.DSCannotEmunerate); // Once an object has been used for an enumerator once, it can't be used again, because it only diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs index 99fd009c3c0637..587e874a871ee7 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs @@ -97,18 +97,18 @@ public object? Value // we could not do Clear and Add, we have to bypass the existing collection cache _changeList.Clear(); - if (value is Array) + if (value is Array array) { // byte[] is a special case, we will follow what ADSI is doing, it must be an octet string. So treat it as a single valued attribute if (value is byte[]) _changeList.Add(value); - else if (value is object[]) - _changeList.AddRange((object[])value); + else if (value is object[] objects) + _changeList.AddRange(objects); else { //Need to box value type array elements. - object[] objArray = new object[((Array)value).Length]; - ((Array)value).CopyTo(objArray, 0); + object[] objArray = new object[array.Length]; + array.CopyTo(objArray, 0); _changeList.AddRange((object[])objArray); } } @@ -191,8 +191,8 @@ private void PopulateList() throw COMExceptionHelper.CreateFormattedComException(unmanagedResult); } } - if (var is ICollection) - InnerList.AddRange((ICollection)var); + if (var is ICollection collection) + InnerList.AddRange(collection); else InnerList.Add(var); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyValueCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyValueCollection.cs index 508802c99963ef..78a7eb6c852743 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyValueCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyValueCollection.cs @@ -20,8 +20,8 @@ public object this[int index] get { object returnValue = InnerList[index]!; - if (returnValue is Exception) - throw (Exception)returnValue; + if (returnValue is Exception exception) + throw exception; else return returnValue; } diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs index 19ed7644e1cecc..e3e6005ae8f8fa 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs @@ -520,7 +520,7 @@ private static int CompareUsingSystemUri(Uri? firstUri, Uri? secondUri) private static string GetStringForPartUriFromAnyUri(Uri partUri) { Debug.Assert(partUri != null, "Null reference check for this uri parameter should have been made earlier"); - Debug.Assert(!(partUri is ValidatedPartUri), "This method should only be called when we have not already validated the part uri"); + Debug.Assert(partUri is not ValidatedPartUri, "This method should only be called when we have not already validated the part uri"); Uri safeUnescapedUri; diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Logical.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Logical.cs index 9ce554cf17f205..55eea7d26b0612 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Logical.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Logical.cs @@ -75,7 +75,7 @@ private static bool Significant(Expression node) } return false; } - return NotEmpty(node) && !(node is DebugInfoExpression); + return NotEmpty(node) && node is not DebugInfoExpression; } #endregion diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs index 730bbb377990d7..f3ebb90fafe081 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Statements.cs @@ -445,9 +445,9 @@ private bool TryEmitSwitchInstruction(SwitchExpression node, CompilationFlags fl private static decimal ConvertSwitchValue(object? value) { - if (value is char) + if (value is char ch) { - return (int)(char)value; + return (int)ch; } return Convert.ToDecimal(value, CultureInfo.InvariantCulture); } @@ -646,7 +646,7 @@ private bool TryEmitHashtableSwitch(SwitchExpression node, CompilationFlags flag { foreach (Expression t in c.TestValues) { - if (!(t is ConstantExpression)) + if (t is not ConstantExpression) { return false; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs index ce8867e87a43ce..cff6e164c4eec3 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs @@ -94,7 +94,7 @@ public static CallInstruction Create(MethodInfo info, ParameterInfo[] parameters } catch (TargetInvocationException tie) { - if (!(tie.InnerException is NotSupportedException)) + if (tie.InnerException is not NotSupportedException) { throw; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs index ccefd14a9a2e9f..15de5c18284034 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs @@ -316,7 +316,7 @@ public override int Run(InterpretedFrame frame) } catch (Exception exception) when (_tryHandler.HasHandler(frame, exception, out ExceptionHandler? exHandler, out object? unwrappedException)) { - Debug.Assert(!(unwrappedException is RethrowException)); + Debug.Assert(unwrappedException is not RethrowException); frame.InstructionIndex += frame.Goto(exHandler.LabelIndex, unwrappedException, gotoExceptionHandler: true); #if FEATURE_THREAD_ABORT diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs index 148e24f812e07e..e73227a4e535f3 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs @@ -351,9 +351,9 @@ public void EmitLoad(object? value, Type? type) if (type == null || type.IsValueType) { - if (value is bool) + if (value is bool b) { - EmitLoad((bool)value); + EmitLoad(b); return; } diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Inlined/InlinedAggregationOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Inlined/InlinedAggregationOperator.cs index f46df11ab721a9..edd168a2d49364 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Inlined/InlinedAggregationOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Inlined/InlinedAggregationOperator.cs @@ -57,7 +57,7 @@ internal TResult Aggregate() catch (Exception ex) { // If the exception is not an aggregate, we must wrap it up and throw that instead. - if (!(ex is AggregateException)) + if (ex is not AggregateException) { // // Special case: if the query has been canceled, we do not want to wrap the diff --git a/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs b/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs index a6d03bfa40918f..4c061c45189428 100644 --- a/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs +++ b/src/libraries/System.Linq/src/System/Linq/SkipTake.SpeedOpt.cs @@ -229,7 +229,7 @@ private sealed class IEnumerableSkipTakeIterator : Iterator internal IEnumerableSkipTakeIterator(IEnumerable source, int minIndexInclusive, int maxIndexInclusive) { Debug.Assert(source is not null); - Debug.Assert(!(source is IList), $"The caller needs to check for {nameof(IList)}."); + Debug.Assert(source is not IList, $"The caller needs to check for {nameof(IList)}."); Debug.Assert(minIndexInclusive >= 0); Debug.Assert(maxIndexInclusive >= -1); // Note that although maxIndexInclusive can't grow, it can still be int.MaxValue. diff --git a/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs b/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs index 76a77643843a8f..8bf5063d6a2fae 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementBaseObject.cs @@ -652,9 +652,9 @@ public override bool Equals(object obj) try { - if (obj is ManagementBaseObject) + if (obj is ManagementBaseObject managementBaseObject) { - result = CompareTo((ManagementBaseObject)obj, ComparisonSettings.IncludeAll); + result = CompareTo(managementBaseObject, ComparisonSettings.IncludeAll); } else { diff --git a/src/libraries/System.Management/src/System/Management/ManagementException.cs b/src/libraries/System.Management/src/System/Management/ManagementException.cs index 10c1e7cbf4fdb2..3443847f957233 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementException.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementException.cs @@ -648,19 +648,19 @@ internal ManagementException(Exception e, string msg, ManagementBaseObject errOb { try { - if (e is ManagementException) + if (e is ManagementException managementException) { - errorCode = ((ManagementException)e).ErrorCode; + errorCode = managementException.ErrorCode; // May/may not have extended error info. // if (errorObject != null) - errorObject = (ManagementBaseObject)((ManagementException)e).errorObject.Clone(); + errorObject = (ManagementBaseObject)managementException.errorObject.Clone(); else errorObject = null; } - else if (e is COMException) - errorCode = (ManagementStatus)((COMException)e).ErrorCode; + else if (e is COMException cOMException) + errorCode = (ManagementStatus)cOMException.ErrorCode; else errorCode = (ManagementStatus)this.HResult; } @@ -709,7 +709,7 @@ public ManagementException(string message) : this(ManagementStatus.Failed, messa public ManagementException(string message, Exception innerException) : this(innerException, message, null) { // if the exception passed is not a ManagementException, then initialize the ErrorCode to Failed - if (!(innerException is ManagementException)) + if (innerException is not ManagementException) errorCode = ManagementStatus.Failed; } @@ -737,11 +737,11 @@ private static string GetMessage(Exception e) { string msg = null; - if (e is COMException) + if (e is COMException cOMException) { // Try and get WMI error message. If not use the one in // the exception - msg = GetMessage((ManagementStatus)((COMException)e).ErrorCode); + msg = GetMessage((ManagementStatus)cOMException.ErrorCode); } if (null == msg) diff --git a/src/libraries/System.Management/src/System/Management/ManagementObject.cs b/src/libraries/System.Management/src/System/Management/ManagementObject.cs index 6686227dd59890..46120af3439cf1 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementObject.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementObject.cs @@ -1671,9 +1671,9 @@ internal void HandleObjectPut(object sender, InternalObjectPutEventArgs e) { try { - if (sender is WmiEventSink) + if (sender is WmiEventSink wmiEventSink) { - ((WmiEventSink)sender).InternalObjectPut -= new InternalObjectPutEventHandler(this.HandleObjectPut); + wmiEventSink.InternalObjectPut -= new InternalObjectPutEventHandler(this.HandleObjectPut); putButNotGot = true; path.SetRelativePath(e.Path.RelativePath); } diff --git a/src/libraries/System.Management/src/System/Management/Property.cs b/src/libraries/System.Management/src/System/Management/Property.cs index fcb5d51bb1ae31..22dc1b5589d361 100644 --- a/src/libraries/System.Management/src/System/Management/Property.cs +++ b/src/libraries/System.Management/src/System/Management/Property.cs @@ -565,9 +565,9 @@ internal static object MapValueToWmiValue(object val, CimType type, bool isArray break; case CimType.Object: - if (val is ManagementBaseObject) + if (val is ManagementBaseObject managementBaseObject) { - wmiValue = Marshal.GetObjectForIUnknown(((ManagementBaseObject)val).wbemObject); + wmiValue = Marshal.GetObjectForIUnknown(managementBaseObject.wbemObject); } else { @@ -799,10 +799,10 @@ internal static object MapValueToWmiValue(object val, out bool isArray, out CimT else { // Check for an embedded object - if (val is ManagementBaseObject) + if (val is ManagementBaseObject managementBaseObject) { type = CimType.Object; - wmiValue = Marshal.GetObjectForIUnknown(((ManagementBaseObject)val).wbemObject); + wmiValue = Marshal.GetObjectForIUnknown(managementBaseObject.wbemObject); } } } diff --git a/src/libraries/System.Management/src/System/Management/Qualifier.cs b/src/libraries/System.Management/src/System/Management/Qualifier.cs index 308c53687c58ec..75d92d8bcb1bdb 100644 --- a/src/libraries/System.Management/src/System/Management/Qualifier.cs +++ b/src/libraries/System.Management/src/System/Management/Qualifier.cs @@ -94,13 +94,13 @@ private static object MapQualValueToWmiValue(object qualVal) if (null != qualVal) { - if (qualVal is Array) + if (qualVal is Array array) { if ((qualVal is int[]) || (qualVal is double[]) || (qualVal is string[]) || (qualVal is bool[])) wmiValue = qualVal; else { - Array valArray = (Array)qualVal; + Array valArray = array; int length = valArray.Length; Type elementType = (length > 0 ? valArray.GetValue(0).GetType() : null); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs index 550f5b9f8ca323..fa794fce993760 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs @@ -388,7 +388,7 @@ private static uint ChooseAuthScheme(uint supportedSchemes, Uri? uri, ICredentia return 0; } - if (uri == null && !(credentials is NetworkCredential)) + if (uri == null && credentials is not NetworkCredential) { // https://github.com/dotnet/runtime/issues/16737. // If the credentials are a NetworkCredential, the uri isn't used when calling .GetCredential() since diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs index f90327e07cd994..6126e05afc985a 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs @@ -249,7 +249,7 @@ private static void OnRequestRedirect(WinHttpRequestState state, Uri redirectUri // For security reasons, we drop the server credential if it is a // NetworkCredential. But we allow credentials in a CredentialCache // since they are specifically tied to URI's. - if (!(state.ServerCredentials is CredentialCache)) + if (state.ServerCredentials is not CredentialCache) { state.ServerCredentials = null; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/CancellationHelper.cs b/src/libraries/System.Net.Http/src/System/Net/Http/CancellationHelper.cs index cf6fdd6b5f48fe..74f141fcd0aad1 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/CancellationHelper.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/CancellationHelper.cs @@ -17,7 +17,7 @@ internal static class CancellationHelper /// The that may have triggered the exception. /// true if the exception should be wrapped; otherwise, false. internal static bool ShouldWrapInOperationCanceledException(Exception exception, CancellationToken cancellationToken) => - !(exception is OperationCanceledException) && cancellationToken.IsCancellationRequested; + exception is not OperationCanceledException && cancellationToken.IsCancellationRequested; /// Creates a cancellation exception. /// The inner exception to wrap. May be null. diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs index f6dafc471ec871..f6a0bd9971f7b8 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs @@ -1014,7 +1014,7 @@ private static bool TryParseAndAddRawHeaderValue(HeaderDescriptor descriptor, He private static void AddParsedValue(HeaderStoreItemInfo info, object value) { - Debug.Assert(!(value is List), + Debug.Assert(value is not List, "Header value types must not derive from List since this type is used internally to store " + "lists of values. So we would not be able to distinguish between a single value and a list of values."); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs index 0932d3de29a208..696b19c38f24b2 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs @@ -91,7 +91,7 @@ internal HttpListenerWebSocketContext( { if (user != null) { - if (!(user is WindowsPrincipal)) + if (user is not WindowsPrincipal) { // AuthenticationSchemes.Basic. if (user.Identity is HttpListenerBasicIdentity basicIdentity) diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs index 5744d9faceea55..85b0dfd72bc6c9 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs @@ -149,7 +149,7 @@ internal async Task GetConnectionAsync(string host, int port, Cancel if (!_serverSupportsStartTls) { // Either TLS is already established or server does not support TLS - if (!(_stream is SslStream)) + if (_stream is not SslStream) { throw new SmtpException(SR.MailServerDoesNotSupportStartTls); } diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs index 6673d8483ec158..de6370f2fa862f 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs @@ -390,7 +390,7 @@ protected override PipelineInstruction PipelineCallback(PipelineEntry? entry, Re // If NetworkStream is a SslStream, then this must be in the async callback // from completing the SSL handshake. // So just let the pipeline continue. - if (!(Stream is SslStream)) + if (Stream is not SslStream) { FtpWebRequest request = (FtpWebRequest)_request!; #pragma warning disable SYSLIB0014 // ServicePointManager is obsolete diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs index 91b95a5eea6604..f0c84f00bf353c 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -1101,10 +1101,10 @@ private void SetException(Exception exception) FtpControlStream? connection = _connection; if (_exception == null) { - if (exception is WebException) + if (exception is WebException webException) { EnsureFtpWebResponse(); - _exception = new WebException(exception.Message, null, ((WebException)exception).Status, _ftpWebResponse); + _exception = new WebException(exception.Message, null, webException.Status, _ftpWebResponse); } else if (exception is AuthenticationException || exception is SecurityException) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs index d4bc05e5949e9b..d026565ce2ccfd 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs @@ -1166,7 +1166,7 @@ public override Stream EndGetRequestStream(IAsyncResult asyncResult) { CheckAbort(); - if (asyncResult == null || !(asyncResult is Task)) + if (asyncResult == null || asyncResult is not Task) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } @@ -1439,7 +1439,7 @@ public override WebResponse EndGetResponse(IAsyncResult asyncResult) { CheckAbort(); - if (asyncResult == null || !(asyncResult is Task)) + if (asyncResult == null || asyncResult is not Task) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs index b5c1cde85be047..bf5b3677775edb 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs @@ -708,7 +708,7 @@ private void ValidateCreateContext( private void SetFailed(Exception e) { - if (_exception == null || !(_exception.SourceException is ObjectDisposedException)) + if (_exception == null || _exception.SourceException is not ObjectDisposedException) { _exception = ExceptionDispatchInfo.Capture(e); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs index 00adb9147ea13f..76c94b03595b1e 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs @@ -239,7 +239,7 @@ public override int Read(byte[] buffer, int offset, int count) { return _streamSocket.Receive(buffer, offset, count, 0); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_readfailure, exception); } @@ -264,7 +264,7 @@ public override int Read(Span buffer) { return _streamSocket.Receive(buffer, SocketFlags.None); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_readfailure, exception); } @@ -311,7 +311,7 @@ public override void Write(byte[] buffer, int offset, int count) // after ALL the requested number of bytes was transferred. _streamSocket.Send(buffer, offset, count, SocketFlags.None); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_writefailure, exception); } @@ -337,7 +337,7 @@ public override void Write(ReadOnlySpan buffer) { _streamSocket.Send(buffer, SocketFlags.None); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_writefailure, exception); } @@ -451,7 +451,7 @@ public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, Asy callback, state); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_readfailure, exception); } @@ -476,7 +476,7 @@ public override int EndRead(IAsyncResult asyncResult) { return _streamSocket.EndReceive(asyncResult); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_readfailure, exception); } @@ -518,7 +518,7 @@ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, As callback, state); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_writefailure, exception); } @@ -539,7 +539,7 @@ public override void EndWrite(IAsyncResult asyncResult) { _streamSocket.EndSend(asyncResult); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_writefailure, exception); } @@ -577,7 +577,7 @@ public override Task ReadAsync(byte[] buffer, int offset, int count, Cancel fromNetworkStream: true, cancellationToken).AsTask(); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_readfailure, exception); } @@ -600,7 +600,7 @@ public override ValueTask ReadAsync(Memory buffer, CancellationToken fromNetworkStream: true, cancellationToken: cancellationToken); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_readfailure, exception); } @@ -637,7 +637,7 @@ public override Task WriteAsync(byte[] buffer, int offset, int count, Cancellati SocketFlags.None, cancellationToken).AsTask(); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_writefailure, exception); } @@ -659,7 +659,7 @@ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationTo SocketFlags.None, cancellationToken); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) + catch (Exception exception) when (exception is not OutOfMemoryException) { throw WrapException(SR.net_io_writefailure, exception); } diff --git a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs index ac1c9e295b8858..7e8375a6580a2d 100644 --- a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs +++ b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs @@ -305,7 +305,7 @@ private byte[] DownloadDataInternal(Uri address, out WebRequest request) tmpRequest = _webRequest = GetWebRequest(GetUri(address)); result = DownloadBits(tmpRequest, new ChunkedMemoryStream())!; } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { AbortRequest(tmpRequest); if (e is WebException || e is SecurityException) throw; @@ -335,7 +335,7 @@ public void DownloadFile(Uri address, string fileName) DownloadBits(request, fs); succeeded = true; } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { AbortRequest(request); if (e is WebException || e is SecurityException) throw; @@ -370,7 +370,7 @@ public Stream OpenRead(Uri address) WebResponse response = _webResponse = GetWebResponse(request); return response.GetResponseStream(); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { AbortRequest(request); if (e is WebException || e is SecurityException) throw; @@ -408,7 +408,7 @@ public Stream OpenWrite(Uri address, string? method) request, this); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { AbortRequest(request); if (e is WebException || e is SecurityException) throw; @@ -460,7 +460,7 @@ private byte[] UploadDataInternal(Uri address, string method, byte[] data, out W tmpRequest = _webRequest = GetWebRequest(GetUri(address)); result = UploadBits(tmpRequest, null, data, 0, null, null); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { AbortRequest(tmpRequest); if (e is WebException || e is SecurityException) throw; @@ -640,7 +640,7 @@ public byte[] UploadValues(Uri address, string? method, NameValueCollection data request = _webRequest = GetWebRequest(GetUri(address)); return UploadBits(request, null, buffer, 0, null, null); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { AbortRequest(request); if (e is WebException || e is SecurityException) throw; @@ -705,7 +705,7 @@ public string DownloadString(Uri address) private static void AbortRequest(WebRequest? request) { try { request?.Abort(); } - catch (Exception exception) when (!(exception is OutOfMemoryException)) { } + catch (Exception exception) when (exception is not OutOfMemoryException) { } } private void CopyHeadersTo(WebRequest request) @@ -855,7 +855,7 @@ private Uri GetUri(Uri address) return (writeStream as ChunkedMemoryStream)?.ToArray(); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { writeStream?.Close(); AbortRequest(request); @@ -925,7 +925,7 @@ private async void DownloadBitsAsync( completionDelegate((writeStream as ChunkedMemoryStream)?.ToArray(), null, asyncOp); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { exception = GetExceptionToPropagate(e); AbortRequest(request); @@ -993,7 +993,7 @@ private byte[] UploadBits( return DownloadBits(request, new ChunkedMemoryStream())!; } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { AbortRequest(request); if (e is WebException || e is SecurityException) throw; @@ -1068,7 +1068,7 @@ private async void UploadBitsAsync( DownloadBitsAsync(request, new ChunkedMemoryStream(), asyncOp, completionDelegate); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { exception = GetExceptionToPropagate(e); AbortRequest(request); @@ -1207,7 +1207,7 @@ public void OpenReadAsync(Uri address, object? userToken) WebResponse response = _webResponse = GetWebResponse(request, iar); stream = response.GetResponseStream(); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { exception = GetExceptionToPropagate(e); } @@ -1215,7 +1215,7 @@ public void OpenReadAsync(Uri address, object? userToken) InvokeOperationCompleted(asyncOp, _openReadOperationCompleted!, new OpenReadCompletedEventArgs(stream, exception, _canceled, asyncOp.UserSuppliedState)); }, null); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { InvokeOperationCompleted(asyncOp, _openReadOperationCompleted!, new OpenReadCompletedEventArgs(null, GetExceptionToPropagate(e), _canceled, asyncOp.UserSuppliedState)); @@ -1248,7 +1248,7 @@ public void OpenWriteAsync(Uri address, string? method, object? userToken) { stream = new WebClientWriteStream(request.EndGetRequestStream(iar), request, this); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { exception = GetExceptionToPropagate(e); } @@ -1256,7 +1256,7 @@ public void OpenWriteAsync(Uri address, string? method, object? userToken) InvokeOperationCompleted(asyncOp, _openWriteOperationCompleted!, new OpenWriteCompletedEventArgs(stream, exception, _canceled, asyncOp.UserSuppliedState)); }, null); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { var eventArgs = new OpenWriteCompletedEventArgs(null, GetExceptionToPropagate(e), _canceled, asyncOp.UserSuppliedState); InvokeOperationCompleted(asyncOp, _openWriteOperationCompleted!, eventArgs); @@ -1274,7 +1274,7 @@ private void DownloadStringAsyncCallback(byte[]? returnBytes, Exception? excepti stringData = GetStringUsingEncoding(_webRequest!, returnBytes); } } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { exception = GetExceptionToPropagate(e); } @@ -1297,7 +1297,7 @@ public void DownloadStringAsync(Uri address, object? userToken) WebRequest request = _webRequest = GetWebRequest(GetUri(address)); DownloadBitsAsync(request, new ChunkedMemoryStream(), asyncOp, DownloadStringAsyncCallback); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { DownloadStringAsyncCallback(null, GetExceptionToPropagate(e), asyncOp); } @@ -1323,7 +1323,7 @@ public void DownloadDataAsync(Uri address, object? userToken) WebRequest request = _webRequest = GetWebRequest(GetUri(address)); DownloadBitsAsync(request, new ChunkedMemoryStream(), asyncOp, DownloadDataAsyncCallback); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { DownloadDataAsyncCallback(null, GetExceptionToPropagate(e), asyncOp); } @@ -1352,7 +1352,7 @@ public void DownloadFileAsync(Uri address, string fileName, object? userToken) WebRequest request = _webRequest = GetWebRequest(GetUri(address)); DownloadBitsAsync(request, fs, asyncOp, DownloadFileAsyncCallback); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { fs?.Close(); DownloadFileAsyncCallback(null, GetExceptionToPropagate(e), asyncOp); @@ -1391,7 +1391,7 @@ public void UploadStringAsync(Uri address, string? method, string data, object? { stringResult = GetStringUsingEncoding(_webRequest, bytesResult); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { error = GetExceptionToPropagate(e); } @@ -1401,7 +1401,7 @@ public void UploadStringAsync(Uri address, string? method, string data, object? new UploadStringCompletedEventArgs(stringResult, error, _canceled, uploadAsyncOp.UserSuppliedState)); }); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { var eventArgs = new UploadStringCompletedEventArgs(null, GetExceptionToPropagate(e), _canceled, asyncOp.UserSuppliedState); InvokeOperationCompleted(asyncOp, _uploadStringOperationCompleted!, eventArgs); @@ -1440,7 +1440,7 @@ public void UploadDataAsync(Uri address, string? method, byte[] data, object? us (result, error, uploadAsyncOp) => InvokeOperationCompleted(asyncOp, _uploadDataOperationCompleted!, new UploadDataCompletedEventArgs(result, error, _canceled, uploadAsyncOp.UserSuppliedState))); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { var eventArgs = new UploadDataCompletedEventArgs(null, GetExceptionToPropagate(e), _canceled, asyncOp.UserSuppliedState); InvokeOperationCompleted(asyncOp, _uploadDataOperationCompleted!, eventArgs); @@ -1476,7 +1476,7 @@ public void UploadFileAsync(Uri address, string? method, string fileName, object (result, error, uploadAsyncOp) => InvokeOperationCompleted(asyncOp, _uploadFileOperationCompleted!, new UploadFileCompletedEventArgs(result, error, _canceled, uploadAsyncOp.UserSuppliedState))); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { fs?.Close(); var eventArgs = new UploadFileCompletedEventArgs(null, GetExceptionToPropagate(e), _canceled, asyncOp.UserSuppliedState); @@ -1516,7 +1516,7 @@ public void UploadValuesAsync(Uri address, string? method, NameValueCollection d (result, error, uploadAsyncOp) => InvokeOperationCompleted(asyncOp, _uploadValuesOperationCompleted!, new UploadValuesCompletedEventArgs(result, error, _canceled, uploadAsyncOp.UserSuppliedState))); } - catch (Exception e) when (!(e is OutOfMemoryException)) + catch (Exception e) when (e is not OutOfMemoryException) { var eventArgs = new UploadValuesCompletedEventArgs(null, GetExceptionToPropagate(e), _canceled, asyncOp.UserSuppliedState!); InvokeOperationCompleted(asyncOp, _uploadValuesOperationCompleted!, eventArgs); diff --git a/src/libraries/System.Private.CoreLib/src/System/Boolean.cs b/src/libraries/System.Private.CoreLib/src/System/Boolean.cs index d2619daba89ebe..007d90c69559fe 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Boolean.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Boolean.cs @@ -119,12 +119,12 @@ public bool TryFormat(Span destination, out int charsWritten) public override bool Equals([NotNullWhen(true)] object? obj) { // If it's not a boolean, we're definitely not equal - if (!(obj is bool)) + if (obj is not bool b) { return false; } - return m_value == ((bool)obj).m_value; + return m_value == b.m_value; } [NonVersionable] @@ -146,12 +146,12 @@ public int CompareTo(object? obj) { return 1; } - if (!(obj is bool)) + if (obj is not bool b) { throw new ArgumentException(SR.Arg_MustBeBoolean); } - if (m_value == ((bool)obj).m_value) + if (m_value == b.m_value) { return 0; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Byte.cs b/src/libraries/System.Private.CoreLib/src/System/Byte.cs index e6a38afe6152b4..c6a14d94da1989 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Byte.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Byte.cs @@ -58,12 +58,12 @@ public int CompareTo(object? value) { return 1; } - if (!(value is byte)) + if (value is not byte b) { throw new ArgumentException(SR.Arg_MustBeByte); } - return m_value - (((byte)value).m_value); + return m_value - (b.m_value); } public int CompareTo(byte value) @@ -74,11 +74,11 @@ public int CompareTo(byte value) // Determines whether two Byte objects are equal. public override bool Equals([NotNullWhen(true)] object? obj) { - if (!(obj is byte)) + if (obj is not byte b) { return false; } - return m_value == ((byte)obj).m_value; + return m_value == b.m_value; } [NonVersionable] diff --git a/src/libraries/System.Private.CoreLib/src/System/Char.cs b/src/libraries/System.Private.CoreLib/src/System/Char.cs index e0018e74006088..85008c4a84c595 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Char.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Char.cs @@ -116,11 +116,11 @@ public override int GetHashCode() // public override bool Equals([NotNullWhen(true)] object? obj) { - if (!(obj is char)) + if (obj is not char ch) { return false; } - return m_value == ((char)obj).m_value; + return m_value == ch.m_value; } [NonVersionable] @@ -160,12 +160,12 @@ public int CompareTo(object? value) { return 1; } - if (!(value is char)) + if (value is not char ch) { throw new ArgumentException(SR.Arg_MustBeChar); } - return m_value - ((char)value).m_value; + return m_value - ch.m_value; } public int CompareTo(char value) diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/ConcurrentDictionary.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/ConcurrentDictionary.cs index 2fd608e1d108ea..5e6942d7881e2f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/ConcurrentDictionary.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/ConcurrentDictionary.cs @@ -1680,14 +1680,14 @@ void IDictionary.Add(object key, object? value) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - if (!(key is TKey)) + if (key is not TKey tKey) { throw new ArgumentException(SR.ConcurrentDictionary_TypeOfKeyIncorrect); } ThrowIfInvalidObjectValue(value); - ((IDictionary)this).Add((TKey)key, (TValue)value!); + ((IDictionary)this).Add(tKey, (TValue)value!); } /// @@ -1813,14 +1813,14 @@ void IDictionary.Remove(object key) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - if (!(key is TKey)) + if (key is not TKey tKey) { throw new ArgumentException(SR.ConcurrentDictionary_TypeOfKeyIncorrect); } ThrowIfInvalidObjectValue(value); - ((ConcurrentDictionary)this)[(TKey)key] = (TValue)value!; + ((ConcurrentDictionary)this)[tKey] = (TValue)value!; } } @@ -1829,7 +1829,7 @@ private static void ThrowIfInvalidObjectValue(object? value) { if (value is not null) { - if (!(value is TValue)) + if (value is not TValue) { ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfValueIncorrect); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.cs index 1afd6d542769f4..686f2402be5e88 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/EqualityComparer.cs @@ -63,7 +63,7 @@ public static EqualityComparer Create(Func keySelector, IEqu int IEqualityComparer.GetHashCode(object? obj) { if (obj == null) return 0; - if (obj is T) return GetHashCode((T)obj); + if (obj is T t) return GetHashCode(t); ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison); return 0; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs index bae03e1780937f..80a30869dcf71d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs @@ -157,9 +157,9 @@ protected IHashCodeProvider? hcp { get { - if (_keycomparer is CompatibleComparer) + if (_keycomparer is CompatibleComparer compatibleComparer) { - return ((CompatibleComparer)_keycomparer).HashCodeProvider; + return compatibleComparer.HashCodeProvider; } else if (_keycomparer == null) { @@ -192,9 +192,9 @@ protected IComparer? comparer { get { - if (_keycomparer is CompatibleComparer) + if (_keycomparer is CompatibleComparer compatibleComparer) { - return ((CompatibleComparer)_keycomparer).Comparer; + return compatibleComparer.Comparer; } else if (_keycomparer == null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs index de2a682059ae0e..75bd835603995c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs @@ -1064,12 +1064,12 @@ public static int Compare(DateTime t1, DateTime t2) public int CompareTo(object? value) { if (value == null) return 1; - if (!(value is DateTime)) + if (value is not DateTime dateTime) { throw new ArgumentException(SR.Arg_MustBeDateTime); } - return Compare(this, (DateTime)value); + return Compare(this, dateTime); } public int CompareTo(DateTime value) diff --git a/src/libraries/System.Private.CoreLib/src/System/Decimal.cs b/src/libraries/System.Private.CoreLib/src/System/Decimal.cs index a5ff30b93be1b3..d63d652046c31a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Decimal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Decimal.cs @@ -420,10 +420,10 @@ public int CompareTo(object? value) { if (value == null) return 1; - if (!(value is decimal)) + if (value is not decimal d) throw new ArgumentException(SR.Arg_MustBeDecimal); - decimal other = (decimal)value; + decimal other = d; return DecCalc.VarDecCmp(in this, in other); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs index 8851c7ff5c6c96..5fdf1bd186f47f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs @@ -283,96 +283,96 @@ to fill the passed in ETW data descriptor. dataBuffer += BasicTypeAllocationBufferSize; dataDescriptor->Size = (uint)blobRet.Length; } - else if (data is IntPtr) + else if (data is IntPtr intPtr) { dataDescriptor->Size = (uint)sizeof(IntPtr); IntPtr* intptrPtr = (IntPtr*)dataBuffer; - *intptrPtr = (IntPtr)data; + *intptrPtr = intPtr; dataDescriptor->Ptr = (ulong)intptrPtr; } - else if (data is int) + else if (data is int num6) { dataDescriptor->Size = (uint)sizeof(int); int* intptr = (int*)dataBuffer; - *intptr = (int)data; + *intptr = num6; dataDescriptor->Ptr = (ulong)intptr; } - else if (data is long) + else if (data is long num5) { dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; - *longptr = (long)data; + *longptr = num5; dataDescriptor->Ptr = (ulong)longptr; } - else if (data is uint) + else if (data is uint num4) { dataDescriptor->Size = (uint)sizeof(uint); uint* uintptr = (uint*)dataBuffer; - *uintptr = (uint)data; + *uintptr = num4; dataDescriptor->Ptr = (ulong)uintptr; } - else if (data is ulong) + else if (data is ulong num3) { dataDescriptor->Size = (uint)sizeof(ulong); ulong* ulongptr = (ulong*)dataBuffer; - *ulongptr = (ulong)data; + *ulongptr = num3; dataDescriptor->Ptr = (ulong)ulongptr; } - else if (data is char) + else if (data is char ch) { dataDescriptor->Size = (uint)sizeof(char); char* charptr = (char*)dataBuffer; - *charptr = (char)data; + *charptr = ch; dataDescriptor->Ptr = (ulong)charptr; } - else if (data is byte) + else if (data is byte b2) { dataDescriptor->Size = (uint)sizeof(byte); byte* byteptr = (byte*)dataBuffer; - *byteptr = (byte)data; + *byteptr = b2; dataDescriptor->Ptr = (ulong)byteptr; } - else if (data is short) + else if (data is short num2) { dataDescriptor->Size = (uint)sizeof(short); short* shortptr = (short*)dataBuffer; - *shortptr = (short)data; + *shortptr = num2; dataDescriptor->Ptr = (ulong)shortptr; } - else if (data is sbyte) + else if (data is sbyte sb) { dataDescriptor->Size = (uint)sizeof(sbyte); sbyte* sbyteptr = (sbyte*)dataBuffer; - *sbyteptr = (sbyte)data; + *sbyteptr = sb; dataDescriptor->Ptr = (ulong)sbyteptr; } - else if (data is ushort) + else if (data is ushort num) { dataDescriptor->Size = (uint)sizeof(ushort); ushort* ushortptr = (ushort*)dataBuffer; - *ushortptr = (ushort)data; + *ushortptr = num; dataDescriptor->Ptr = (ulong)ushortptr; } - else if (data is float) + else if (data is float f) { dataDescriptor->Size = (uint)sizeof(float); float* floatptr = (float*)dataBuffer; - *floatptr = (float)data; + *floatptr = f; dataDescriptor->Ptr = (ulong)floatptr; } - else if (data is double) + else if (data is double d2) { dataDescriptor->Size = (uint)sizeof(double); double* doubleptr = (double*)dataBuffer; - *doubleptr = (double)data; + *doubleptr = d2; dataDescriptor->Ptr = (ulong)doubleptr; } - else if (data is bool) + else if (data is bool b) { // WIN32 Bool is 4 bytes dataDescriptor->Size = 4; int* intptr = (int*)dataBuffer; - if ((bool)data) + if (b) { *intptr = 1; } @@ -382,28 +382,28 @@ to fill the passed in ETW data descriptor. } dataDescriptor->Ptr = (ulong)intptr; } - else if (data is Guid) + else if (data is Guid guid) { dataDescriptor->Size = (uint)sizeof(Guid); Guid* guidptr = (Guid*)dataBuffer; - *guidptr = (Guid)data; + *guidptr = guid; dataDescriptor->Ptr = (ulong)guidptr; } - else if (data is decimal) + else if (data is decimal d) { dataDescriptor->Size = (uint)sizeof(decimal); decimal* decimalptr = (decimal*)dataBuffer; - *decimalptr = (decimal)data; + *decimalptr = d; dataDescriptor->Ptr = (ulong)decimalptr; } - else if (data is DateTime) + else if (data is DateTime dateTime) { const long UTCMinTicks = 504911232000000000; long dateTimeTicks = 0; // We cannot translate dates sooner than 1/1/1601 in UTC. // To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks - if (((DateTime)data).Ticks > UTCMinTicks) - dateTimeTicks = ((DateTime)data).ToFileTimeUtc(); + if (dateTime.Ticks > UTCMinTicks) + dateTimeTicks = dateTime.ToFileTimeUtc(); dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = dateTimeTicks; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ManifestBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ManifestBuilder.cs index d430213b058f1e..32f92547e05118 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ManifestBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ManifestBuilder.cs @@ -446,8 +446,8 @@ static FieldInfo[] GetEnumFields(Type localEnumType) if (constantValObj != null) { ulong hexValue; - if (constantValObj is ulong) - hexValue = (ulong)constantValObj; // This is the only integer type that can't be represented by a long. + if (constantValObj is ulong num) + hexValue = num; // This is the only integer type that can't be represented by a long. else hexValue = (ulong)Convert.ToInt64(constantValObj); // Handles all integer types except ulong. diff --git a/src/libraries/System.Private.CoreLib/src/System/Int16.cs b/src/libraries/System.Private.CoreLib/src/System/Int16.cs index d7eb5b70c85789..60013b24372e4d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Int16.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Int16.cs @@ -60,9 +60,9 @@ public int CompareTo(object? value) return 1; } - if (value is short) + if (value is short num) { - return m_value - ((short)value).m_value; + return m_value - num.m_value; } throw new ArgumentException(SR.Arg_MustBeInt16); @@ -75,11 +75,11 @@ public int CompareTo(short value) public override bool Equals([NotNullWhen(true)] object? obj) { - if (!(obj is short)) + if (obj is not short num) { return false; } - return m_value == ((short)obj).m_value; + return m_value == num.m_value; } [NonVersionable] diff --git a/src/libraries/System.Private.CoreLib/src/System/Int32.cs b/src/libraries/System.Private.CoreLib/src/System/Int32.cs index b6285e071a2e32..313e5b6241dc08 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Int32.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Int32.cs @@ -92,11 +92,11 @@ public int CompareTo(int value) public override bool Equals([NotNullWhen(true)] object? obj) { - if (!(obj is int)) + if (obj is not int num) { return false; } - return m_value == ((int)obj).m_value; + return m_value == num.m_value; } [NonVersionable] diff --git a/src/libraries/System.Private.CoreLib/src/System/Int64.cs b/src/libraries/System.Private.CoreLib/src/System/Int64.cs index e5dbace947d36f..624b8a7bee1b89 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Int64.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Int64.cs @@ -89,11 +89,11 @@ public int CompareTo(long value) public override bool Equals([NotNullWhen(true)] object? obj) { - if (!(obj is long)) + if (obj is not long num) { return false; } - return m_value == ((long)obj).m_value; + return m_value == num.m_value; } [NonVersionable] diff --git a/src/libraries/System.Private.CoreLib/src/System/Memory.cs b/src/libraries/System.Private.CoreLib/src/System/Memory.cs index c8eac110cb5234..e34ad99875204d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Memory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Memory.cs @@ -446,9 +446,9 @@ public unsafe MemoryHandle Pin() [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals([NotNullWhen(true)] object? obj) { - if (obj is ReadOnlyMemory) + if (obj is ReadOnlyMemory readOnlyMemory) { - return ((ReadOnlyMemory)obj).Equals(this); + return readOnlyMemory.Equals(this); } else if (obj is Memory memory) { diff --git a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs index 2ef440179364ef..7ae925b20441eb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs @@ -6156,7 +6156,7 @@ public bool AppendFormatted(T value) // if it only implements IFormattable, we come out even: only if it implements both do we // end up paying for an extra interface check. string? s; - if (value is IFormattable) + if (value is IFormattable formattable) { // If the value can format itself directly into our buffer, do so. @@ -6171,9 +6171,9 @@ public bool AppendFormatted(T value) return Fail(); } - if (value is ISpanFormattable) + if (value is ISpanFormattable spanFormattable) { - if (((ISpanFormattable)value).TryFormat(_destination.Slice(_pos), out int charsWritten, default, _provider)) // constrained call avoiding boxing for value types + if (spanFormattable.TryFormat(_destination.Slice(_pos), out int charsWritten, default, _provider)) // constrained call avoiding boxing for value types { _pos += charsWritten; return true; @@ -6182,7 +6182,7 @@ public bool AppendFormatted(T value) return Fail(); } - s = ((IFormattable)value).ToString(format: null, _provider); // constrained call avoiding boxing for value types + s = formattable.ToString(format: null, _provider); // constrained call avoiding boxing for value types } else { @@ -6217,7 +6217,7 @@ public bool AppendFormatted(T value, string? format) // if it only implements IFormattable, we come out even: only if it implements both do we // end up paying for an extra interface check. string? s; - if (value is IFormattable) + if (value is IFormattable formattable) { // If the value can format itself directly into our buffer, do so. @@ -6232,9 +6232,9 @@ public bool AppendFormatted(T value, string? format) return Fail(); } - if (value is ISpanFormattable) + if (value is ISpanFormattable spanFormattable) { - if (((ISpanFormattable)value).TryFormat(_destination.Slice(_pos), out int charsWritten, format, _provider)) // constrained call avoiding boxing for value types + if (spanFormattable.TryFormat(_destination.Slice(_pos), out int charsWritten, format, _provider)) // constrained call avoiding boxing for value types { _pos += charsWritten; return true; @@ -6243,7 +6243,7 @@ public bool AppendFormatted(T value, string? format) return Fail(); } - s = ((IFormattable)value).ToString(format, _provider); // constrained call avoiding boxing for value types + s = formattable.ToString(format, _provider); // constrained call avoiding boxing for value types } else { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs index 0fa80dc2600e48..4846f8fe9a6bb7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs @@ -260,7 +260,7 @@ public void AppendFormatted(T value) // if it only implements IFormattable, we come out even: only if it implements both do we // end up paying for an extra interface check. string? s; - if (value is IFormattable) + if (value is IFormattable formattable) { // If the value can format itself directly into our buffer, do so. @@ -276,10 +276,10 @@ public void AppendFormatted(T value) return; } - if (value is ISpanFormattable) + if (value is ISpanFormattable spanFormattable) { int charsWritten; - while (!((ISpanFormattable)value).TryFormat(_chars.Slice(_pos), out charsWritten, default, _provider)) // constrained call avoiding boxing for value types + while (!spanFormattable.TryFormat(_chars.Slice(_pos), out charsWritten, default, _provider)) // constrained call avoiding boxing for value types { Grow(); } @@ -288,7 +288,7 @@ public void AppendFormatted(T value) return; } - s = ((IFormattable)value).ToString(format: null, _provider); // constrained call avoiding boxing for value types + s = formattable.ToString(format: null, _provider); // constrained call avoiding boxing for value types } else { @@ -327,7 +327,7 @@ public void AppendFormatted(T value, string? format) // if it only implements IFormattable, we come out even: only if it implements both do we // end up paying for an extra interface check. string? s; - if (value is IFormattable) + if (value is IFormattable formattable) { // If the value can format itself directly into our buffer, do so. @@ -343,10 +343,10 @@ public void AppendFormatted(T value, string? format) return; } - if (value is ISpanFormattable) + if (value is ISpanFormattable spanFormattable) { int charsWritten; - while (!((ISpanFormattable)value).TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) // constrained call avoiding boxing for value types + while (!spanFormattable.TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) // constrained call avoiding boxing for value types { Grow(); } @@ -355,7 +355,7 @@ public void AppendFormatted(T value, string? format) return; } - s = ((IFormattable)value).ToString(format, _provider); // constrained call avoiding boxing for value types + s = formattable.ToString(format, _provider); // constrained call avoiding boxing for value types } else { diff --git a/src/libraries/System.Private.CoreLib/src/System/SByte.cs b/src/libraries/System.Private.CoreLib/src/System/SByte.cs index 48411fe9e54f94..9056d65c1e5465 100644 --- a/src/libraries/System.Private.CoreLib/src/System/SByte.cs +++ b/src/libraries/System.Private.CoreLib/src/System/SByte.cs @@ -62,11 +62,11 @@ public int CompareTo(object? obj) { return 1; } - if (!(obj is sbyte)) + if (obj is not sbyte sb) { throw new ArgumentException(SR.Arg_MustBeSByte); } - return m_value - ((sbyte)obj).m_value; + return m_value - sb.m_value; } public int CompareTo(sbyte value) @@ -77,11 +77,11 @@ public int CompareTo(sbyte value) // Determines whether two Byte objects are equal. public override bool Equals([NotNullWhen(true)] object? obj) { - if (!(obj is sbyte)) + if (obj is not sbyte sb) { return false; } - return m_value == ((sbyte)obj).m_value; + return m_value == sb.m_value; } [NonVersionable] diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs index 5787996513129a..f8a7070114940f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs @@ -3032,7 +3032,7 @@ public void AppendFormatted(T value) return; } - if (value is IFormattable) + if (value is IFormattable formattable) { // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter // requires the former. For value types, it won't matter as the type checks devolve into @@ -3053,10 +3053,10 @@ public void AppendFormatted(T value) AppendFormattedWithTempSpace(value, 0, format: null); } } - else if (value is ISpanFormattable) + else if (value is ISpanFormattable spanFormattable) { Span destination = _stringBuilder.RemainingCurrentChunk; - if (((ISpanFormattable)value).TryFormat(destination, out int charsWritten, default, _provider)) // constrained call avoiding boxing for value types + if (spanFormattable.TryFormat(destination, out int charsWritten, default, _provider)) // constrained call avoiding boxing for value types { if ((uint)charsWritten > (uint)destination.Length) { @@ -3076,7 +3076,7 @@ public void AppendFormatted(T value) } else { - _stringBuilder.Append(((IFormattable)value).ToString(format: null, _provider)); // constrained call avoiding boxing for value types + _stringBuilder.Append(formattable.ToString(format: null, _provider)); // constrained call avoiding boxing for value types } } else @@ -3103,7 +3103,7 @@ public void AppendFormatted(T value, string? format) return; } - if (value is IFormattable) + if (value is IFormattable formattable) { // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter // requires the former. For value types, it won't matter as the type checks devolve into @@ -3124,10 +3124,10 @@ public void AppendFormatted(T value, string? format) AppendFormattedWithTempSpace(value, 0, format); } } - else if (value is ISpanFormattable) + else if (value is ISpanFormattable spanFormattable) { Span destination = _stringBuilder.RemainingCurrentChunk; - if (((ISpanFormattable)value).TryFormat(destination, out int charsWritten, format, _provider)) // constrained call avoiding boxing for value types + if (spanFormattable.TryFormat(destination, out int charsWritten, format, _provider)) // constrained call avoiding boxing for value types { if ((uint)charsWritten > (uint)destination.Length) { @@ -3147,7 +3147,7 @@ public void AppendFormatted(T value, string? format) } else { - _stringBuilder.Append(((IFormattable)value).ToString(format, _provider)); // constrained call avoiding boxing for value types + _stringBuilder.Append(formattable.ToString(format, _provider)); // constrained call avoiding boxing for value types } } else diff --git a/src/libraries/System.Private.CoreLib/src/System/UInt16.cs b/src/libraries/System.Private.CoreLib/src/System/UInt16.cs index e6cf2e20b51427..55e4c31d2c2540 100644 --- a/src/libraries/System.Private.CoreLib/src/System/UInt16.cs +++ b/src/libraries/System.Private.CoreLib/src/System/UInt16.cs @@ -56,9 +56,9 @@ public int CompareTo(object? value) { return 1; } - if (value is ushort) + if (value is ushort num) { - return (int)m_value - (int)(((ushort)value).m_value); + return (int)m_value - (int)(num.m_value); } throw new ArgumentException(SR.Arg_MustBeUInt16); } @@ -70,11 +70,11 @@ public int CompareTo(ushort value) public override bool Equals([NotNullWhen(true)] object? obj) { - if (!(obj is ushort)) + if (obj is not ushort num) { return false; } - return m_value == ((ushort)obj).m_value; + return m_value == num.m_value; } [NonVersionable] diff --git a/src/libraries/System.Private.CoreLib/src/System/UInt32.cs b/src/libraries/System.Private.CoreLib/src/System/UInt32.cs index f8df052f77ebb0..de27ae39f95a57 100644 --- a/src/libraries/System.Private.CoreLib/src/System/UInt32.cs +++ b/src/libraries/System.Private.CoreLib/src/System/UInt32.cs @@ -86,11 +86,11 @@ public int CompareTo(uint value) public override bool Equals([NotNullWhen(true)] object? obj) { - if (!(obj is uint)) + if (obj is not uint num) { return false; } - return m_value == ((uint)obj).m_value; + return m_value == num.m_value; } [NonVersionable] diff --git a/src/libraries/System.Private.CoreLib/src/System/UInt64.cs b/src/libraries/System.Private.CoreLib/src/System/UInt64.cs index b19deea580a6ea..ff0909ef8d11f5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/UInt64.cs +++ b/src/libraries/System.Private.CoreLib/src/System/UInt64.cs @@ -86,11 +86,11 @@ public int CompareTo(ulong value) public override bool Equals([NotNullWhen(true)] object? obj) { - if (!(obj is ulong)) + if (obj is not ulong num) { return false; } - return m_value == ((ulong)obj).m_value; + return m_value == num.m_value; } [NonVersionable] diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs index 9c5a0dd96a2277..903ccff957f020 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs @@ -849,7 +849,7 @@ private void ImportDataMembers() if (getMethod.GetParameters().Length > 0) ThrowInvalidDataContractException(SR.Format(SR.IndexedPropertyCannotBeSerialized, property.DeclaringType, property.Name)); } - else if (!(member is FieldInfo)) + else if (member is not FieldInfo) ThrowInvalidDataContractException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(type), member.Name)); DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0]; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExceptionUtility.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExceptionUtility.cs index 438a54589a09ac..411b2e198c5d52 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExceptionUtility.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExceptionUtility.cs @@ -13,7 +13,7 @@ public static bool IsFatal(Exception exception) while (exception != null) { // NetFx checked for FatalException and FatalInternalException as well, which were ServiceModel constructs. - if ((exception is OutOfMemoryException && !(exception is InsufficientMemoryException)) || + if ((exception is OutOfMemoryException && exception is not InsufficientMemoryException) || exception is ThreadAbortException) { return true; @@ -27,12 +27,12 @@ public static bool IsFatal(Exception exception) { exception = exception.InnerException!; } - else if (exception is AggregateException) + else if (exception is AggregateException aggregateException) { // AggregateExceptions have a collection of inner exceptions, which may themselves be other // wrapping exceptions (including nested AggregateExceptions). Recursively walk this // hierarchy. The (singular) InnerException is included in the collection. - var innerExceptions = ((AggregateException)exception).InnerExceptions; + var innerExceptions = aggregateException.InnerExceptions; foreach (Exception innerException in innerExceptions) { if (IsFatal(innerException)) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs index ad0d50f9c0311e..0ec4348e1e3b30 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs @@ -70,7 +70,7 @@ internal ExtensionDataReader(XmlObjectSerializerReadContext context) internal void SetDeserializedValue(object? obj) { IDataNode? deserializedDataNode = (_deserializedDataNodes == null || _deserializedDataNodes.Count == 0) ? null : _deserializedDataNodes.Dequeue(); - if (deserializedDataNode != null && !(obj is IDataNode)) + if (deserializedDataNode != null && obj is not IDataNode) { deserializedDataNode.Value = obj; deserializedDataNode.IsFinalValue = true; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs index 25654871992db8..29ee1016e711e2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs @@ -299,7 +299,7 @@ private void AddCollectionItemContractsToKnownDataContracts() _knownDataContracts.TryAdd(itemDataContract.XmlName, itemDataContract); } - if (!(itemContract is CollectionDataContract)) + if (itemContract is not CollectionDataContract) { break; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs index 8679c524c10fce..fe74b1832bb4d7 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs @@ -1033,13 +1033,13 @@ public override void WriteValue(object value) ThrowClosed(); } - if (value is Array) + if (value is Array array) { - WriteValue((Array)value); + WriteValue(array); } - else if (value is IStreamProvider) + else if (value is IStreamProvider streamProvider) { - WriteValue((IStreamProvider)value); + WriteValue(streamProvider); } else { @@ -1375,57 +1375,57 @@ private void WritePrimitiveValue(object value) ThrowClosed(); } - if (value is ulong) + if (value is ulong num3) { - WriteValue((ulong)value); + WriteValue(num3); } - else if (value is string) + else if (value is string str) { - WriteValue((string)value); + WriteValue(str); } - else if (value is int) + else if (value is int num2) { - WriteValue((int)value); + WriteValue(num2); } - else if (value is long) + else if (value is long num) { - WriteValue((long)value); + WriteValue(num); } - else if (value is bool) + else if (value is bool b) { - WriteValue((bool)value); + WriteValue(b); } - else if (value is double) + else if (value is double d2) { - WriteValue((double)value); + WriteValue(d2); } - else if (value is DateTime) + else if (value is DateTime dateTime) { - WriteValue((DateTime)value); + WriteValue(dateTime); } - else if (value is float) + else if (value is float f) { - WriteValue((float)value); + WriteValue(f); } - else if (value is decimal) + else if (value is decimal d) { - WriteValue((decimal)value); + WriteValue(d); } - else if (value is XmlDictionaryString) + else if (value is XmlDictionaryString xmlDictionaryString) { - WriteValue((XmlDictionaryString)value); + WriteValue(xmlDictionaryString); } - else if (value is UniqueId) + else if (value is UniqueId uniqueId) { - WriteValue((UniqueId)value); + WriteValue(uniqueId); } - else if (value is Guid) + else if (value is Guid guid) { - WriteValue((Guid)value); + WriteValue(guid); } - else if (value is TimeSpan) + else if (value is TimeSpan timeSpan) { - WriteValue((TimeSpan)value); + WriteValue(timeSpan); } else if (value.GetType().IsArray) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs index 86a826e88108d3..9324be32bdc5fa 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs @@ -79,8 +79,8 @@ private void ExportDataContract(DataContract dataContract) { if (dataContract.IsBuiltInDataContract) return; - else if (dataContract is XmlDataContract) - ExportXmlDataContract((XmlDataContract)dataContract); + else if (dataContract is XmlDataContract xmlDataContract) + ExportXmlDataContract(xmlDataContract); else { XmlSchema schema = GetSchema(dataContract.XmlName.Namespace); @@ -92,10 +92,10 @@ private void ExportDataContract(DataContract dataContract) else ExportClassDataContract(classDataContract, schema); } - else if (dataContract is CollectionDataContract) - ExportCollectionDataContract((CollectionDataContract)dataContract, schema); - else if (dataContract is EnumDataContract) - ExportEnumDataContract((EnumDataContract)dataContract, schema); + else if (dataContract is CollectionDataContract collectionDataContract) + ExportCollectionDataContract(collectionDataContract, schema); + else if (dataContract is EnumDataContract enumDataContract) + ExportEnumDataContract(enumDataContract, schema); ExportTopLevelElement(dataContract, schema); Schemas.Reprocess(schema); } @@ -561,15 +561,15 @@ private static void ReprocessAll(XmlSchemaSet schemas)// and remove duplicate it XmlSchemaObject item = itemArray[j]; Hashtable items; XmlQualifiedName qname; - if (item is XmlSchemaElement) + if (item is XmlSchemaElement xmlSchemaElement) { items = elements; - qname = new XmlQualifiedName(((XmlSchemaElement)item).Name, schema.TargetNamespace); + qname = new XmlQualifiedName(xmlSchemaElement.Name, schema.TargetNamespace); } - else if (item is XmlSchemaType) + else if (item is XmlSchemaType xmlSchemaType) { items = types; - qname = new XmlQualifiedName(((XmlSchemaType)item).Name, schema.TargetNamespace); + qname = new XmlQualifiedName(xmlSchemaType.Name, schema.TargetNamespace); } else continue; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs index e42b4287766ef0..9d74525e9f4909 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs @@ -158,9 +158,9 @@ internal static void AddSchemaImport(string ns, XmlSchema schema) foreach (object item in schema.Includes) { - if (item is XmlSchemaImport) + if (item is XmlSchemaImport xmlSchemaImport) { - if (SchemaHelper.NamespacesEqual(ns, ((XmlSchemaImport)item).Namespace)) + if (SchemaHelper.NamespacesEqual(ns, xmlSchemaImport.Namespace)) return; } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaImporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaImporter.cs index 9a8ad5349164d6..891e1fb6870732 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaImporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaImporter.cs @@ -425,8 +425,8 @@ private DataContract ImportType(XmlSchemaType type, XmlQualifiedName typeName, b XmlSchemaSimpleTypeContent? content = simpleType.Content; if (content is XmlSchemaSimpleTypeUnion) ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.SimpleTypeUnionNotSupported); - else if (content is XmlSchemaSimpleTypeList) - dataContract = ImportFlagsEnum(typeName, (XmlSchemaSimpleTypeList)content, simpleType.Annotation); + else if (content is XmlSchemaSimpleTypeList xmlSchemaSimpleTypeList) + dataContract = ImportFlagsEnum(typeName, xmlSchemaSimpleTypeList, simpleType.Annotation); else if (content is XmlSchemaSimpleTypeRestriction restriction) { if (CheckIfEnum(restriction)) @@ -853,7 +853,7 @@ private static void CheckISerializableBase(XmlQualifiedName typeName, XmlSchemaS ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.ISerializableContainsMoreThanOneItems); XmlSchemaObject o = rootSequence.Items[0]; - if (!(o is XmlSchemaAny)) + if (o is not XmlSchemaAny) ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.ISerializableDoesNotContainAny); XmlSchemaAny wildcard = (XmlSchemaAny)o; @@ -874,9 +874,9 @@ private static void CheckISerializableBase(XmlQualifiedName typeName, XmlSchemaS for (int i = 0; i < attributes.Count; i++) { o = attributes[i]; - if (o is XmlSchemaAttribute) + if (o is XmlSchemaAttribute xmlSchemaAttribute) { - if (((XmlSchemaAttribute)o).RefName == factoryTypeAttributeRefName) + if (xmlSchemaAttribute.RefName == factoryTypeAttributeRefName) { containsFactoryTypeAttribute = true; break; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs index 63c7d049bfecbb..cd79e9e16c5ad6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs @@ -60,9 +60,9 @@ public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pa [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static DataContract ProcessDataContract(DataContract contract, ExportContext context, MemberInfo memberNode) { - if (contract is ClassDataContract) + if (contract is ClassDataContract classDataContract) { - return ProcessClassDataContract((ClassDataContract)contract, context, memberNode); + return ProcessClassDataContract(classDataContract, context, memberNode); } throw XmlObjectSerializer.CreateSerializationException(SR.QueryGeneratorPathToMemberNotFound); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs index aa67d42b32f239..fb33a9cfa1133f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs @@ -679,9 +679,9 @@ private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); } } - else if (dataContract is EnumDataContract) + else if (dataContract is EnumDataContract enumDataContract) { - dataNode = new DataNode(((EnumDataContract)dataContract).ReadEnumValue(xmlReader)); + dataNode = new DataNode(enumDataContract.ReadEnumValue(xmlReader)); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); } else if (dataContract is ClassDataContract) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs index a5536358e37242..2d1f59da45776f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs @@ -1145,17 +1145,17 @@ public override void WriteValue(object value) ArgumentNullException.ThrowIfNull(value); - if (value is object[]) + if (value is object[] objects) { - WriteValue((object[])value); + WriteValue(objects); } - else if (value is Array) + else if (value is Array array) { - WriteValue((Array)value); + WriteValue(array); } - else if (value is IStreamProvider) + else if (value is IStreamProvider streamProvider) { - WriteValue((IStreamProvider)value); + WriteValue(streamProvider); } else { @@ -1170,57 +1170,57 @@ protected void WritePrimitiveValue(object value) ArgumentNullException.ThrowIfNull(value); - if (value is ulong) + if (value is ulong num3) { - WriteValue((ulong)value); + WriteValue(num3); } - else if (value is string) + else if (value is string str) { - WriteValue((string)value); + WriteValue(str); } - else if (value is int) + else if (value is int num2) { - WriteValue((int)value); + WriteValue(num2); } - else if (value is long) + else if (value is long num) { - WriteValue((long)value); + WriteValue(num); } - else if (value is bool) + else if (value is bool b) { - WriteValue((bool)value); + WriteValue(b); } - else if (value is double) + else if (value is double d2) { - WriteValue((double)value); + WriteValue(d2); } - else if (value is DateTime) + else if (value is DateTime dateTime) { - WriteValue((DateTime)value); + WriteValue(dateTime); } - else if (value is float) + else if (value is float f) { - WriteValue((float)value); + WriteValue(f); } - else if (value is decimal) + else if (value is decimal d) { - WriteValue((decimal)value); + WriteValue(d); } - else if (value is XmlDictionaryString) + else if (value is XmlDictionaryString xmlDictionaryString) { - WriteValue((XmlDictionaryString)value); + WriteValue(xmlDictionaryString); } - else if (value is UniqueId) + else if (value is UniqueId uniqueId) { - WriteValue((UniqueId)value); + WriteValue(uniqueId); } - else if (value is Guid) + else if (value is Guid guid) { - WriteValue((Guid)value); + WriteValue(guid); } - else if (value is TimeSpan) + else if (value is TimeSpan timeSpan) { - WriteValue((TimeSpan)value); + WriteValue(timeSpan); } else if (value.GetType().IsArray) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs index 0f2c9162a850e1..e219c6e9b4c1a9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs @@ -401,28 +401,28 @@ public static string ToString(DateTime value) private static string ToString(object value) { - if (value is int) - return ToString((int)value); - else if (value is long) - return ToString((long)value); - else if (value is float) - return ToString((float)value); - else if (value is double) - return ToString((double)value); - else if (value is decimal) - return ToString((decimal)value); - else if (value is TimeSpan) - return ToString((TimeSpan)value); - else if (value is UniqueId) - return ToString((UniqueId)value); - else if (value is Guid) - return ToString((Guid)value); - else if (value is ulong) - return ToString((ulong)value); - else if (value is DateTime) - return ToString((DateTime)value); - else if (value is bool) - return ToString((bool)value); + if (value is int num3) + return ToString(num3); + else if (value is long num2) + return ToString(num2); + else if (value is float f) + return ToString(f); + else if (value is double d2) + return ToString(d2); + else if (value is decimal d) + return ToString(d); + else if (value is TimeSpan timeSpan) + return ToString(timeSpan); + else if (value is UniqueId uniqueId) + return ToString(uniqueId); + else if (value is Guid guid) + return ToString(guid); + else if (value is ulong num) + return ToString(num); + else if (value is DateTime dateTime) + return ToString(dateTime); + else if (value is bool b) + return ToString(b); else return value.ToString()!; // value can only be an object created by ToList() } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs index 8b21982599f04b..1d1b4db7f32956 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs @@ -570,7 +570,7 @@ internal void AddString(string s) { ConvertTextToNode(); XText? tn = content as XText; - if (tn != null && !(tn is XCData)) + if (tn != null && tn is not XCData) { tn.Value += s; } @@ -598,7 +598,7 @@ internal void AddStringSkipNotify(string s) else { XText? tn = content as XText; - if (tn != null && !(tn is XCData)) + if (tn != null && tn is not XCData) { tn.text += s; } @@ -1369,7 +1369,7 @@ private static void AddContentToList(List list, object? content) [return: NotNullIfNotNull(nameof(content))] internal static object? GetContentSnapshot(object? content) { - if (content is string || !(content is IEnumerable)) return content; + if (content is string || content is not IEnumerable) return content; List list = new List(); AddContentToList(list, content); return list; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs index a5b7cc8c416124..ad9f41da6441bd 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs @@ -61,7 +61,7 @@ public void Add(object? content) else if (_text.Length > 0) { XText? prevXText = _previous as XText; - if (prevXText != null && !(_previous is XCData)) + if (prevXText != null && _previous is not XCData) { prevXText.Value += _text; } @@ -130,7 +130,7 @@ private void AddNode(XNode n) if (_text.Length > 0) { XText? prevXText = _previous as XText; - if (prevXText != null && !(_previous is XCData)) + if (prevXText != null && _previous is not XCData) { prevXText.Value += _text; } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs index 5bd9d3f1a2a8ae..99a36444677b90 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs @@ -309,7 +309,7 @@ public void RemoveAnnotations() where T : class { object? obj = a[i]; if (obj == null) break; - if (!(obj is T)) a[j++] = obj; + if (obj is not T) a[j++] = obj; i++; } if (j == 0) diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs index e994a489678d4c..3068ecd5518b81 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs @@ -872,8 +872,8 @@ public static object Evaluate(XNode node, string expression, IXmlNamespaceRes { return EvaluateIterator(iterator); } - if (!(result is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, result.GetType())); - return (T)result; + if (result is not T t) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, result.GetType())); + return t; } private static IEnumerable EvaluateIterator(XPathNodeIterator result) @@ -882,8 +882,8 @@ private static IEnumerable EvaluateIterator(XPathNodeIterator result) { Debug.Assert(navigator.UnderlyingObject != null); object r = navigator.UnderlyingObject; - if (!(r is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, r.GetType())); - yield return (T)r; + if (r is not T t2) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, r.GetType())); + yield return t2; XText? t = r as XText; if (t != null && t.GetParent() != null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs index 3a1764e5b2c3fd..84b8d1b3c0f70a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs @@ -33,15 +33,15 @@ public static XmlAsyncCheckReader CreateAsyncCheckWrapper(XmlReader reader) } return new XmlAsyncCheckReaderWithLineInfoNS(reader); } - Debug.Assert(!(reader is IXmlSchemaInfo)); + Debug.Assert(reader is not IXmlSchemaInfo); return new XmlAsyncCheckReaderWithLineInfo(reader); } else if (reader is IXmlNamespaceResolver) { - Debug.Assert(!(reader is IXmlSchemaInfo)); + Debug.Assert(reader is not IXmlSchemaInfo); return new XmlAsyncCheckReaderWithNS(reader); } - Debug.Assert(!(reader is IXmlSchemaInfo)); + Debug.Assert(reader is not IXmlSchemaInfo); return new XmlAsyncCheckReader(reader); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs index 89c814b2a27b9e..f6c88af12537ae 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs @@ -1990,7 +1990,7 @@ internal bool Namespaces } else { - if (!(_namespaceManager is NoNamespaceManager)) + if (_namespaceManager is not NoNamespaceManager) { _namespaceManager = new NoNamespaceManager(); } @@ -3670,7 +3670,7 @@ private bool ParseXmlDeclaration(bool isTextDecl) Debug.Assert(_ps.encoding != null); string encodingName = _ps.encoding.WebName; if (encodingName != "utf-8" && encodingName != "utf-16" && - encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding)) + encodingName != "utf-16BE" && _ps.encoding is not Ucs4Encoding) { Throw(SR.Xml_EncodingSwitchAfterResetState, (_ps.encoding.GetByteCount("A") == 1) ? "UTF-8" : "UTF-16"); } @@ -3888,7 +3888,7 @@ private bool ParseXmlDeclaration(bool isTextDecl) Debug.Assert(_ps.encoding != null); string encodingName = _ps.encoding.WebName; if (encodingName != "utf-8" && encodingName != "utf-16" && - encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding)) + encodingName != "utf-16BE" && _ps.encoding is not Ucs4Encoding) { Throw(SR.Xml_EncodingSwitchAfterResetState, (_ps.encoding.GetByteCount("A") == 1) ? "UTF-8" : "UTF-16"); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs index 8edafd8e7ef408..21d9c84581fc3e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs @@ -1237,7 +1237,7 @@ private async Task ParseXmlDeclarationAsync(bool isTextDecl) // check for invalid encoding switches to default encoding string encodingName = _ps.encoding!.WebName; if (encodingName != "utf-8" && encodingName != "utf-16" && - encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding)) + encodingName != "utf-16BE" && _ps.encoding is not Ucs4Encoding) { Throw(SR.Xml_EncodingSwitchAfterResetState, (_ps.encoding.GetByteCount("A") == 1) ? "UTF-8" : "UTF-16"); } @@ -1450,7 +1450,7 @@ private async Task ParseXmlDeclarationAsync(bool isTextDecl) // check for invalid encoding switches to default encoding string encodingName = _ps.encoding!.WebName; if (encodingName != "utf-8" && encodingName != "utf-16" && - encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding)) + encodingName != "utf-16BE" && _ps.encoding is not Ucs4Encoding) { Throw(SR.Xml_EncodingSwitchAfterResetState, (_ps.encoding.GetByteCount("A") == 1) ? "UTF-8" : "UTF-16"); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs index 5304c6b6b2e4c0..d317cef3a2e4be 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs @@ -117,13 +117,13 @@ internal int FindNodeOffsetNS(XmlAttribute node) if (node == null) return null; - if (!(node is XmlAttribute)) + if (node is not XmlAttribute xmlAttribute) throw new ArgumentException(SR.Xdom_AttrCol_Object); int offset = FindNodeOffset(node.LocalName, node.NamespaceURI); if (offset == -1) { - return InternalAppendAttribute((XmlAttribute)node); + return InternalAppendAttribute(xmlAttribute); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs index 79bbbc75d0e7a2..ee3eab6c3403e6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs @@ -288,7 +288,7 @@ internal bool IsConnected() return first; } - if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) + if (newChild is not XmlLinkedNode || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); XmlLinkedNode newNode = (XmlLinkedNode)newChild; @@ -403,7 +403,7 @@ internal bool IsConnected() return first; } - if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) + if (newChild is not XmlLinkedNode || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); XmlLinkedNode newNode = (XmlLinkedNode)newChild; @@ -608,7 +608,7 @@ public virtual XmlNode RemoveChild(XmlNode oldChild) return first; } - if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType)) + if (newChild is not XmlLinkedNode || !IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs index eabeb1e5a92424..940e4f16bbcb92 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs @@ -498,10 +498,10 @@ public override void ConstructPos(BitSet firstpos, BitSet lastpos, BitSet[] foll { SequenceNode this_ = context.this_; context.lastposLeft = new BitSet(lastpos.Count); - if (this_.LeftChild is SequenceNode) + if (this_.LeftChild is SequenceNode sequenceNode) { contextStack.Push(context); - context = new SequenceConstructPosContext((SequenceNode)this_.LeftChild, context.firstpos, context.lastposLeft); + context = new SequenceConstructPosContext(sequenceNode, context.firstpos, context.lastposLeft); continue; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs index ece91ebee076cd..69b78fd5096b6c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs @@ -712,7 +712,7 @@ private void Preprocess(XmlSchema schema, string? targetNamespace, ArrayList imp { for (int j = 0; j < redefine.Items.Count; ++j) { - if (!(redefine.Items[j] is XmlSchemaAnnotation)) + if (redefine.Items[j] is not XmlSchemaAnnotation) { SendValidationEvent(SR.Sch_RedefineNoSchema, redefine); break; @@ -1110,12 +1110,12 @@ private void CheckRefinedComplexType(XmlSchemaComplexType ctype) if (ctype.ContentModel != null) { XmlQualifiedName? baseName; - if (ctype.ContentModel is XmlSchemaComplexContent) + if (ctype.ContentModel is XmlSchemaComplexContent xmlSchemaComplexContent) { - XmlSchemaComplexContent content = (XmlSchemaComplexContent)ctype.ContentModel; - if (content.Content is XmlSchemaComplexContentRestriction) + XmlSchemaComplexContent content = xmlSchemaComplexContent; + if (content.Content is XmlSchemaComplexContentRestriction xmlSchemaComplexContentRestriction) { - baseName = ((XmlSchemaComplexContentRestriction)content.Content).BaseTypeName; + baseName = xmlSchemaComplexContentRestriction.BaseTypeName; } else { @@ -1125,9 +1125,9 @@ private void CheckRefinedComplexType(XmlSchemaComplexType ctype) else { XmlSchemaSimpleContent content = (XmlSchemaSimpleContent)ctype.ContentModel; - if (content.Content is XmlSchemaSimpleContentRestriction) + if (content.Content is XmlSchemaSimpleContentRestriction xmlSchemaSimpleContentRestriction) { - baseName = ((XmlSchemaSimpleContentRestriction)content.Content).BaseTypeName; + baseName = xmlSchemaSimpleContentRestriction.BaseTypeName; } else { @@ -1405,9 +1405,9 @@ private void PreprocessElementContent(XmlSchemaElement element) { SendValidationEvent(SR.Sch_TypeMutualExclusive, element); } - if (element.SchemaType is XmlSchemaComplexType) + if (element.SchemaType is XmlSchemaComplexType xmlSchemaComplexType) { - PreprocessComplexType((XmlSchemaComplexType)element.SchemaType, true); + PreprocessComplexType(xmlSchemaComplexType, true); } else { @@ -1702,9 +1702,9 @@ private void PreprocessComplexType(XmlSchemaComplexType complexType, bool local) // "complexType.Particle != null || complexType.Attributes != null" is illegal - if (complexType.ContentModel is XmlSchemaSimpleContent) + if (complexType.ContentModel is XmlSchemaSimpleContent xmlSchemaSimpleContent) { - XmlSchemaSimpleContent content = (XmlSchemaSimpleContent)complexType.ContentModel; + XmlSchemaSimpleContent content = xmlSchemaSimpleContent; if (content.Content == null) { if (complexType.QualifiedName == XmlQualifiedName.Empty) @@ -1905,7 +1905,7 @@ private void PreprocessNotation(XmlSchemaNotation notation) private void PreprocessParticle(XmlSchemaParticle particle) { XmlSchemaObjectCollection items; - if (particle is XmlSchemaAll) + if (particle is XmlSchemaAll xmlSchemaAll) { if (particle.MinOccurs != decimal.Zero && particle.MinOccurs != decimal.One) { @@ -1917,7 +1917,7 @@ private void PreprocessParticle(XmlSchemaParticle particle) particle.MaxOccurs = decimal.One; SendValidationEvent(SR.Sch_InvalidAllMax, particle); } - items = ((XmlSchemaAll)particle).Items; + items = xmlSchemaAll.Items; for (int i = 0; i < items.Count; ++i) { XmlSchemaElement element = (XmlSchemaElement)items[i]; @@ -1937,9 +1937,9 @@ private void PreprocessParticle(XmlSchemaParticle particle) particle.MinOccurs = particle.MaxOccurs; SendValidationEvent(SR.Sch_MinGtMax, particle); } - if (particle is XmlSchemaChoice) + if (particle is XmlSchemaChoice xmlSchemaChoice) { - items = ((XmlSchemaChoice)particle).Items; + items = xmlSchemaChoice.Items; for (int i = 0; i < items.Count; ++i) { SetParent(items[i], particle); @@ -1954,9 +1954,9 @@ private void PreprocessParticle(XmlSchemaParticle particle) } } } - else if (particle is XmlSchemaSequence) + else if (particle is XmlSchemaSequence xmlSchemaSequence) { - items = ((XmlSchemaSequence)particle).Items; + items = xmlSchemaSequence.Items; for (int i = 0; i < items.Count; ++i) { SetParent(items[i], particle); @@ -1982,11 +1982,11 @@ private void PreprocessParticle(XmlSchemaParticle particle) ValidateQNameAttribute(groupRef, "ref", groupRef.RefName); } } - else if (particle is XmlSchemaAny) + else if (particle is XmlSchemaAny xmlSchemaAny) { try { - ((XmlSchemaAny)particle).BuildNamespaceList(_targetNamespace!); + xmlSchemaAny.BuildNamespaceList(_targetNamespace!); } catch (FormatException fe) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs index b5e129c68f6fe8..757bfcc3d3847a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs @@ -71,9 +71,9 @@ private void Cleanup() foreach (XmlSchemaType? type in _schema.SchemaTypes.Values) { - if (type is XmlSchemaComplexType) + if (type is XmlSchemaComplexType xmlSchemaComplexType) { - CleanupComplexType((XmlSchemaComplexType)type); + CleanupComplexType(xmlSchemaComplexType); } else { @@ -213,9 +213,9 @@ private void Compile() foreach (XmlSchemaType? type in _schema.SchemaTypes.Values) { - if (type is XmlSchemaComplexType) + if (type is XmlSchemaComplexType xmlSchemaComplexType) { - CompileComplexType((XmlSchemaComplexType)type); + CompileComplexType(xmlSchemaComplexType); } else { @@ -254,9 +254,9 @@ private void Compile() foreach (XmlSchemaType? type in _schema.SchemaTypes.Values) { - if (type is XmlSchemaComplexType) + if (type is XmlSchemaComplexType xmlSchemaComplexType2) { - CheckParticleDerivation((XmlSchemaComplexType)type); + CheckParticleDerivation(xmlSchemaComplexType2); } } @@ -416,13 +416,13 @@ private static void CleanupGroup(XmlSchemaGroup group) private static void CleanupParticle(XmlSchemaParticle particle) { - if (particle is XmlSchemaElement) + if (particle is XmlSchemaElement xmlSchemaElement) { - CleanupElement((XmlSchemaElement)particle); + CleanupElement(xmlSchemaElement); } - else if (particle is XmlSchemaGroupBase) + else if (particle is XmlSchemaGroupBase xmlSchemaGroupBase) { - XmlSchemaObjectCollection particles = ((XmlSchemaGroupBase)particle).Items; + XmlSchemaObjectCollection particles = xmlSchemaGroupBase.Items; for (int i = 0; i < particles.Count; ++i) { CleanupParticle((XmlSchemaParticle)particles[i]); @@ -718,9 +718,9 @@ private void CompileComplexType(XmlSchemaComplexType complexType) if (complexType.ContentModel is XmlSchemaSimpleContent simpleContent) { complexType.SetContentType(XmlSchemaContentType.TextOnly); - if (simpleContent.Content is XmlSchemaSimpleContentExtension) + if (simpleContent.Content is XmlSchemaSimpleContentExtension xmlSchemaSimpleContentExtension) { - CompileSimpleContentExtension(complexType, (XmlSchemaSimpleContentExtension)simpleContent.Content); + CompileSimpleContentExtension(complexType, xmlSchemaSimpleContentExtension); } else { //simpleContent.Content is XmlSchemaSimpleContentRestriction @@ -730,9 +730,9 @@ private void CompileComplexType(XmlSchemaComplexType complexType) else { // complexType.ContentModel is XmlSchemaComplexContent XmlSchemaComplexContent complexContent = (XmlSchemaComplexContent)complexType.ContentModel; - if (complexContent.Content is XmlSchemaComplexContentExtension) + if (complexContent.Content is XmlSchemaComplexContentExtension xmlSchemaComplexContentExtension) { - CompileComplexContentExtension(complexType, complexContent, (XmlSchemaComplexContentExtension)complexContent.Content); + CompileComplexContentExtension(complexType, complexContent, xmlSchemaComplexContentExtension); } else { // complexContent.Content is XmlSchemaComplexContentRestriction @@ -1071,25 +1071,25 @@ private XmlSchemaParticle CanonicalizeParticle(XmlSchemaParticle? particle, bool { return XmlSchemaParticle.Empty; } - else if (particle is XmlSchemaElement) + else if (particle is XmlSchemaElement xmlSchemaElement) { - return CanonicalizeElement((XmlSchemaElement)particle, substitution); + return CanonicalizeElement(xmlSchemaElement, substitution); } - else if (particle is XmlSchemaGroupRef) + else if (particle is XmlSchemaGroupRef xmlSchemaGroupRef) { - return CanonicalizeGroupRef((XmlSchemaGroupRef)particle, root); + return CanonicalizeGroupRef(xmlSchemaGroupRef, root); } - else if (particle is XmlSchemaAll) + else if (particle is XmlSchemaAll xmlSchemaAll) { - return CanonicalizeAll((XmlSchemaAll)particle, root, substitution); + return CanonicalizeAll(xmlSchemaAll, root, substitution); } - else if (particle is XmlSchemaChoice) + else if (particle is XmlSchemaChoice xmlSchemaChoice) { - return CanonicalizeChoice((XmlSchemaChoice)particle, root, substitution); + return CanonicalizeChoice(xmlSchemaChoice, root, substitution); } - else if (particle is XmlSchemaSequence) + else if (particle is XmlSchemaSequence xmlSchemaSequence) { - return CanonicalizeSequence((XmlSchemaSequence)particle, root, substitution); + return CanonicalizeSequence(xmlSchemaSequence, root, substitution); } else { @@ -1331,67 +1331,67 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart { return false; } - if (baseParticle is XmlSchemaElement) + if (baseParticle is XmlSchemaElement xmlSchemaElement6) { - if (derivedParticle is XmlSchemaElement) + if (derivedParticle is XmlSchemaElement xmlSchemaElement) { - return IsElementFromElement((XmlSchemaElement)derivedParticle, (XmlSchemaElement)baseParticle); + return IsElementFromElement(xmlSchemaElement, xmlSchemaElement6); } else { return false; } } - else if (baseParticle is XmlSchemaAny) + else if (baseParticle is XmlSchemaAny xmlSchemaAny2) { - if (derivedParticle is XmlSchemaElement) + if (derivedParticle is XmlSchemaElement xmlSchemaElement2) { - return IsElementFromAny((XmlSchemaElement)derivedParticle, (XmlSchemaAny)baseParticle); + return IsElementFromAny(xmlSchemaElement2, xmlSchemaAny2); } - else if (derivedParticle is XmlSchemaAny) + else if (derivedParticle is XmlSchemaAny xmlSchemaAny) { - return IsAnyFromAny((XmlSchemaAny)derivedParticle, (XmlSchemaAny)baseParticle); + return IsAnyFromAny(xmlSchemaAny, xmlSchemaAny2); } else { - return IsGroupBaseFromAny((XmlSchemaGroupBase)derivedParticle, (XmlSchemaAny)baseParticle); + return IsGroupBaseFromAny((XmlSchemaGroupBase)derivedParticle, xmlSchemaAny2); } } - else if (baseParticle is XmlSchemaAll) + else if (baseParticle is XmlSchemaAll xmlSchemaAll) { - if (derivedParticle is XmlSchemaElement) + if (derivedParticle is XmlSchemaElement xmlSchemaElement3) { - return IsElementFromGroupBase((XmlSchemaElement)derivedParticle, (XmlSchemaGroupBase)baseParticle, true); + return IsElementFromGroupBase(xmlSchemaElement3, (XmlSchemaGroupBase)baseParticle, true); } else if (derivedParticle is XmlSchemaAll) { return IsGroupBaseFromGroupBase((XmlSchemaGroupBase)derivedParticle, (XmlSchemaGroupBase)baseParticle, true); } - else if (derivedParticle is XmlSchemaSequence) + else if (derivedParticle is XmlSchemaSequence xmlSchemaSequence) { - return IsSequenceFromAll((XmlSchemaSequence)derivedParticle, (XmlSchemaAll)baseParticle); + return IsSequenceFromAll(xmlSchemaSequence, xmlSchemaAll); } } - else if (baseParticle is XmlSchemaChoice) + else if (baseParticle is XmlSchemaChoice xmlSchemaChoice) { - if (derivedParticle is XmlSchemaElement) + if (derivedParticle is XmlSchemaElement xmlSchemaElement4) { - return IsElementFromGroupBase((XmlSchemaElement)derivedParticle, (XmlSchemaGroupBase)baseParticle, false); + return IsElementFromGroupBase(xmlSchemaElement4, (XmlSchemaGroupBase)baseParticle, false); } else if (derivedParticle is XmlSchemaChoice) { return IsGroupBaseFromGroupBase((XmlSchemaGroupBase)derivedParticle, (XmlSchemaGroupBase)baseParticle, false); } - else if (derivedParticle is XmlSchemaSequence) + else if (derivedParticle is XmlSchemaSequence xmlSchemaSequence2) { - return IsSequenceFromChoice((XmlSchemaSequence)derivedParticle, (XmlSchemaChoice)baseParticle); + return IsSequenceFromChoice(xmlSchemaSequence2, xmlSchemaChoice); } } else if (baseParticle is XmlSchemaSequence) { - if (derivedParticle is XmlSchemaElement) + if (derivedParticle is XmlSchemaElement xmlSchemaElement5) { - return IsElementFromGroupBase((XmlSchemaElement)derivedParticle, (XmlSchemaGroupBase)baseParticle, true); + return IsElementFromGroupBase(xmlSchemaElement5, (XmlSchemaGroupBase)baseParticle, true); } else if (derivedParticle is XmlSchemaSequence) { @@ -1619,9 +1619,9 @@ private static void CalculateEffectiveTotalRange(XmlSchemaParticle particle, out minOccurs = particle.MinOccurs; maxOccurs = particle.MaxOccurs; } - else if (particle is XmlSchemaChoice) + else if (particle is XmlSchemaChoice xmlSchemaChoice) { - if (((XmlSchemaChoice)particle).Items.Count == 0) + if (xmlSchemaChoice.Items.Count == 0) { minOccurs = maxOccurs = decimal.Zero; } @@ -1629,7 +1629,7 @@ private static void CalculateEffectiveTotalRange(XmlSchemaParticle particle, out { minOccurs = decimal.MaxValue; maxOccurs = decimal.Zero; - XmlSchemaChoice choice = (XmlSchemaChoice)particle; + XmlSchemaChoice choice = xmlSchemaChoice; for (int i = 0; i < choice.Items.Count; ++i) { decimal min, max; @@ -2133,17 +2133,17 @@ private void CompileIdentityConstraint(XmlSchemaIdentityConstraint xi) { SchemaNamespaceManager xnmgr = new SchemaNamespaceManager(xi); compic = new CompiledIdentityConstraint(xi, xnmgr); - if (xi is XmlSchemaKeyref) + if (xi is XmlSchemaKeyref xmlSchemaKeyref) { - XmlSchemaIdentityConstraint? ic = (XmlSchemaIdentityConstraint?)_schema!.IdentityConstraints[((XmlSchemaKeyref)xi).Refer]; + XmlSchemaIdentityConstraint? ic = (XmlSchemaIdentityConstraint?)_schema!.IdentityConstraints[xmlSchemaKeyref.Refer]; if (ic == null) { - throw new XmlSchemaException(SR.Sch_UndeclaredIdentityConstraint, ((XmlSchemaKeyref)xi).Refer.ToString(), xi); + throw new XmlSchemaException(SR.Sch_UndeclaredIdentityConstraint, xmlSchemaKeyref.Refer.ToString(), xi); } CompileIdentityConstraint(ic); if (ic.CompiledConstraint == null) { - throw new XmlSchemaException(SR.Sch_RefInvalidIdentityConstraint, ((XmlSchemaKeyref)xi).Refer.ToString(), xi); + throw new XmlSchemaException(SR.Sch_RefInvalidIdentityConstraint, xmlSchemaKeyref.Refer.ToString(), xi); } // keyref has the different cardinality with the key it referred if (ic.Fields.Count != xi.Fields.Count) @@ -2387,22 +2387,22 @@ private ContentValidator CompileComplexContent(XmlSchemaComplexType complexType) } catch (UpaException e) { - if (e.Particle1 is XmlSchemaElement) + if (e.Particle1 is XmlSchemaElement xmlSchemaElement3) { - if (e.Particle2 is XmlSchemaElement) + if (e.Particle2 is XmlSchemaElement xmlSchemaElement) { - SendValidationEvent(SR.Sch_NonDeterministic, ((XmlSchemaElement)e.Particle1).QualifiedName.ToString(), (XmlSchemaElement)e.Particle2); + SendValidationEvent(SR.Sch_NonDeterministic, xmlSchemaElement3.QualifiedName.ToString(), xmlSchemaElement); } else { - SendValidationEvent(SR.Sch_NonDeterministicAnyEx, ((XmlSchemaAny)e.Particle2!).NamespaceList!.ToString(), ((XmlSchemaElement)e.Particle1).QualifiedName.ToString(), (XmlSchemaAny)e.Particle2); + SendValidationEvent(SR.Sch_NonDeterministicAnyEx, ((XmlSchemaAny)e.Particle2!).NamespaceList!.ToString(), xmlSchemaElement3.QualifiedName.ToString(), (XmlSchemaAny)e.Particle2); } } else { - if (e.Particle2 is XmlSchemaElement) + if (e.Particle2 is XmlSchemaElement xmlSchemaElement2) { - SendValidationEvent(SR.Sch_NonDeterministicAnyEx, ((XmlSchemaAny)e.Particle1!).NamespaceList!.ToString(), ((XmlSchemaElement)e.Particle2).QualifiedName.ToString(), (XmlSchemaAny)e.Particle1); + SendValidationEvent(SR.Sch_NonDeterministicAnyEx, ((XmlSchemaAny)e.Particle1!).NamespaceList!.ToString(), xmlSchemaElement2.QualifiedName.ToString(), (XmlSchemaAny)e.Particle1); } else { @@ -2519,9 +2519,9 @@ private static void BuildParticleContentModel(ParticleContentValidator contentVa { contentValidator.AddNamespaceList(any.NamespaceList!, any); } - else if (particle is XmlSchemaGroupBase) + else if (particle is XmlSchemaGroupBase xmlSchemaGroupBase) { - XmlSchemaObjectCollection particles = ((XmlSchemaGroupBase)particle).Items; + XmlSchemaObjectCollection particles = xmlSchemaGroupBase.Items; bool isChoice = particle is XmlSchemaChoice; contentValidator.OpenGroup(); bool first = true; @@ -2589,9 +2589,9 @@ private void CompileParticleElements(XmlSchemaComplexType complexType, XmlSchema } } } - else if (particle is XmlSchemaGroupBase) + else if (particle is XmlSchemaGroupBase xmlSchemaGroupBase) { - XmlSchemaObjectCollection particles = ((XmlSchemaGroupBase)particle).Items; + XmlSchemaObjectCollection particles = xmlSchemaGroupBase.Items; for (int i = 0; i < particles.Count; ++i) { CompileParticleElements(complexType, (XmlSchemaParticle)particles[i]); @@ -2658,9 +2658,9 @@ private void CompileCompexTypeElements(XmlSchemaComplexType complexType) XmlSchemaType? type = (XmlSchemaType?)_schema!.SchemaTypes[name]; if (type != null) { - if (type is XmlSchemaComplexType) + if (type is XmlSchemaComplexType xmlSchemaComplexType) { - CompileComplexType((XmlSchemaComplexType)type); + CompileComplexType(xmlSchemaComplexType); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs index e98111ca67e5ce..f5a96e9d1e7cb9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs @@ -381,26 +381,26 @@ private void Preprocess(XmlSchema schema, string? targetNamespace, Compositor co { Preprocess(include.Schema, schema.TargetNamespace, Compositor.Include); } - else if (include is XmlSchemaImport) + else if (include is XmlSchemaImport xmlSchemaImport) { - if (((XmlSchemaImport)include).Namespace == null && schema.TargetNamespace == null) + if (xmlSchemaImport.Namespace == null && schema.TargetNamespace == null) { SendValidationEvent(SR.Sch_ImportTargetNamespaceNull, include); } - else if (((XmlSchemaImport)include).Namespace == schema.TargetNamespace) + else if (xmlSchemaImport.Namespace == schema.TargetNamespace) { SendValidationEvent(SR.Sch_ImportTargetNamespace, include); } - Preprocess(include.Schema, ((XmlSchemaImport)include).Namespace, Compositor.Import); + Preprocess(include.Schema, xmlSchemaImport.Namespace, Compositor.Import); } else { Preprocess(include.Schema, schema.TargetNamespace, Compositor.Include); } } - else if (include is XmlSchemaImport) + else if (include is XmlSchemaImport xmlSchemaImport2) { - string? ns = ((XmlSchemaImport)include).Namespace; + string? ns = xmlSchemaImport2.Namespace; if (ns != null) { if (ns.Length == 0) @@ -484,7 +484,7 @@ private void Preprocess(XmlSchema schema, string? targetNamespace, Compositor co { for (int j = 0; j < redefine.Items.Count; ++j) { - if (!(redefine.Items[j] is XmlSchemaAnnotation)) + if (redefine.Items[j] is not XmlSchemaAnnotation) { SendValidationEvent(SR.Sch_RedefineNoSchema, redefine); break; @@ -568,7 +568,7 @@ private void Preprocess(XmlSchema schema, string? targetNamespace, Compositor co PreprocessNotation(notation); AddToTable(schema.Notations, notation.QualifiedName, notation); } - else if (!(schema.Items[i] is XmlSchemaAnnotation)) + else if (schema.Items[i] is not XmlSchemaAnnotation) { SendValidationEvent(SR.Sch_InvalidCollection, schema.Items[i]); removeItemsList.Add(schema.Items[i]); @@ -783,12 +783,12 @@ private void CheckRefinedComplexType(XmlSchemaComplexType ctype) if (ctype.ContentModel != null) { XmlQualifiedName baseName; - if (ctype.ContentModel is XmlSchemaComplexContent) + if (ctype.ContentModel is XmlSchemaComplexContent xmlSchemaComplexContent) { - XmlSchemaComplexContent content = (XmlSchemaComplexContent)ctype.ContentModel; - if (content.Content is XmlSchemaComplexContentRestriction) + XmlSchemaComplexContent content = xmlSchemaComplexContent; + if (content.Content is XmlSchemaComplexContentRestriction xmlSchemaComplexContentRestriction) { - baseName = ((XmlSchemaComplexContentRestriction)content.Content).BaseTypeName; + baseName = xmlSchemaComplexContentRestriction.BaseTypeName; } else { @@ -798,9 +798,9 @@ private void CheckRefinedComplexType(XmlSchemaComplexType ctype) else { XmlSchemaSimpleContent content = (XmlSchemaSimpleContent)ctype.ContentModel; - if (content.Content is XmlSchemaSimpleContentRestriction) + if (content.Content is XmlSchemaSimpleContentRestriction xmlSchemaSimpleContentRestriction) { - baseName = ((XmlSchemaSimpleContentRestriction)content.Content).BaseTypeName; + baseName = xmlSchemaSimpleContentRestriction.BaseTypeName; } else { @@ -1075,9 +1075,9 @@ private void PreprocessElementContent(XmlSchemaElement element) { SendValidationEvent(SR.Sch_TypeMutualExclusive, element); } - if (element.SchemaType is XmlSchemaComplexType) + if (element.SchemaType is XmlSchemaComplexType xmlSchemaComplexType) { - PreprocessComplexType((XmlSchemaComplexType)element.SchemaType, true); + PreprocessComplexType(xmlSchemaComplexType, true); } else { @@ -1364,9 +1364,9 @@ private void PreprocessComplexType(XmlSchemaComplexType complexType, bool local) // "complexType.Particle != null || complexType.Attributes != null" is illegal - if (complexType.ContentModel is XmlSchemaSimpleContent) + if (complexType.ContentModel is XmlSchemaSimpleContent xmlSchemaSimpleContent) { - XmlSchemaSimpleContent content = (XmlSchemaSimpleContent)complexType.ContentModel; + XmlSchemaSimpleContent content = xmlSchemaSimpleContent; if (content.Content == null) { if (complexType.QualifiedName == XmlQualifiedName.Empty) @@ -1619,9 +1619,9 @@ private void PreprocessParticle(XmlSchemaParticle particle) } } } - else if (particle is XmlSchemaSequence) + else if (particle is XmlSchemaSequence xmlSchemaSequence) { - XmlSchemaObjectCollection sequences = ((XmlSchemaSequence)particle).Items; + XmlSchemaObjectCollection sequences = xmlSchemaSequence.Items; for (int i = 0; i < sequences.Count; ++i) { SetParent(sequences[i], particle); @@ -1647,11 +1647,11 @@ private void PreprocessParticle(XmlSchemaParticle particle) ValidateQNameAttribute(groupRef, "ref", groupRef.RefName); } } - else if (particle is XmlSchemaAny) + else if (particle is XmlSchemaAny xmlSchemaAny) { try { - ((XmlSchemaAny)particle).BuildNamespaceListV1Compat(_targetNamespace!); + xmlSchemaAny.BuildNamespaceListV1Compat(_targetNamespace!); } catch { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs index 1e79524bb100ec..f9bcc75fc67f58 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs @@ -809,9 +809,9 @@ private void CompileComplexType(XmlSchemaComplexType complexType) if (complexType.ContentModel is XmlSchemaSimpleContent simpleContent) { complexType.SetContentType(XmlSchemaContentType.TextOnly); - if (simpleContent.Content is XmlSchemaSimpleContentExtension) + if (simpleContent.Content is XmlSchemaSimpleContentExtension xmlSchemaSimpleContentExtension) { - CompileSimpleContentExtension(complexType, (XmlSchemaSimpleContentExtension)simpleContent.Content); + CompileSimpleContentExtension(complexType, xmlSchemaSimpleContentExtension); } else { //simpleContent.Content is XmlSchemaSimpleContentRestriction @@ -821,9 +821,9 @@ private void CompileComplexType(XmlSchemaComplexType complexType) else { // complexType.ContentModel is XmlSchemaComplexContent XmlSchemaComplexContent complexContent = (XmlSchemaComplexContent)complexType.ContentModel; - if (complexContent.Content is XmlSchemaComplexContentExtension) + if (complexContent.Content is XmlSchemaComplexContentExtension xmlSchemaComplexContentExtension) { - CompileComplexContentExtension(complexType, complexContent, (XmlSchemaComplexContentExtension)complexContent.Content); + CompileComplexContentExtension(complexType, complexContent, xmlSchemaComplexContentExtension); } else { // complexContent.Content is XmlSchemaComplexContentRestriction @@ -1206,21 +1206,21 @@ private XmlSchemaParticle CanonicalizeParticle(XmlSchemaParticle? particle, bool //return CanonicalizeElement((XmlSchemaElement)particle, substitution); return particle; } - else if (particle is XmlSchemaGroupRef) + else if (particle is XmlSchemaGroupRef xmlSchemaGroupRef) { - return CanonicalizeGroupRef((XmlSchemaGroupRef)particle, root); + return CanonicalizeGroupRef(xmlSchemaGroupRef, root); } - else if (particle is XmlSchemaAll) + else if (particle is XmlSchemaAll xmlSchemaAll) { - return CanonicalizeAll((XmlSchemaAll)particle, root); + return CanonicalizeAll(xmlSchemaAll, root); } - else if (particle is XmlSchemaChoice) + else if (particle is XmlSchemaChoice xmlSchemaChoice) { - return CanonicalizeChoice((XmlSchemaChoice)particle, root); + return CanonicalizeChoice(xmlSchemaChoice, root); } - else if (particle is XmlSchemaSequence) + else if (particle is XmlSchemaSequence xmlSchemaSequence) { - return CanonicalizeSequence((XmlSchemaSequence)particle, root); + return CanonicalizeSequence(xmlSchemaSequence, root); } else { @@ -1536,9 +1536,9 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart { //Base Element is subs grp head. return IsValidRestriction(derivedParticle, newBaseParticle); } - else if (derivedParticle is XmlSchemaElement) + else if (derivedParticle is XmlSchemaElement xmlSchemaElement) { - return IsElementFromElement((XmlSchemaElement)derivedParticle, baseElem); + return IsElementFromElement(xmlSchemaElement, baseElem); } else { @@ -1546,26 +1546,26 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart return false; } } - else if (baseParticle is XmlSchemaAny) + else if (baseParticle is XmlSchemaAny xmlSchemaAny2) { - if (derivedParticle is XmlSchemaElement) + if (derivedParticle is XmlSchemaElement xmlSchemaElement2) { - return IsElementFromAny((XmlSchemaElement)derivedParticle, (XmlSchemaAny)baseParticle); + return IsElementFromAny(xmlSchemaElement2, xmlSchemaAny2); } - else if (derivedParticle is XmlSchemaAny) + else if (derivedParticle is XmlSchemaAny xmlSchemaAny) { - return IsAnyFromAny((XmlSchemaAny)derivedParticle, (XmlSchemaAny)baseParticle); + return IsAnyFromAny(xmlSchemaAny, xmlSchemaAny2); } else { - return IsGroupBaseFromAny((XmlSchemaGroupBase)derivedParticle, (XmlSchemaAny)baseParticle); + return IsGroupBaseFromAny((XmlSchemaGroupBase)derivedParticle, xmlSchemaAny2); } } - else if (baseParticle is XmlSchemaAll) + else if (baseParticle is XmlSchemaAll xmlSchemaAll) { - if (derivedParticle is XmlSchemaElement) + if (derivedParticle is XmlSchemaElement xmlSchemaElement3) { - return IsElementFromGroupBase((XmlSchemaElement)derivedParticle, (XmlSchemaGroupBase)baseParticle); + return IsElementFromGroupBase(xmlSchemaElement3, (XmlSchemaGroupBase)baseParticle); } else if (derivedParticle is XmlSchemaAll) { @@ -1574,9 +1574,9 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart return true; } } - else if (derivedParticle is XmlSchemaSequence) + else if (derivedParticle is XmlSchemaSequence xmlSchemaSequence) { - if (IsSequenceFromAll((XmlSchemaSequence)derivedParticle, (XmlSchemaAll)baseParticle)) + if (IsSequenceFromAll(xmlSchemaSequence, xmlSchemaAll)) { return true; } @@ -1588,11 +1588,11 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart } return false; } - else if (baseParticle is XmlSchemaChoice) + else if (baseParticle is XmlSchemaChoice xmlSchemaChoice) { - if (derivedParticle is XmlSchemaElement) + if (derivedParticle is XmlSchemaElement xmlSchemaElement4) { - return IsElementFromGroupBase((XmlSchemaElement)derivedParticle, (XmlSchemaGroupBase)baseParticle); + return IsElementFromGroupBase(xmlSchemaElement4, (XmlSchemaGroupBase)baseParticle); } else if (derivedParticle is XmlSchemaChoice) { @@ -1608,9 +1608,9 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart return true; } } - else if (derivedParticle is XmlSchemaSequence) + else if (derivedParticle is XmlSchemaSequence xmlSchemaSequence2) { - if (IsSequenceFromChoice((XmlSchemaSequence)derivedParticle, (XmlSchemaChoice)baseParticle)) + if (IsSequenceFromChoice(xmlSchemaSequence2, xmlSchemaChoice)) { return true; } @@ -1624,9 +1624,9 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart } else if (baseParticle is XmlSchemaSequence) { - if (derivedParticle is XmlSchemaElement) + if (derivedParticle is XmlSchemaElement xmlSchemaElement5) { - return IsElementFromGroupBase((XmlSchemaElement)derivedParticle, (XmlSchemaGroupBase)baseParticle); + return IsElementFromGroupBase(xmlSchemaElement5, (XmlSchemaGroupBase)baseParticle); } else if (derivedParticle is XmlSchemaSequence || (derivedParticle is XmlSchemaAll && ((XmlSchemaGroupBase)derivedParticle).Items.Count == 1)) { @@ -2589,18 +2589,18 @@ private void CompileIdentityConstraint(XmlSchemaIdentityConstraint xi) { SchemaNamespaceManager xnmgr = new SchemaNamespaceManager(xi); compic = new CompiledIdentityConstraint(xi, xnmgr); - if (xi is XmlSchemaKeyref) + if (xi is XmlSchemaKeyref xmlSchemaKeyref) { - XmlSchemaIdentityConstraint? ic = (XmlSchemaIdentityConstraint?)_identityConstraints[((XmlSchemaKeyref)xi).Refer]; + XmlSchemaIdentityConstraint? ic = (XmlSchemaIdentityConstraint?)_identityConstraints[xmlSchemaKeyref.Refer]; if (ic == null) { - throw new XmlSchemaException(SR.Sch_UndeclaredIdentityConstraint, ((XmlSchemaKeyref)xi).Refer.ToString(), xi); + throw new XmlSchemaException(SR.Sch_UndeclaredIdentityConstraint, xmlSchemaKeyref.Refer.ToString(), xi); } CompileIdentityConstraint(ic); if (ic.CompiledConstraint == null) { - throw new XmlSchemaException(SR.Sch_RefInvalidIdentityConstraint, ((XmlSchemaKeyref)xi).Refer.ToString(), xi); + throw new XmlSchemaException(SR.Sch_RefInvalidIdentityConstraint, xmlSchemaKeyref.Refer.ToString(), xi); } // keyref has the different cardinality with the key it referred @@ -2856,22 +2856,22 @@ private ContentValidator CompileComplexContent(XmlSchemaComplexType complexType) } catch (UpaException e) { - if (e.Particle1 is XmlSchemaElement) + if (e.Particle1 is XmlSchemaElement xmlSchemaElement3) { - if (e.Particle2 is XmlSchemaElement) + if (e.Particle2 is XmlSchemaElement xmlSchemaElement) { - SendValidationEvent(SR.Sch_NonDeterministic, ((XmlSchemaElement)e.Particle1).QualifiedName.ToString(), (XmlSchemaElement)e.Particle2); + SendValidationEvent(SR.Sch_NonDeterministic, xmlSchemaElement3.QualifiedName.ToString(), xmlSchemaElement); } else { - SendValidationEvent(SR.Sch_NonDeterministicAnyEx, ((XmlSchemaAny)e.Particle2!).ResolvedNamespace, ((XmlSchemaElement)e.Particle1).QualifiedName.ToString(), (XmlSchemaAny)e.Particle2); + SendValidationEvent(SR.Sch_NonDeterministicAnyEx, ((XmlSchemaAny)e.Particle2!).ResolvedNamespace, xmlSchemaElement3.QualifiedName.ToString(), (XmlSchemaAny)e.Particle2); } } else { - if (e.Particle2 is XmlSchemaElement) + if (e.Particle2 is XmlSchemaElement xmlSchemaElement2) { - SendValidationEvent(SR.Sch_NonDeterministicAnyEx, ((XmlSchemaAny)e.Particle1!).ResolvedNamespace, ((XmlSchemaElement)e.Particle2).QualifiedName.ToString(), (XmlSchemaElement)e.Particle2); + SendValidationEvent(SR.Sch_NonDeterministicAnyEx, ((XmlSchemaAny)e.Particle1!).ResolvedNamespace, xmlSchemaElement2.QualifiedName.ToString(), xmlSchemaElement2); } else { @@ -2895,15 +2895,15 @@ private static bool BuildParticleContentModel(ParticleContentValidator contentVa { contentValidator.AddName(element.QualifiedName, element); } - else if (particle is XmlSchemaAny) + else if (particle is XmlSchemaAny xmlSchemaAny) { hasWildCard = true; - XmlSchemaAny any = (XmlSchemaAny)particle; + XmlSchemaAny any = xmlSchemaAny; contentValidator.AddNamespaceList(any.NamespaceList!, any); } - else if (particle is XmlSchemaGroupBase) + else if (particle is XmlSchemaGroupBase xmlSchemaGroupBase) { - XmlSchemaObjectCollection particles = ((XmlSchemaGroupBase)particle).Items; + XmlSchemaObjectCollection particles = xmlSchemaGroupBase.Items; bool isChoice = particle is XmlSchemaChoice; contentValidator.OpenGroup(); bool first = true; @@ -2971,9 +2971,9 @@ private void CompileParticleElements(XmlSchemaComplexType complexType, XmlSchema } } } - else if (particle is XmlSchemaGroupBase) + else if (particle is XmlSchemaGroupBase xmlSchemaGroupBase) { - XmlSchemaObjectCollection particles = ((XmlSchemaGroupBase)particle).Items; + XmlSchemaObjectCollection particles = xmlSchemaGroupBase.Items; for (int i = 0; i < particles.Count; ++i) { CompileParticleElements(complexType, (XmlSchemaParticle)particles[i]); @@ -2987,9 +2987,9 @@ private void CompileParticleElements(XmlSchemaParticle particle) { CompileElement(localElement); } - else if (particle is XmlSchemaGroupBase) + else if (particle is XmlSchemaGroupBase xmlSchemaGroupBase) { - XmlSchemaObjectCollection particles = ((XmlSchemaGroupBase)particle).Items; + XmlSchemaObjectCollection particles = xmlSchemaGroupBase.Items; for (int i = 0; i < particles.Count; ++i) { CompileParticleElements((XmlSchemaParticle)particles[i]); @@ -3048,9 +3048,9 @@ private void CompileComplexTypeElements(XmlSchemaComplexType complexType) XmlSchemaType? type = (XmlSchemaType?)_schemaTypes[name]; if (type != null) { - if (type is XmlSchemaComplexType) + if (type is XmlSchemaComplexType xmlSchemaComplexType) { - CompileComplexType((XmlSchemaComplexType)type); + CompileComplexType(xmlSchemaComplexType); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs index 5a37b587541b13..7dd41a8fe801f2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs @@ -274,14 +274,14 @@ internal override XmlQualifiedName DerivedFrom // type derived from anyType return XmlQualifiedName.Empty; } - if (_contentModel.Content is XmlSchemaComplexContentRestriction) - return ((XmlSchemaComplexContentRestriction)_contentModel.Content).BaseTypeName; - else if (_contentModel.Content is XmlSchemaComplexContentExtension) - return ((XmlSchemaComplexContentExtension)_contentModel.Content).BaseTypeName; - else if (_contentModel.Content is XmlSchemaSimpleContentRestriction) - return ((XmlSchemaSimpleContentRestriction)_contentModel.Content).BaseTypeName; - else if (_contentModel.Content is XmlSchemaSimpleContentExtension) - return ((XmlSchemaSimpleContentExtension)_contentModel.Content).BaseTypeName; + if (_contentModel.Content is XmlSchemaComplexContentRestriction xmlSchemaComplexContentRestriction) + return xmlSchemaComplexContentRestriction.BaseTypeName; + else if (_contentModel.Content is XmlSchemaComplexContentExtension xmlSchemaComplexContentExtension) + return xmlSchemaComplexContentExtension.BaseTypeName; + else if (_contentModel.Content is XmlSchemaSimpleContentRestriction xmlSchemaSimpleContentRestriction) + return xmlSchemaSimpleContentRestriction.BaseTypeName; + else if (_contentModel.Content is XmlSchemaSimpleContentExtension xmlSchemaSimpleContentExtension) + return xmlSchemaSimpleContentExtension.BaseTypeName; else return XmlQualifiedName.Empty; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs index 2ac345672a40d1..461b83d872c002 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs @@ -181,9 +181,9 @@ internal static string ConcatenatedToString(object value) { bldr.Append('{'); object cur = enumerator.Current!; - if (cur is IFormattable) + if (cur is IFormattable formattable) { - bldr.Append(((IFormattable)cur).ToString("", CultureInfo.InvariantCulture)); + bldr.Append(formattable.ToString("", CultureInfo.InvariantCulture)); } else { @@ -193,9 +193,9 @@ internal static string ConcatenatedToString(object value) { bldr.Append(" , "); cur = enumerator.Current!; - if (cur is IFormattable) + if (cur is IFormattable formattable2) { - bldr.Append(((IFormattable)cur).ToString("", CultureInfo.InvariantCulture)); + bldr.Append(formattable2.ToString("", CultureInfo.InvariantCulture)); } else { @@ -206,9 +206,9 @@ internal static string ConcatenatedToString(object value) stringValue = bldr.ToString(); } } - else if (value is IFormattable) + else if (value is IFormattable formattable3) { - stringValue = ((IFormattable)value).ToString("", CultureInfo.InvariantCulture); + stringValue = formattable3.ToString("", CultureInfo.InvariantCulture); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaFacet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaFacet.cs index d32e87af59694e..e6845b64afd003 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaFacet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaFacet.cs @@ -42,7 +42,7 @@ public virtual bool IsFixed get { return _isFixed; } set { - if (!(this is XmlSchemaEnumerationFacet) && !(this is XmlSchemaPatternFacet)) + if (this is not XmlSchemaEnumerationFacet && this is not XmlSchemaPatternFacet) { _isFixed = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs index 8bb6d41419ea6d..c4f11da3b122d5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs @@ -33,9 +33,9 @@ internal override XmlQualifiedName DerivedFrom // type derived from anyType return XmlQualifiedName.Empty; } - if (_content is XmlSchemaSimpleTypeRestriction) + if (_content is XmlSchemaSimpleTypeRestriction xmlSchemaSimpleTypeRestriction) { - return ((XmlSchemaSimpleTypeRestriction)_content).BaseTypeName; + return xmlSchemaSimpleTypeRestriction.BaseTypeName; } return XmlQualifiedName.Empty; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs index 2a73f6dd24cc4a..18955955b94d0b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs @@ -234,7 +234,7 @@ protected XmlBaseConverter(XmlSchemaType schemaType) XmlSchemaDatatype? datatype = schemaType.Datatype; Debug.Assert(schemaType != null && datatype != null, "schemaType or schemaType.Datatype may not be null"); - while (schemaType != null && !(schemaType is XmlSchemaSimpleType)) + while (schemaType != null && schemaType is not XmlSchemaSimpleType) { schemaType = schemaType.BaseXmlSchemaType!; } @@ -2877,7 +2877,7 @@ public override object ChangeType(object value, Type destinationType, IXmlNamesp ArgumentNullException.ThrowIfNull(destinationType); // If source value does not implement IEnumerable, or it is a string or byte[], - if (!(value is IEnumerable) || value.GetType() == StringType || value.GetType() == ByteArrayType) + if (value is not IEnumerable || value.GetType() == StringType || value.GetType() == ByteArrayType) { // Then create a list from it value = new object[] { value }; @@ -2916,7 +2916,7 @@ public static XmlValueConverter Create(XmlValueConverter atomicConverter) if (atomicConverter == XmlAnyConverter.AnyAtomic) return XmlAnyListConverter.AnyAtomicList; - Debug.Assert(!(atomicConverter is XmlListConverter) || ((XmlListConverter)atomicConverter).atomicConverter == null, + Debug.Assert(atomicConverter is not XmlListConverter || ((XmlListConverter)atomicConverter).atomicConverter == null, "List converters should not be nested within one another."); return new XmlListConverter((XmlBaseConverter)atomicConverter); @@ -2947,7 +2947,7 @@ protected override object ChangeListType(object value, Type destinationType, IXm if (destinationType == ObjectType) destinationType = DefaultClrType!; // Input value must support IEnumerable and destination type should be IEnumerable, ICollection, IList, Type[], or String - if (!(value is IEnumerable) || !IsListType(destinationType)) + if (value is not IEnumerable || !IsListType(destinationType)) throw CreateInvalidClrMappingException(sourceType, destinationType); // Handle case where destination type is a string diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs index b692fac96ea573..6535504dba664f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs @@ -2176,9 +2176,9 @@ private static void BuildIdentityConstraint_Name(XsdBuilder builder, string valu private static void BuildIdentityConstraint_Refer(XsdBuilder builder, string value) { - if (builder._identityConstraint is XmlSchemaKeyref) + if (builder._identityConstraint is XmlSchemaKeyref xmlSchemaKeyref) { - ((XmlSchemaKeyref)builder._identityConstraint).Refer = builder.ParseQName(value, "refer"); + xmlSchemaKeyref.Refer = builder.ParseQName(value, "refer"); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs index 8fed6c4cf7b69f..a191d13b8e222b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs @@ -160,10 +160,10 @@ internal LocalBuilder GetTempLocal(Type type) internal static Type GetVariableType(object var) { - if (var is ArgBuilder) - return ((ArgBuilder)var).ArgType; - else if (var is LocalBuilder) - return ((LocalBuilder)var).LocalType; + if (var is ArgBuilder argBuilder) + return argBuilder.ArgType; + else if (var is LocalBuilder localBuilder) + return localBuilder.LocalType; else return var.GetType(); } @@ -633,20 +633,20 @@ internal void Load(object? obj) { if (obj == null) _ilGen!.Emit(OpCodes.Ldnull); - else if (obj is ArgBuilder) - Ldarg((ArgBuilder)obj); - else if (obj is LocalBuilder) - Ldloc((LocalBuilder)obj); + else if (obj is ArgBuilder argBuilder) + Ldarg(argBuilder); + else if (obj is LocalBuilder localBuilder) + Ldloc(localBuilder); else Ldc(obj); } internal void LoadAddress(object obj) { - if (obj is ArgBuilder) - LdargAddress((ArgBuilder)obj); - else if (obj is LocalBuilder) - LdlocAddress((LocalBuilder)obj); + if (obj is ArgBuilder argBuilder) + LdargAddress(argBuilder); + else if (obj is LocalBuilder localBuilder) + LdlocAddress(localBuilder); else Load(obj); } @@ -768,9 +768,9 @@ internal void Ldtoken(Type t) internal void Ldc(object o) { Type valueType = o.GetType(); - if (o is Type) + if (o is Type type) { - Ldtoken((Type)o); + Ldtoken(type); Call(typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(RuntimeTypeHandle) })!); } else if (valueType.IsEnum) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs index a58813263729f9..c437a09d940323 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs @@ -136,9 +136,9 @@ private int CompositeHash(XmlSchemaObject o) for (int i = 0; i < list.Count; i++) { object? cachedHash = Hash[list[i]!]; - if (cachedHash is int) + if (cachedHash is int num) { - tmp += (int)cachedHash / list.Count; + tmp += num / list.Count; } } return (int)tmp; @@ -264,10 +264,10 @@ internal void Depends(XmlSchemaObject? item, ArrayList refs) if (ct.ContentModel != null) { XmlSchemaContent? content = ct.ContentModel.Content; - if (content is XmlSchemaComplexContentRestriction) + if (content is XmlSchemaComplexContentRestriction xmlSchemaComplexContentRestriction) { - baseName = ((XmlSchemaComplexContentRestriction)content).BaseTypeName; - attributes = ((XmlSchemaComplexContentRestriction)content).Attributes; + baseName = xmlSchemaComplexContentRestriction.BaseTypeName; + attributes = xmlSchemaComplexContentRestriction.Attributes; } else if (content is XmlSchemaSimpleContentRestriction restriction) { @@ -306,10 +306,10 @@ internal void Depends(XmlSchemaObject? item, ArrayList refs) else if (item is XmlSchemaSimpleType simpleType) { XmlSchemaSimpleTypeContent? content = simpleType.Content; - if (content is XmlSchemaSimpleTypeRestriction) + if (content is XmlSchemaSimpleTypeRestriction xmlSchemaSimpleTypeRestriction) { - baseType = ((XmlSchemaSimpleTypeRestriction)content).BaseType; - baseName = ((XmlSchemaSimpleTypeRestriction)content).BaseTypeName; + baseType = xmlSchemaSimpleTypeRestriction.BaseType; + baseName = xmlSchemaSimpleTypeRestriction.BaseTypeName; } else if (content is XmlSchemaSimpleTypeList list) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs index e9eb811cf3fffa..bb358df7b9df41 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs @@ -1238,7 +1238,7 @@ internal void CheckDuplicateElement(XmlSchemaElement? element, string? elementNs return; // only check duplicate definitions for top-level element - if (element.Parent == null || !(element.Parent is XmlSchema)) + if (element.Parent == null || element.Parent is not XmlSchema) return; XmlSchemaObjectTable? elements; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs index 9319de05d7deb7..702401772c6515 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs @@ -80,7 +80,7 @@ internal ArrayModel GetArrayModel(Type type) if (!_arrayModels.TryGetValue(type, out model)) { model = GetTypeModel(type); - if (!(model is ArrayModel)) + if (model is not ArrayModel) { TypeDesc typeDesc = _typeScope.GetArrayTypeDesc(type); model = new ArrayModel(type, typeDesc, this); @@ -168,7 +168,7 @@ internal MemberInfo[] GetMemberInfos() // first copy all non-property members over for (int i = 0; i < members.Length; i++) { - if (!(members[i] is PropertyInfo)) + if (members[i] is not PropertyInfo) { fieldsAndProps[cMember++] = members[i]; } @@ -188,10 +188,10 @@ internal MemberInfo[] GetMemberInfos() internal FieldModel? GetFieldModel(MemberInfo memberInfo) { FieldModel? model = null; - if (memberInfo is FieldInfo) - model = GetFieldModel((FieldInfo)memberInfo); - else if (memberInfo is PropertyInfo) - model = GetPropertyModel((PropertyInfo)memberInfo); + if (memberInfo is FieldInfo fieldInfo) + model = GetFieldModel(fieldInfo); + else if (memberInfo is PropertyInfo propertyInfo) + model = GetPropertyModel(propertyInfo); if (model != null) { if (model.ReadOnly && model.FieldTypeDesc.Kind != TypeKind.Collection && model.FieldTypeDesc.Kind != TypeKind.Enumerable) @@ -326,14 +326,14 @@ internal FieldModel(MemberInfo memberInfo, Type fieldType, TypeDesc fieldTypeDes } } } - if (memberInfo is PropertyInfo) + if (memberInfo is PropertyInfo propertyInfo) { - _readOnly = !((PropertyInfo)memberInfo).CanWrite; + _readOnly = !propertyInfo.CanWrite; _isProperty = true; } - else if (memberInfo is FieldInfo) + else if (memberInfo is FieldInfo fieldInfo) { - _readOnly = ((FieldInfo)memberInfo).IsInitOnly; + _readOnly = fieldInfo.IsInitOnly; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs index 899dea108d5414..878b0c76f0bbe4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs @@ -22,8 +22,8 @@ internal NameKey(string? name, string? ns) public override bool Equals([NotNullWhen(true)] object? other) { - if (!(other is NameKey)) return false; - NameKey key = (NameKey)other; + if (other is not NameKey nameKey) return false; + NameKey key = nameKey; return _name == key._name && _ns == key._ns; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs index fba464fcbf582c..e3bf3b63619787 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs @@ -449,12 +449,12 @@ private void WriteElement(object? o, ElementAccessor element, bool writeAccessor } } } - else if (element.Mapping is EnumMapping) + else if (element.Mapping is EnumMapping enumMapping) { if (element.Mapping.IsSoap) { Writer.WriteStartElement(name, ns); - WriteEnumMethod((EnumMapping)element.Mapping, o!); + WriteEnumMethod(enumMapping, o!); WriteEndElement(); } else @@ -880,9 +880,9 @@ private void WriteMember(object? memberValue, AttributeAccessor attribute, TypeD Writer.WriteString(" "); } - if (ai is byte[]) + if (ai is byte[] bytes) { - WriteValue((byte[])ai); + WriteValue(bytes); } else { @@ -1000,9 +1000,9 @@ private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; if (hasDefault) { - if (mapping is EnumMapping) + if (mapping is EnumMapping enumMapping2) { - if (((EnumMapping)mapping).IsFlags) + if (enumMapping2.IsFlags) { IEnumerable defaultEnumFlagValues = defaultValue!.ToString()!.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); string defaultEnumFlagString = string.Join(", ", defaultEnumFlagValues); @@ -1152,21 +1152,21 @@ private bool WritePrimitiveValue(TypeDesc typeDesc, object? o, out string? strin stringValue = FromByteArrayHex((byte[])o); return true; } - else if (o is DateTime) + else if (o is DateTime dateTime) { if (typeDesc.FormatterName == "DateTime") { - stringValue = FromDateTime((DateTime)o); + stringValue = FromDateTime(dateTime); return true; } else if (typeDesc.FormatterName == "Date") { - stringValue = FromDate((DateTime)o); + stringValue = FromDate(dateTime); return true; } else if (typeDesc.FormatterName == "Time") { - stringValue = FromTime((DateTime)o); + stringValue = FromTime(dateTime); return true; } else @@ -1174,14 +1174,14 @@ private bool WritePrimitiveValue(TypeDesc typeDesc, object? o, out string? strin throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Invalid DateTime")); } } - else if (o is DateOnly) + else if (o is DateOnly dateOnly) { - stringValue = FromDateOnly((DateOnly)o); + stringValue = FromDateOnly(dateOnly); return true; } - else if (o is TimeOnly) + else if (o is TimeOnly timeOnly) { - stringValue = FromTimeOnly((TimeOnly)o); + stringValue = FromTimeOnly(timeOnly); return true; } else if (typeDesc == ReflectionXmlSerializationReader.QnameTypeDesc) @@ -1189,21 +1189,21 @@ private bool WritePrimitiveValue(TypeDesc typeDesc, object? o, out string? strin stringValue = FromXmlQualifiedName((XmlQualifiedName?)o); return true; } - else if (o is string) + else if (o is string str) { switch (typeDesc.FormatterName) { case "XmlName": - stringValue = FromXmlName((string)o); + stringValue = FromXmlName(str); break; case "XmlNCName": - stringValue = FromXmlNCName((string)o); + stringValue = FromXmlNCName(str); break; case "XmlNmToken": - stringValue = FromXmlNmToken((string)o); + stringValue = FromXmlNmToken(str); break; case "XmlNmTokens": - stringValue = FromXmlNmTokens((string)o); + stringValue = FromXmlNmTokens(str); break; default: stringValue = null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs index 6ede76395540a5..d0b03157b176d3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs @@ -63,37 +63,37 @@ public int Compare(object? o1, object? o2) internal static XmlQualifiedName NameOf(XmlSchemaObject? o) { - if (o is XmlSchemaAttribute) + if (o is XmlSchemaAttribute xmlSchemaAttribute) { - return ((XmlSchemaAttribute)o).QualifiedName; + return xmlSchemaAttribute.QualifiedName; } - else if (o is XmlSchemaAttributeGroup) + else if (o is XmlSchemaAttributeGroup xmlSchemaAttributeGroup) { - return ((XmlSchemaAttributeGroup)o).QualifiedName; + return xmlSchemaAttributeGroup.QualifiedName; } - else if (o is XmlSchemaComplexType) + else if (o is XmlSchemaComplexType xmlSchemaComplexType) { - return ((XmlSchemaComplexType)o).QualifiedName; + return xmlSchemaComplexType.QualifiedName; } - else if (o is XmlSchemaSimpleType) + else if (o is XmlSchemaSimpleType xmlSchemaSimpleType) { - return ((XmlSchemaSimpleType)o).QualifiedName; + return xmlSchemaSimpleType.QualifiedName; } - else if (o is XmlSchemaElement) + else if (o is XmlSchemaElement xmlSchemaElement) { - return ((XmlSchemaElement)o).QualifiedName; + return xmlSchemaElement.QualifiedName; } - else if (o is XmlSchemaGroup) + else if (o is XmlSchemaGroup xmlSchemaGroup) { - return ((XmlSchemaGroup)o).QualifiedName; + return xmlSchemaGroup.QualifiedName; } - else if (o is XmlSchemaGroupRef) + else if (o is XmlSchemaGroupRef xmlSchemaGroupRef) { - return ((XmlSchemaGroupRef)o).RefName; + return xmlSchemaGroupRef.RefName; } - else if (o is XmlSchemaNotation) + else if (o is XmlSchemaNotation xmlSchemaNotation) { - return ((XmlSchemaNotation)o).QualifiedName; + return xmlSchemaNotation.QualifiedName; } else if (o is XmlSchemaSequence s) { @@ -113,13 +113,13 @@ internal static XmlQualifiedName NameOf(XmlSchemaObject? o) return new XmlQualifiedName(".choice", Namespace(o)); return NameOf(c.Items); } - else if (o is XmlSchemaAny) + else if (o is XmlSchemaAny xmlSchemaAny) { - return new XmlQualifiedName("*", SchemaObjectWriter.ToString(((XmlSchemaAny)o).NamespaceList)); + return new XmlQualifiedName("*", SchemaObjectWriter.ToString(xmlSchemaAny.NamespaceList)); } - else if (o is XmlSchemaIdentityConstraint) + else if (o is XmlSchemaIdentityConstraint xmlSchemaIdentityConstraint) { - return ((XmlSchemaIdentityConstraint)o).QualifiedName; + return xmlSchemaIdentityConstraint.QualifiedName; } return new XmlQualifiedName("?", Namespace(o)); } @@ -138,7 +138,7 @@ internal static XmlQualifiedName NameOf(XmlSchemaObjectCollection items) internal static string? Namespace(XmlSchemaObject? o) { - while (o != null && !(o is XmlSchema)) + while (o != null && o is not XmlSchema) { o = o.Parent; } @@ -302,7 +302,7 @@ private void Write1_XmlSchemaAttribute(XmlSchemaAttribute? o) WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); WriteAttribute(@"default", @"", ((string?)o.@DefaultValue)); WriteAttribute(@"fixed", @"", ((string?)o.@FixedValue)); - if (o.Parent != null && !(o.Parent is XmlSchema)) + if (o.Parent != null && o.Parent is not XmlSchema) { if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && !string.IsNullOrEmpty(o.QualifiedName.Namespace)) { @@ -500,13 +500,13 @@ private void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation? o) for (int ia = 0; ia < a.Count; ia++) { XmlSchemaObject ai = (XmlSchemaObject)a[ia]; - if (ai is XmlSchemaAppInfo) + if (ai is XmlSchemaAppInfo xmlSchemaAppInfo) { - Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)ai); + Write7_XmlSchemaAppInfo(xmlSchemaAppInfo); } - else if (ai is XmlSchemaDocumentation) + else if (ai is XmlSchemaDocumentation xmlSchemaDocumentation) { - Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)ai); + Write6_XmlSchemaDocumentation(xmlSchemaDocumentation); } } } @@ -562,17 +562,17 @@ private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType? o) WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); - if (o.@Content is XmlSchemaSimpleTypeUnion) + if (o.@Content is XmlSchemaSimpleTypeUnion xmlSchemaSimpleTypeUnion) { - Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o.@Content); + Write12_XmlSchemaSimpleTypeUnion(xmlSchemaSimpleTypeUnion); } - else if (o.@Content is XmlSchemaSimpleTypeRestriction) + else if (o.@Content is XmlSchemaSimpleTypeRestriction xmlSchemaSimpleTypeRestriction) { - Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o.@Content); + Write15_XmlSchemaSimpleTypeRestriction(xmlSchemaSimpleTypeRestriction); } - else if (o.@Content is XmlSchemaSimpleTypeList) + else if (o.@Content is XmlSchemaSimpleTypeList xmlSchemaSimpleTypeList) { - Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o.@Content); + Write14_XmlSchemaSimpleTypeList(xmlSchemaSimpleTypeList); } WriteEndElement(); } @@ -815,29 +815,29 @@ private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o) } WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); - if (o.@ContentModel is XmlSchemaComplexContent) + if (o.@ContentModel is XmlSchemaComplexContent xmlSchemaComplexContent) { - Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o.@ContentModel); + Write41_XmlSchemaComplexContent(xmlSchemaComplexContent); } - else if (o.@ContentModel is XmlSchemaSimpleContent) + else if (o.@ContentModel is XmlSchemaSimpleContent xmlSchemaSimpleContent) { - Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o.@ContentModel); + Write36_XmlSchemaSimpleContent(xmlSchemaSimpleContent); } - if (o.@Particle is XmlSchemaSequence) + if (o.@Particle is XmlSchemaSequence xmlSchemaSequence) { - Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); + Write54_XmlSchemaSequence(xmlSchemaSequence); } - else if (o.@Particle is XmlSchemaGroupRef) + else if (o.@Particle is XmlSchemaGroupRef xmlSchemaGroupRef) { - Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); + Write55_XmlSchemaGroupRef(xmlSchemaGroupRef); } - else if (o.@Particle is XmlSchemaChoice) + else if (o.@Particle is XmlSchemaChoice xmlSchemaChoice) { - Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); + Write52_XmlSchemaChoice(xmlSchemaChoice); } - else if (o.@Particle is XmlSchemaAll) + else if (o.@Particle is XmlSchemaAll xmlSchemaAll) { - Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); + Write43_XmlSchemaAll(xmlSchemaAll); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); @@ -852,13 +852,13 @@ private void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent? o) WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); - if (o.@Content is XmlSchemaSimpleContentRestriction) + if (o.@Content is XmlSchemaSimpleContentRestriction xmlSchemaSimpleContentRestriction) { - Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o.@Content); + Write40_XmlSchemaSimpleContentRestriction(xmlSchemaSimpleContentRestriction); } - else if (o.@Content is XmlSchemaSimpleContentExtension) + else if (o.@Content is XmlSchemaSimpleContentExtension xmlSchemaSimpleContentExtension) { - Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o.@Content); + Write38_XmlSchemaSimpleContentExtension(xmlSchemaSimpleContentExtension); } WriteEndElement(); } @@ -907,13 +907,13 @@ private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent? o) WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed))); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); - if (o.@Content is XmlSchemaComplexContentRestriction) + if (o.@Content is XmlSchemaComplexContentRestriction xmlSchemaComplexContentRestriction) { - Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o.@Content); + Write56_XmlSchemaComplexContentRestriction(xmlSchemaComplexContentRestriction); } - else if (o.@Content is XmlSchemaComplexContentExtension) + else if (o.@Content is XmlSchemaComplexContentExtension xmlSchemaComplexContentExtension) { - Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o.@Content); + Write42_XmlSchemaComplexContentExtension(xmlSchemaComplexContentExtension); } WriteEndElement(); } @@ -930,21 +930,21 @@ private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExt WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); - if (o.@Particle is XmlSchemaSequence) + if (o.@Particle is XmlSchemaSequence xmlSchemaSequence) { - Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); + Write54_XmlSchemaSequence(xmlSchemaSequence); } - else if (o.@Particle is XmlSchemaGroupRef) + else if (o.@Particle is XmlSchemaGroupRef xmlSchemaGroupRef) { - Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); + Write55_XmlSchemaGroupRef(xmlSchemaGroupRef); } - else if (o.@Particle is XmlSchemaChoice) + else if (o.@Particle is XmlSchemaChoice xmlSchemaChoice) { - Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); + Write52_XmlSchemaChoice(xmlSchemaChoice); } - else if (o.@Particle is XmlSchemaAll) + else if (o.@Particle is XmlSchemaAll xmlSchemaAll) { - Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); + Write43_XmlSchemaAll(xmlSchemaAll); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); @@ -980,7 +980,7 @@ private void Write46_XmlSchemaElement(XmlSchemaElement? o) WriteAttribute(@"default", @"", o.DefaultValue); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); WriteAttribute(@"fixed", @"", o.FixedValue); - if (o.Parent != null && !(o.Parent is XmlSchema)) + if (o.Parent != null && o.Parent is not XmlSchema) { if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && !string.IsNullOrEmpty(o.QualifiedName.Namespace)) { @@ -1014,13 +1014,13 @@ private void Write46_XmlSchemaElement(XmlSchemaElement? o) WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation(o.Annotation); - if (o.SchemaType is XmlSchemaComplexType) + if (o.SchemaType is XmlSchemaComplexType xmlSchemaComplexType) { - Write35_XmlSchemaComplexType((XmlSchemaComplexType)o.SchemaType); + Write35_XmlSchemaComplexType(xmlSchemaComplexType); } - else if (o.SchemaType is XmlSchemaSimpleType) + else if (o.SchemaType is XmlSchemaSimpleType xmlSchemaSimpleType) { - Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.SchemaType); + Write9_XmlSchemaSimpleType(xmlSchemaSimpleType); } WriteSortedItems(o.Constraints); WriteEndElement(); @@ -1172,25 +1172,25 @@ private void Write54_XmlSchemaSequence(XmlSchemaSequence? o) for (int ia = 0; ia < a.Count; ia++) { XmlSchemaObject ai = (XmlSchemaObject)a[ia]; - if (ai is XmlSchemaAny) + if (ai is XmlSchemaAny xmlSchemaAny) { - Write53_XmlSchemaAny((XmlSchemaAny)ai); + Write53_XmlSchemaAny(xmlSchemaAny); } - else if (ai is XmlSchemaSequence) + else if (ai is XmlSchemaSequence xmlSchemaSequence) { - Write54_XmlSchemaSequence((XmlSchemaSequence)ai); + Write54_XmlSchemaSequence(xmlSchemaSequence); } - else if (ai is XmlSchemaChoice) + else if (ai is XmlSchemaChoice xmlSchemaChoice) { - Write52_XmlSchemaChoice((XmlSchemaChoice)ai); + Write52_XmlSchemaChoice(xmlSchemaChoice); } - else if (ai is XmlSchemaElement) + else if (ai is XmlSchemaElement xmlSchemaElement) { - Write46_XmlSchemaElement((XmlSchemaElement)ai); + Write46_XmlSchemaElement(xmlSchemaElement); } - else if (ai is XmlSchemaGroupRef) + else if (ai is XmlSchemaGroupRef xmlSchemaGroupRef) { - Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)ai); + Write55_XmlSchemaGroupRef(xmlSchemaGroupRef); } } } @@ -1229,21 +1229,21 @@ private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentR } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); - if (o.@Particle is XmlSchemaSequence) + if (o.@Particle is XmlSchemaSequence xmlSchemaSequence) { - Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); + Write54_XmlSchemaSequence(xmlSchemaSequence); } - else if (o.@Particle is XmlSchemaGroupRef) + else if (o.@Particle is XmlSchemaGroupRef xmlSchemaGroupRef) { - Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); + Write55_XmlSchemaGroupRef(xmlSchemaGroupRef); } - else if (o.@Particle is XmlSchemaChoice) + else if (o.@Particle is XmlSchemaChoice xmlSchemaChoice) { - Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); + Write52_XmlSchemaChoice(xmlSchemaChoice); } - else if (o.@Particle is XmlSchemaAll) + else if (o.@Particle is XmlSchemaAll xmlSchemaAll) { - Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); + Write43_XmlSchemaAll(xmlSchemaAll); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); @@ -1259,17 +1259,17 @@ private void Write57_XmlSchemaGroup(XmlSchemaGroup? o) WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); - if (o.@Particle is XmlSchemaSequence) + if (o.@Particle is XmlSchemaSequence xmlSchemaSequence) { - Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); + Write54_XmlSchemaSequence(xmlSchemaSequence); } - else if (o.@Particle is XmlSchemaChoice) + else if (o.@Particle is XmlSchemaChoice xmlSchemaChoice) { - Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); + Write52_XmlSchemaChoice(xmlSchemaChoice); } - else if (o.@Particle is XmlSchemaAll) + else if (o.@Particle is XmlSchemaAll xmlSchemaAll) { - Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); + Write43_XmlSchemaAll(xmlSchemaAll); } WriteEndElement(); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs index 54798764fe12e0..47413d04f73ce3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs @@ -262,9 +262,9 @@ private NullableMapping CreateNullableMapping(TypeMapping baseMapping, NullableMapping mapping; if (existingMapping != null) { - if (existingMapping is NullableMapping) + if (existingMapping is NullableMapping nullableMapping) { - mapping = (NullableMapping)existingMapping; + mapping = nullableMapping; if (mapping.BaseMapping is PrimitiveMapping && baseMapping is PrimitiveMapping) return mapping; else if (mapping.BaseMapping == baseMapping) @@ -276,7 +276,7 @@ private NullableMapping CreateNullableMapping(TypeMapping baseMapping, throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc!.FullName, typeDesc.Name, existingMapping.Namespace)); } } - else if (!(baseMapping is PrimitiveMapping)) + else if (baseMapping is not PrimitiveMapping) { throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc!.FullName, typeDesc.Name, existingMapping.Namespace)); } @@ -386,7 +386,7 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, R var members = new List(); foreach (MemberInfo memberInfo in model.GetMemberInfos()) { - if (!(memberInfo is FieldInfo) && !(memberInfo is PropertyInfo)) + if (memberInfo is not FieldInfo && memberInfo is not PropertyInfo) continue; SoapAttributes memberAttrs = GetAttributes(memberInfo); if (memberAttrs.SoapIgnore) continue; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs index 9e6859bd12523c..4bb898aca754b3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs @@ -297,8 +297,8 @@ private static string GetMappingName(Mapping mapping) { if (mapping is MembersMapping) return "(method)"; - else if (mapping is TypeMapping) - return ((TypeMapping)mapping).TypeDesc!.FullName; + else if (mapping is TypeMapping typeMapping) + return typeMapping.TypeDesc!.FullName; else throw new ArgumentException(SR.XmlInternalError, nameof(mapping)); } @@ -325,7 +325,7 @@ private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors) if (existing.Mapping == accessor.Mapping) return existing; - if (!(accessor.Mapping is MembersMapping) && !(existing.Mapping is MembersMapping)) + if (accessor.Mapping is not MembersMapping && existing.Mapping is not MembersMapping) { if (accessor.Mapping!.TypeDesc == existing.Mapping!.TypeDesc || (existing.Mapping is NullableMapping && accessor.Mapping.TypeDesc == ((NullableMapping)existing.Mapping).BaseMapping!.TypeDesc) @@ -345,13 +345,13 @@ private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors) if (accessor.Mapping is MembersMapping || existing.Mapping is MembersMapping) throw new InvalidOperationException(SR.Format(SR.XmlMethodTypeNameConflict, accessor.Name, accessor.Namespace)); - if (accessor.Mapping is ArrayMapping) + if (accessor.Mapping is ArrayMapping arrayMapping) { - if (!(existing.Mapping is ArrayMapping)) + if (existing.Mapping is not ArrayMapping) { throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping!), GetMappingName(accessor.Mapping))); } - ArrayMapping mapping = (ArrayMapping)accessor.Mapping; + ArrayMapping mapping = arrayMapping; ArrayMapping? existingMapping = mapping.IsAnonymousType ? null : (ArrayMapping?)_types[existing.Mapping.TypeName!, existing.Mapping.Namespace]; ArrayMapping? first = existingMapping; while (existingMapping != null) @@ -660,9 +660,9 @@ private NullableMapping CreateNullableMapping(TypeMapping baseMapping, NullableMapping mapping; if (existingMapping != null) { - if (existingMapping is NullableMapping) + if (existingMapping is NullableMapping nullableMapping) { - mapping = (NullableMapping)existingMapping; + mapping = nullableMapping; if (mapping.BaseMapping is PrimitiveMapping && baseMapping is PrimitiveMapping) return mapping; else if (mapping.BaseMapping == baseMapping) @@ -799,12 +799,12 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, b if (model.TypeDesc.BaseTypeDesc != null) { TypeModel baseModel = _modelScope.GetTypeModel(model.Type.BaseType!, false); - if (!(baseModel is StructModel)) + if (baseModel is not StructModel structModel) { //XmlUnsupportedInheritance=Using '{0}' as a base type for a class is not supported by XmlSerializer. throw new NotSupportedException(SR.Format(SR.XmlUnsupportedInheritance, model.Type.BaseType!.FullName)); } - StructMapping baseMapping = ImportStructLikeMapping((StructModel)baseModel, mapping.Namespace, openModel, null, limiter); + StructMapping baseMapping = ImportStructLikeMapping(structModel, mapping.Namespace, openModel, null, limiter); // check to see if the import of the baseMapping was deferred int baseIndex = limiter.DeferredWorkItems.IndexOf(baseMapping); if (baseIndex < 0) @@ -1634,7 +1634,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType); text.Name = accessorName; // unused except to make more helpful error messages text.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(targetType), ns, ImportContext.Text, a.XmlText.DataType, null, true, false, limiter); - if (!(text.Mapping is SpecialMapping) && targetTypeDesc != _typeScope.GetTypeDesc(typeof(string))) + if (text.Mapping is not SpecialMapping && targetTypeDesc != _typeScope.GetTypeDesc(typeof(string))) throw new InvalidOperationException(SR.Format(SR.XmlIllegalArrayTextAttribute, accessorName)); accessor.Text = text; @@ -1979,7 +1979,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml if (rpc) { - if (accessor.TypeDesc.IsArrayLike && accessor.Elements.Length > 0 && !(accessor.Elements[0].Mapping is ArrayMapping)) + if (accessor.TypeDesc.IsArrayLike && accessor.Elements.Length > 0 && accessor.Elements[0].Mapping is not ArrayMapping) throw new InvalidOperationException(SR.Format(SR.XmlRpcLitArrayElement, accessor.Elements[0].Name)); if (accessor.Xmlns != null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs index 74f21b5657dc3b..4e660d66b8f98f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs @@ -82,7 +82,7 @@ public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool expor else if (member.Elements == null || member.Elements.Length == 0) continue; - if (member.TypeDesc!.IsArrayLike && !(member.Elements[0].Mapping is ArrayMapping)) + if (member.TypeDesc!.IsArrayLike && member.Elements[0].Mapping is not ArrayMapping) throw new InvalidOperationException(SR.Format(SR.XmlIllegalArrayElement, member.Elements[0].Name)); if (exportEnclosingType) @@ -346,28 +346,28 @@ private bool SchemaContainsItem(XmlSchemaObject item, string ns) private void ExportMapping(Mapping mapping, string? ns, bool isAny) { - if (mapping is ArrayMapping) - ExportArrayMapping((ArrayMapping)mapping, ns, null); - else if (mapping is PrimitiveMapping) + if (mapping is ArrayMapping arrayMapping) + ExportArrayMapping(arrayMapping, ns, null); + else if (mapping is PrimitiveMapping primitiveMapping) { - ExportPrimitiveMapping((PrimitiveMapping)mapping, ns); + ExportPrimitiveMapping(primitiveMapping, ns); } - else if (mapping is StructMapping) - ExportStructMapping((StructMapping)mapping, ns, null); - else if (mapping is MembersMapping) - ExportMembersMapping((MembersMapping)mapping, ns); - else if (mapping is SpecialMapping) - ExportSpecialMapping((SpecialMapping)mapping, ns, isAny, null); - else if (mapping is NullableMapping) - ExportMapping(((NullableMapping)mapping).BaseMapping!, ns, isAny); + else if (mapping is StructMapping structMapping) + ExportStructMapping(structMapping, ns, null); + else if (mapping is MembersMapping membersMapping) + ExportMembersMapping(membersMapping, ns); + else if (mapping is SpecialMapping specialMapping) + ExportSpecialMapping(specialMapping, ns, isAny, null); + else if (mapping is NullableMapping nullableMapping) + ExportMapping(nullableMapping.BaseMapping!, ns, isAny); else throw new ArgumentException(SR.XmlInternalError, nameof(mapping)); } private void ExportElementMapping(XmlSchemaElement element, Mapping mapping, string? ns, bool isAny) { - if (mapping is ArrayMapping) - ExportArrayMapping((ArrayMapping)mapping, ns, element); + if (mapping is ArrayMapping arrayMapping) + ExportArrayMapping(arrayMapping, ns, element); else if (mapping is PrimitiveMapping pm) { if (pm.IsAnonymousType) @@ -379,17 +379,17 @@ private void ExportElementMapping(XmlSchemaElement element, Mapping mapping, str element.SchemaTypeName = ExportPrimitiveMapping(pm, ns); } } - else if (mapping is StructMapping) + else if (mapping is StructMapping structMapping) { - ExportStructMapping((StructMapping)mapping, ns, element); + ExportStructMapping(structMapping, ns, element); } - else if (mapping is MembersMapping) - element.SchemaType = ExportMembersMapping((MembersMapping)mapping, ns); - else if (mapping is SpecialMapping) - ExportSpecialMapping((SpecialMapping)mapping, ns, isAny, element); - else if (mapping is NullableMapping) + else if (mapping is MembersMapping membersMapping) + element.SchemaType = ExportMembersMapping(membersMapping, ns); + else if (mapping is SpecialMapping specialMapping) + ExportSpecialMapping(specialMapping, ns, isAny, element); + else if (mapping is NullableMapping nullableMapping) { - ExportElementMapping(element, ((NullableMapping)mapping).BaseMapping!, ns, isAny); + ExportElementMapping(element, nullableMapping.BaseMapping!, ns, isAny); } else throw new ArgumentException(SR.XmlInternalError, nameof(mapping)); @@ -549,9 +549,9 @@ private XmlSchemaComplexType ExportMembersMapping(MembersMapping mapping, string private XmlSchemaSimpleType ExportAnonymousPrimitiveMapping(PrimitiveMapping mapping) { - if (mapping is EnumMapping) + if (mapping is EnumMapping enumMapping) { - return ExportEnumMapping((EnumMapping)mapping, null); + return ExportEnumMapping(enumMapping, null); } else { @@ -562,9 +562,9 @@ private XmlSchemaSimpleType ExportAnonymousPrimitiveMapping(PrimitiveMapping map private XmlQualifiedName ExportPrimitiveMapping(PrimitiveMapping mapping, string? ns) { XmlQualifiedName qname; - if (mapping is EnumMapping) + if (mapping is EnumMapping enumMapping) { - XmlSchemaType type = ExportEnumMapping((EnumMapping)mapping, ns); + XmlSchemaType type = ExportEnumMapping(enumMapping, ns); qname = new XmlQualifiedName(type.Name, mapping.Namespace); } else @@ -667,12 +667,12 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso if (type.ContentModel != null) { - if (type.ContentModel.Content is XmlSchemaComplexContentRestriction) - attributes = ((XmlSchemaComplexContentRestriction)type.ContentModel.Content).Attributes; - else if (type.ContentModel.Content is XmlSchemaComplexContentExtension) - attributes = ((XmlSchemaComplexContentExtension)type.ContentModel.Content).Attributes; - else if (type.ContentModel.Content is XmlSchemaSimpleContentExtension) - attributes = ((XmlSchemaSimpleContentExtension)type.ContentModel.Content).Attributes; + if (type.ContentModel.Content is XmlSchemaComplexContentRestriction xmlSchemaComplexContentRestriction) + attributes = xmlSchemaComplexContentRestriction.Attributes; + else if (type.ContentModel.Content is XmlSchemaComplexContentExtension xmlSchemaComplexContentExtension) + attributes = xmlSchemaComplexContentExtension.Attributes; + else if (type.ContentModel.Content is XmlSchemaSimpleContentExtension xmlSchemaSimpleContentExtension) + attributes = xmlSchemaSimpleContentExtension.Attributes; else throw new InvalidOperationException(SR.Format(SR.XmlInvalidContent, type.ContentModel.Content!.GetType().Name)); } @@ -701,9 +701,9 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso else { XmlSchemaContent? content = type.ContentModel.Content; - if (content is XmlSchemaComplexContentExtension) + if (content is XmlSchemaComplexContentExtension xmlSchemaComplexContentExtension2) { - XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content; + XmlSchemaComplexContentExtension extension = xmlSchemaComplexContentExtension2; extension.AnyAttribute = new XmlSchemaAnyAttribute(); } else if (content is XmlSchemaComplexContentRestriction restriction) @@ -784,7 +784,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso } } } - else if (!(accessor.Mapping is SpecialMapping)) + else if (accessor.Mapping is not SpecialMapping) throw new InvalidOperationException(SR.XmlInternalError); if (accessor.HasDefault) @@ -858,7 +858,7 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc internal static string? ExportDefaultValue(TypeMapping mapping, object? value) { - if (!(mapping is PrimitiveMapping)) + if (mapping is not PrimitiveMapping primitiveMapping) // should throw, but it will be a breaking change; return null; @@ -901,7 +901,7 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc } } - PrimitiveMapping pm = (PrimitiveMapping)mapping; + PrimitiveMapping pm = primitiveMapping; if (!pm.TypeDesc!.HasCustomFormatter) { @@ -941,13 +941,13 @@ private void ExportRootIfNecessary(TypeScope typeScope) { ExportDerivedMappings((StructMapping)mapping); } - else if (mapping is ArrayMapping) + else if (mapping is ArrayMapping arrayMapping) { - ExportArrayMapping((ArrayMapping)mapping, mapping.Namespace, null); + ExportArrayMapping(arrayMapping, mapping.Namespace, null); } - else if (mapping is SerializableMapping) + else if (mapping is SerializableMapping serializableMapping) { - ExportSpecialMapping((SerializableMapping)mapping, mapping.Namespace, false, null); + ExportSpecialMapping(serializableMapping, mapping.Namespace, false, null); } } } @@ -1061,10 +1061,10 @@ private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] member { if (type.ContentModel != null) { - if (type.ContentModel.Content is XmlSchemaComplexContentRestriction) - ((XmlSchemaComplexContentRestriction)type.ContentModel.Content).Particle = seq; - else if (type.ContentModel.Content is XmlSchemaComplexContentExtension) - ((XmlSchemaComplexContentExtension)type.ContentModel.Content).Particle = seq; + if (type.ContentModel.Content is XmlSchemaComplexContentRestriction xmlSchemaComplexContentRestriction) + xmlSchemaComplexContentRestriction.Particle = seq; + else if (type.ContentModel.Content is XmlSchemaComplexContentExtension xmlSchemaComplexContentExtension) + xmlSchemaComplexContentExtension.Particle = seq; else throw new InvalidOperationException(SR.Format(SR.XmlInvalidContent, type.ContentModel.Content!.GetType().Name)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs index 28212bf79bc2e3..811b6ac1876a3f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs @@ -53,9 +53,9 @@ public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type? base { ElementAccessor element = ImportElement(name, typeof(TypeMapping), baseType); - if (element.Mapping is StructMapping) + if (element.Mapping is StructMapping structMapping) { - MakeDerived((StructMapping)element.Mapping, baseType, baseTypeCanBeIndirect); + MakeDerived(structMapping, baseType, baseTypeCanBeIndirect); } else if (baseType != null) { @@ -106,9 +106,9 @@ public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type? baseType accessor.IsNullable = typeMapping.TypeDesc!.IsNullable; accessor.Form = XmlSchemaForm.Qualified; - if (accessor.Mapping is StructMapping) + if (accessor.Mapping is StructMapping structMapping) { - MakeDerived((StructMapping)accessor.Mapping, baseType, baseTypeCanBeIndirect); + MakeDerived(structMapping, baseType, baseTypeCanBeIndirect); } else if (baseType != null) { @@ -342,8 +342,8 @@ private TypeMapping ImportElementType(XmlSchemaElement element, string identifie } else if (element.SchemaType != null) { - if (element.SchemaType is XmlSchemaComplexType) - mapping = ImportType((XmlSchemaComplexType)element.SchemaType, ns, identifier, desiredMappingType, baseType); + if (element.SchemaType is XmlSchemaComplexType xmlSchemaComplexType) + mapping = ImportType(xmlSchemaComplexType, ns, identifier, desiredMappingType, baseType); else mapping = ImportDataType((XmlSchemaSimpleType)element.SchemaType, ns, identifier, baseType, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeTextValue, false)!; mapping!.ReferencedByElement = true; @@ -424,12 +424,12 @@ internal override void ImportDerivedTypes(XmlQualifiedName baseName) if (addref) AddReference(name, TypesInUse, SR.XmlCircularTypeReference); - if (type is XmlSchemaComplexType) + if (type is XmlSchemaComplexType xmlSchemaComplexType) { - mapping = ImportType((XmlSchemaComplexType)type, name.Namespace, name.Name, desiredMappingType, baseType); + mapping = ImportType(xmlSchemaComplexType, name.Namespace, name.Name, desiredMappingType, baseType); } - else if (type is XmlSchemaSimpleType) - mapping = ImportDataType((XmlSchemaSimpleType)type, name.Namespace, name.Name, baseType, flags, false); + else if (type is XmlSchemaSimpleType xmlSchemaSimpleType) + mapping = ImportDataType(xmlSchemaSimpleType, name.Namespace, name.Name, baseType, flags, false); else throw new InvalidOperationException(SR.XmlInternalError); @@ -502,8 +502,8 @@ private StructMapping ImportStructType(XmlSchemaType type, string? typeNs, strin { baseMapping = ImportType(type.DerivedFrom, typeof(TypeMapping), null, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue, false); - if (baseMapping is StructMapping) - baseTypeDesc = ((StructMapping)baseMapping).TypeDesc; + if (baseMapping is StructMapping structMapping2) + baseTypeDesc = structMapping2.TypeDesc; else if (baseMapping is ArrayMapping) { baseMapping = ((ArrayMapping)baseMapping).TopLevelMapping; @@ -527,9 +527,9 @@ private StructMapping ImportStructType(XmlSchemaType type, string? typeNs, strin Mapping? previousMapping = (Mapping?)ImportedMappings[type]; if (previousMapping != null) { - if (previousMapping is StructMapping) + if (previousMapping is StructMapping structMapping3) { - return (StructMapping)previousMapping; + return structMapping3; } else if (arrayLike && previousMapping is ArrayMapping) { @@ -547,9 +547,9 @@ private StructMapping ImportStructType(XmlSchemaType type, string? typeNs, strin StructMapping structMapping = new StructMapping(); structMapping.IsReference = Schemas.IsReference(type); TypeFlags flags = TypeFlags.Reference; - if (type is XmlSchemaComplexType) + if (type is XmlSchemaComplexType xmlSchemaComplexType) { - if (((XmlSchemaComplexType)type).IsAbstract) + if (xmlSchemaComplexType.IsAbstract) flags |= TypeFlags.Abstract; } @@ -663,13 +663,13 @@ private MemberMapping[] ImportTypeMembers(XmlSchemaType type, string? typeNs, st for (int i = 0; i < items.Attributes.Count; i++) { object item = items.Attributes[i]; - if (item is XmlSchemaAttribute) + if (item is XmlSchemaAttribute xmlSchemaAttribute) { - ImportAttributeMember((XmlSchemaAttribute)item, identifier, members, membersScope, typeNs); + ImportAttributeMember(xmlSchemaAttribute, identifier, members, membersScope, typeNs); } - else if (item is XmlSchemaAttributeGroupRef) + else if (item is XmlSchemaAttributeGroupRef xmlSchemaAttributeGroupRef) { - XmlQualifiedName groupName = ((XmlSchemaAttributeGroupRef)item).RefName; + XmlQualifiedName groupName = xmlSchemaAttributeGroupRef.RefName; ImportAttributeGroupMembers(FindAttributeGroup(groupName), identifier, members, membersScope, groupName.Namespace); } } @@ -690,10 +690,10 @@ private MemberMapping[] ImportTypeMembers(XmlSchemaType type, string? typeNs, st internal static bool IsMixed(XmlSchemaType type) { - if (!(type is XmlSchemaComplexType)) + if (type is not XmlSchemaComplexType xmlSchemaComplexType) return false; - XmlSchemaComplexType ct = (XmlSchemaComplexType)type; + XmlSchemaComplexType ct = xmlSchemaComplexType; bool mixed = ct.IsMixed; // check the mixed attribute on the complexContent @@ -710,10 +710,10 @@ internal static bool IsMixed(XmlSchemaType type) private TypeItems GetTypeItems(XmlSchemaType type) { TypeItems items = new TypeItems(); - if (type is XmlSchemaComplexType) + if (type is XmlSchemaComplexType xmlSchemaComplexType) { XmlSchemaParticle? particle = null; - XmlSchemaComplexType ct = (XmlSchemaComplexType)type; + XmlSchemaComplexType ct = xmlSchemaComplexType; if (ct.ContentModel != null) { XmlSchemaContent? content = ct.ContentModel.Content; @@ -741,9 +741,9 @@ private TypeItems GetTypeItems(XmlSchemaType type) items.Particle = FindGroup(refGroup.RefName).Particle; items.IsUnbounded = particle.IsMultipleOccurrence; } - else if (particle is XmlSchemaGroupBase) + else if (particle is XmlSchemaGroupBase xmlSchemaGroupBase) { - items.Particle = (XmlSchemaGroupBase)particle; + items.Particle = xmlSchemaGroupBase; items.IsUnbounded = particle.IsMultipleOccurrence; } } @@ -754,8 +754,8 @@ private TypeItems GetTypeItems(XmlSchemaType type) [RequiresDynamicCode(XmlSerializer.AotSerializationWarning)] private void ImportGroup(XmlSchemaGroupBase group, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool groupRepeats, bool allowUnboundedElements) { - if (group is XmlSchemaChoice) - ImportChoiceGroup((XmlSchemaChoice)group, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates); + if (group is XmlSchemaChoice xmlSchemaChoice) + ImportChoiceGroup(xmlSchemaChoice, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates); else ImportGroupMembers(group, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref mixed, ref needExplicitOrder, allowDuplicates, allowUnboundedElements); @@ -940,15 +940,15 @@ private bool GatherGroupChoices(XmlSchemaParticle? particle, NameTable choiceEle if (GatherGroupChoices((XmlSchemaParticle)item, choiceElements, identifier, ns, ref needExplicitOrder, allowDuplicates)) groupRepeats = true; } - else if (item is XmlSchemaAny) + else if (item is XmlSchemaAny xmlSchemaAny) { if (GenerateOrder) { - AddScopeElements(choiceElements, ImportAny((XmlSchemaAny)item, true, ns), ref duplicateElements, allowDuplicates); + AddScopeElements(choiceElements, ImportAny(xmlSchemaAny, true, ns), ref duplicateElements, allowDuplicates); } else { - any = (XmlSchemaAny)item; + any = xmlSchemaAny; } } else if (item is XmlSchemaElement element) @@ -971,7 +971,7 @@ private bool GatherGroupChoices(XmlSchemaParticle? particle, NameTable choiceEle { AddScopeElements(choiceElements, ImportAny(any, true, ns), ref duplicateElements, allowDuplicates); } - if (!groupRepeats && !(group is XmlSchemaChoice) && group.Items.Count > 1) + if (!groupRepeats && group is not XmlSchemaChoice && group.Items.Count > 1) { groupRepeats = true; } @@ -1041,15 +1041,15 @@ private void ImportGroupMembers(XmlSchemaParticle? particle, string identifier, object item = group.Items[i]; if (item is XmlSchemaChoice) ImportChoiceGroup((XmlSchemaGroupBase)item, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates); - else if (item is XmlSchemaElement) - ImportElementMember((XmlSchemaElement)item, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates, allowUnboundedElements); - else if (item is XmlSchemaAny) + else if (item is XmlSchemaElement xmlSchemaElement) + ImportElementMember(xmlSchemaElement, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates, allowUnboundedElements); + else if (item is XmlSchemaAny xmlSchemaAny) { - ImportAnyMember((XmlSchemaAny)item, members, membersScope, elementsScope, ns, ref mixed, ref needExplicitOrder, allowDuplicates); + ImportAnyMember(xmlSchemaAny, members, membersScope, elementsScope, ns, ref mixed, ref needExplicitOrder, allowDuplicates); } - else if (item is XmlSchemaParticle) + else if (item is XmlSchemaParticle xmlSchemaParticle) { - ImportGroupMembers((XmlSchemaParticle)item, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref mixed, ref needExplicitOrder, allowDuplicates, true); + ImportGroupMembers(xmlSchemaParticle, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref mixed, ref needExplicitOrder, allowDuplicates, true); } } } @@ -1259,15 +1259,15 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string? [RequiresDynamicCode(XmlSerializer.AotSerializationWarning)] private ArrayMapping? ImportArrayMapping(XmlSchemaType type, string identifier, string? ns) { - if (!(type is XmlSchemaComplexType)) return null; + if (type is not XmlSchemaComplexType) return null; if (!type.DerivedFrom.IsEmpty) return null; if (IsMixed(type)) return null; Mapping? previousMapping = (Mapping?)ImportedMappings[type]; if (previousMapping != null) { - if (previousMapping is ArrayMapping) - return (ArrayMapping)previousMapping; + if (previousMapping is ArrayMapping arrayMapping2) + return arrayMapping2; else return null; } @@ -1297,7 +1297,7 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string? } else if (item is XmlSchemaAll || item is XmlSchemaSequence) { - if (item.Items.Count != 1 || !(item.Items[0] is XmlSchemaElement)) return null; + if (item.Items.Count != 1 || item.Items[0] is not XmlSchemaElement) return null; XmlSchemaElement itemElement = (XmlSchemaElement)item.Items[0]; if (!itemElement.IsMultipleOccurrence) return null; if (IsCyclicReferencedType(itemElement, new List(1) { identifier })) @@ -1373,7 +1373,7 @@ private bool IsCyclicReferencedType(XmlSchemaElement element, List ident if (items.Attributes != null && items.Attributes.Count > 0) return null; XmlSchemaGroupBase group = (XmlSchemaGroupBase)items.Particle; - if (group.Items.Count != 1 || !(group.Items[0] is XmlSchemaAny)) return null; + if (group.Items.Count != 1 || group.Items[0] is not XmlSchemaAny) return null; XmlSchemaAny any = (XmlSchemaAny)group.Items[0]; SpecialMapping mapping = new SpecialMapping(); @@ -1515,9 +1515,9 @@ private static bool KeepXmlnsDeclarations(XmlSchemaType type, out string? xmlnsM foreach (XmlSchemaObject o in type.Annotation.Items) { - if (o is XmlSchemaAppInfo) + if (o is XmlSchemaAppInfo xmlSchemaAppInfo) { - XmlNode?[]? nodes = ((XmlSchemaAppInfo)o).Markup; + XmlNode?[]? nodes = xmlSchemaAppInfo.Markup; if (nodes != null && nodes.Length > 0) { foreach (XmlNode? node in nodes) @@ -1526,9 +1526,9 @@ private static bool KeepXmlnsDeclarations(XmlSchemaType type, out string? xmlnsM { if (e.Name == "keepNamespaceDeclarations") { - if (e.LastNode is XmlText) + if (e.LastNode is XmlText xmlText) { - xmlnsMemberName = (((XmlText)e.LastNode).Value!).Trim(null); + xmlnsMemberName = (xmlText.Value!).Trim(null); } return true; } @@ -1575,10 +1575,10 @@ private void ImportAttributeGroupMembers(XmlSchemaAttributeGroup group, string i for (int i = 0; i < group.Attributes.Count; i++) { object item = group.Attributes[i]; - if (item is XmlSchemaAttributeGroup) - ImportAttributeGroupMembers((XmlSchemaAttributeGroup)item, identifier, members, membersScope, ns); - else if (item is XmlSchemaAttribute) - ImportAttributeMember((XmlSchemaAttribute)item, identifier, members, membersScope, ns); + if (item is XmlSchemaAttributeGroup xmlSchemaAttributeGroup) + ImportAttributeGroupMembers(xmlSchemaAttributeGroup, identifier, members, membersScope, ns); + else if (item is XmlSchemaAttribute xmlSchemaAttribute) + ImportAttributeMember(xmlSchemaAttribute, identifier, members, membersScope, ns); } if (group.AnyAttribute != null) ImportAnyAttributeMember(members, membersScope); @@ -1755,8 +1755,8 @@ private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name) for (int i = 0; i < restriction.Facets.Count; i++) { object facet = restriction.Facets[i]; - if (!(facet is XmlSchemaEnumerationFacet)) continue; - XmlSchemaEnumerationFacet enumeration = (XmlSchemaEnumerationFacet)facet; + if (facet is not XmlSchemaEnumerationFacet xmlSchemaEnumerationFacet) continue; + XmlSchemaEnumerationFacet enumeration = xmlSchemaEnumerationFacet; // validate the enumeration value if (sourceTypeDesc != null && sourceTypeDesc.HasCustomFormatter) { @@ -1873,9 +1873,9 @@ private XmlSchemaAttributeGroup FindAttributeGroup(XmlQualifiedName name) internal static XmlQualifiedName BaseTypeName(XmlSchemaSimpleType dataType) { XmlSchemaSimpleTypeContent? content = dataType.Content; - if (content is XmlSchemaSimpleTypeRestriction) + if (content is XmlSchemaSimpleTypeRestriction xmlSchemaSimpleTypeRestriction) { - return ((XmlSchemaSimpleTypeRestriction)content).BaseTypeName; + return xmlSchemaSimpleTypeRestriction.BaseTypeName; } else if (content is XmlSchemaSimpleTypeList list) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs index 5807ff48269a52..ede7ed47bba56a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs @@ -185,9 +185,9 @@ private static void Prepare(XmlSchema schema) string? ns = schema.TargetNamespace; foreach (XmlSchemaExternal external in schema.Includes) { - if (external is XmlSchemaImport) + if (external is XmlSchemaImport xmlSchemaImport) { - if (ns == ((XmlSchemaImport)external).Namespace) + if (ns == xmlSchemaImport.Namespace) { removes.Add(external); } @@ -371,7 +371,7 @@ private void Merge(IList originals, XmlSchema schema) foreach (XmlSchemaExternal external in schema.Includes) { - if (external is XmlSchemaImport) + if (external is XmlSchemaImport xmlSchemaImport) { external.SchemaLocation = null; if (external.Schema != null) @@ -380,7 +380,7 @@ private void Merge(IList originals, XmlSchema schema) } else { - AddImport(originals, ((XmlSchemaImport)external).Namespace); + AddImport(originals, xmlSchemaImport.Namespace); } } else @@ -435,29 +435,29 @@ private void Merge(IList originals, XmlSchema schema) private static string? ItemName(XmlSchemaObject o) { - if (o is XmlSchemaNotation) + if (o is XmlSchemaNotation xmlSchemaNotation) { - return ((XmlSchemaNotation)o).Name; + return xmlSchemaNotation.Name; } - else if (o is XmlSchemaGroup) + else if (o is XmlSchemaGroup xmlSchemaGroup) { - return ((XmlSchemaGroup)o).Name; + return xmlSchemaGroup.Name; } - else if (o is XmlSchemaElement) + else if (o is XmlSchemaElement xmlSchemaElement) { - return ((XmlSchemaElement)o).Name; + return xmlSchemaElement.Name; } - else if (o is XmlSchemaType) + else if (o is XmlSchemaType xmlSchemaType) { - return ((XmlSchemaType)o).Name; + return xmlSchemaType.Name; } - else if (o is XmlSchemaAttributeGroup) + else if (o is XmlSchemaAttributeGroup xmlSchemaAttributeGroup) { - return ((XmlSchemaAttributeGroup)o).Name; + return xmlSchemaAttributeGroup.Name; } - else if (o is XmlSchemaAttribute) + else if (o is XmlSchemaAttribute xmlSchemaAttribute) { - return ((XmlSchemaAttribute)o).Name; + return xmlSchemaAttribute.Name; } return null; } @@ -496,19 +496,19 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) { tmp = tmp.Parent; } - if (tmp is XmlSchema) + if (tmp is XmlSchema xmlSchema) { - ns = ((XmlSchema)tmp).TargetNamespace; + ns = xmlSchema.TargetNamespace; } } string? item; - if (o is XmlSchemaNotation) + if (o is XmlSchemaNotation xmlSchemaNotation) { - item = SR.Format(SR.XmlSchemaNamedItem, ns, "notation", ((XmlSchemaNotation)o).Name, details); + item = SR.Format(SR.XmlSchemaNamedItem, ns, "notation", xmlSchemaNotation.Name, details); } - else if (o is XmlSchemaGroup) + else if (o is XmlSchemaGroup xmlSchemaGroup) { - item = SR.Format(SR.XmlSchemaNamedItem, ns, "group", ((XmlSchemaGroup)o).Name, details); + item = SR.Format(SR.XmlSchemaNamedItem, ns, "group", xmlSchemaGroup.Name, details); } else if (o is XmlSchemaElement e) { @@ -523,13 +523,13 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) item = SR.Format(SR.XmlSchemaNamedItem, ns, "element", e.Name, details); } } - else if (o is XmlSchemaType) + else if (o is XmlSchemaType xmlSchemaType) { - item = SR.Format(SR.XmlSchemaNamedItem, ns, o.GetType() == typeof(XmlSchemaSimpleType) ? "simpleType" : "complexType", ((XmlSchemaType)o).Name, null); + item = SR.Format(SR.XmlSchemaNamedItem, ns, o.GetType() == typeof(XmlSchemaSimpleType) ? "simpleType" : "complexType", xmlSchemaType.Name, null); } - else if (o is XmlSchemaAttributeGroup) + else if (o is XmlSchemaAttributeGroup xmlSchemaAttributeGroup) { - item = SR.Format(SR.XmlSchemaNamedItem, ns, "attributeGroup", ((XmlSchemaAttributeGroup)o).Name, details); + item = SR.Format(SR.XmlSchemaNamedItem, ns, "attributeGroup", xmlSchemaAttributeGroup.Name, details); } else if (o is XmlSchemaAttribute a) { @@ -702,9 +702,9 @@ internal static Exception CreateValidationException(XmlSchemaException exception { source = source.Parent; } - if (source is XmlSchema) + if (source is XmlSchema xmlSchema) { - ns = ((XmlSchema)source).TargetNamespace; + ns = xmlSchema.TargetNamespace; } } throw new InvalidOperationException(SR.Format(SR.XmlSchemaSyntaxErrorDetails, ns, message, exception.LineNumber, exception.LinePosition), exception); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs index 56f8a56b1fbf49..f9cb42d61180de 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs @@ -396,8 +396,8 @@ internal void GenerateSerializerContract(XmlMapping[] xmlMappings, Type?[] types internal static bool IsWildcard(SpecialMapping mapping) { - if (mapping is SerializableMapping) - return ((SerializableMapping)mapping).IsAny; + if (mapping is SerializableMapping serializableMapping) + return serializableMapping.IsAny; return mapping.TypeDesc!.CanBeElementValue; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs index fa4f1151d20f83..ecf0554d1ca6cb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs @@ -564,8 +564,8 @@ internal void GenerateSerializerContract(XmlMapping[] xmlMappings, Type[] types, internal static bool IsWildcard(SpecialMapping mapping) { - if (mapping is SerializableMapping) - return ((SerializableMapping)mapping).IsAny; + if (mapping is SerializableMapping serializableMapping) + return serializableMapping.IsAny; return mapping.TypeDesc!.CanBeElementValue; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs index 220f86cf123829..d4096626a59ed0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs @@ -2300,13 +2300,13 @@ internal void GenerateBegin() { if (!mapping.IsSoap) continue; - if (mapping is StructMapping) - WriteStructMethod((StructMapping)mapping); - else if (mapping is EnumMapping) - WriteEnumMethod((EnumMapping)mapping); - else if (mapping is NullableMapping) + if (mapping is StructMapping structMapping) + WriteStructMethod(structMapping); + else if (mapping is EnumMapping enumMapping) + WriteEnumMethod(enumMapping); + else if (mapping is NullableMapping nullableMapping) { - WriteNullableMethod((NullableMapping)mapping); + WriteNullableMethod(nullableMapping); } } } @@ -2319,17 +2319,17 @@ internal override void GenerateMethod(TypeMapping mapping) return; GeneratedMethods[mapping] = mapping; - if (mapping is StructMapping) + if (mapping is StructMapping structMapping) { - WriteStructMethod((StructMapping)mapping); + WriteStructMethod(structMapping); } - else if (mapping is EnumMapping) + else if (mapping is EnumMapping enumMapping) { - WriteEnumMethod((EnumMapping)mapping); + WriteEnumMethod(enumMapping); } - else if (mapping is NullableMapping) + else if (mapping is NullableMapping nullableMapping) { - WriteNullableMethod((NullableMapping)mapping); + WriteNullableMethod(nullableMapping); } } @@ -2377,10 +2377,10 @@ internal void GenerateEnd() return null; if (!xmlMapping.GenerateSerializer) throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); - if (xmlMapping is XmlTypeMapping) - return GenerateTypeElement((XmlTypeMapping)xmlMapping); - else if (xmlMapping is XmlMembersMapping) - return GenerateMembersElement((XmlMembersMapping)xmlMapping); + if (xmlMapping is XmlTypeMapping xmlTypeMapping) + return GenerateTypeElement(xmlTypeMapping); + else if (xmlMapping is XmlMembersMapping xmlMembersMapping) + return GenerateMembersElement(xmlMembersMapping); else throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); } @@ -4290,9 +4290,9 @@ private void WriteMemberElementsIf(Member[] members, Member? anyElement, string } if (checkType) { - if (e.Mapping is NullableMapping) + if (e.Mapping is NullableMapping nullableMapping) { - TypeDesc td = ((NullableMapping)e.Mapping).BaseMapping!.TypeDesc!; + TypeDesc td = nullableMapping.BaseMapping!.TypeDesc!; Writer.Write(RaCodeGen.GetStringForTypeof(td.CSharpName, td.UseReflection)); } else @@ -4329,10 +4329,10 @@ private void WriteMemberElementsIf(Member[] members, Member? anyElement, string Writer.WriteLine(" != null) {"); Writer.Indent++; } - if (e.Mapping is NullableMapping) + if (e.Mapping is NullableMapping nullableMapping2) { WriteSourceBegin(member.ArraySource); - TypeDesc td = ((NullableMapping)e.Mapping).BaseMapping!.TypeDesc!; + TypeDesc td = nullableMapping2.BaseMapping!.TypeDesc!; Writer.Write(RaCodeGen.GetStringForCreateInstance(e.Mapping.TypeDesc.CSharpName, e.Mapping.TypeDesc.UseReflection, false, true, $"({td.CSharpName}){checkTypeSource}")); } else @@ -4670,9 +4670,9 @@ private void WriteElement(string source, string? arrayName, string? choiceSource Writer.WriteLine(" = true;"); } - if (element.Mapping is ArrayMapping) + if (element.Mapping is ArrayMapping arrayMapping) { - WriteArray(source, arrayName, (ArrayMapping)element.Mapping, readOnly, element.IsNullable, fixupIndex); + WriteArray(source, arrayName, arrayMapping, readOnly, element.IsNullable, fixupIndex); } else if (element.Mapping is NullableMapping) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index 8ba96636eed923..3b9df2c58eaf35 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -205,17 +205,17 @@ internal override void GenerateMethod(TypeMapping mapping) if (!GeneratedMethods.Add(mapping)) return; - if (mapping is StructMapping) + if (mapping is StructMapping structMapping) { - WriteStructMethod((StructMapping)mapping); + WriteStructMethod(structMapping); } - else if (mapping is EnumMapping) + else if (mapping is EnumMapping enumMapping) { - WriteEnumMethod((EnumMapping)mapping); + WriteEnumMethod(enumMapping); } - else if (mapping is NullableMapping) + else if (mapping is NullableMapping nullableMapping) { - WriteNullableMethod((NullableMapping)mapping); + WriteNullableMethod(nullableMapping); } } @@ -267,10 +267,10 @@ internal void GenerateEnd() return null; if (!xmlMapping.GenerateSerializer) throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); - if (xmlMapping is XmlTypeMapping) - return GenerateTypeElement((XmlTypeMapping)xmlMapping); - else if (xmlMapping is XmlMembersMapping) - return GenerateMembersElement((XmlMembersMapping)xmlMapping); + if (xmlMapping is XmlTypeMapping xmlTypeMapping) + return GenerateTypeElement(xmlTypeMapping); + else if (xmlMapping is XmlMembersMapping xmlMembersMapping) + return GenerateMembersElement(xmlMembersMapping); else throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); } @@ -2966,9 +2966,9 @@ private void WriteElement(string source, string? arrayName, string? choiceSource ILGenSet(checkSpecified, true); } - if (element.Mapping is ArrayMapping) + if (element.Mapping is ArrayMapping arrayMapping) { - WriteArray(source, arrayName, (ArrayMapping)element.Mapping, readOnly, element.IsNullable, elementIndex); + WriteArray(source, arrayName, arrayMapping, readOnly, element.IsNullable, elementIndex); } else if (element.Mapping is NullableMapping) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs index befc8d8b4b2cd3..d34ab2e4ce9d18 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs @@ -1381,7 +1381,7 @@ protected void WritePotentiallyReferencingElement(string? n, string? ns, object? return; } Type t = o.GetType(); - if (Type.GetTypeCode(t) == TypeCode.Object && !(o is Guid) && (t != typeof(XmlQualifiedName)) && !(o is XmlNode[]) && (t != typeof(byte[]))) + if (Type.GetTypeCode(t) == TypeCode.Object && o is not Guid && (t != typeof(XmlQualifiedName)) && o is not XmlNode[] && (t != typeof(byte[]))) { if ((suppressReference || _soap12) && !IsIdDefined(o)) { @@ -2323,10 +2323,10 @@ internal void GenerateBegin() if (!mapping.IsSoap) continue; - if (mapping is StructMapping) - WriteStructMethod((StructMapping)mapping); - else if (mapping is EnumMapping) - WriteEnumMethod((EnumMapping)mapping); + if (mapping is StructMapping structMapping) + WriteStructMethod(structMapping); + else if (mapping is EnumMapping enumMapping) + WriteEnumMethod(enumMapping); } } } @@ -2338,13 +2338,13 @@ internal override void GenerateMethod(TypeMapping mapping) return; GeneratedMethods[mapping] = mapping; - if (mapping is StructMapping) + if (mapping is StructMapping structMapping) { - WriteStructMethod((StructMapping)mapping); + WriteStructMethod(structMapping); } - else if (mapping is EnumMapping) + else if (mapping is EnumMapping enumMapping) { - WriteEnumMethod((EnumMapping)mapping); + WriteEnumMethod(enumMapping); } } @@ -2364,10 +2364,10 @@ internal void GenerateEnd() return null; if (!xmlMapping.GenerateSerializer) throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); - if (xmlMapping is XmlTypeMapping) - return GenerateTypeElement((XmlTypeMapping)xmlMapping); - else if (xmlMapping is XmlMembersMapping) - return GenerateMembersElement((XmlMembersMapping)xmlMapping); + if (xmlMapping is XmlTypeMapping xmlTypeMapping) + return GenerateTypeElement(xmlTypeMapping); + else if (xmlMapping is XmlMembersMapping xmlMembersMapping) + return GenerateMembersElement(xmlMembersMapping); else throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); } @@ -2496,7 +2496,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; if (hasDefault) { - if (mapping is EnumMapping) + if (mapping is EnumMapping enumMapping) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe @@ -2509,7 +2509,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa else Writer.Write(source); Writer.Write(" != "); - if (((EnumMapping)mapping).IsFlags) + if (enumMapping.IsFlags) { Writer.Write("("); string[] values = ((string)defaultValue!).Split(null); @@ -2519,13 +2519,13 @@ private void WritePrimitive(string method, string name, string? ns, object? defa continue; if (i > 0) Writer.WriteLine(" | "); - Writer.Write(RaCodeGen.GetStringForEnumCompare((EnumMapping)mapping, values[i], mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForEnumCompare(enumMapping, values[i], mapping.TypeDesc.UseReflection)); } Writer.Write(")"); } else { - Writer.Write(RaCodeGen.GetStringForEnumCompare((EnumMapping)mapping, (string)defaultValue!, mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForEnumCompare(enumMapping, (string)defaultValue!, mapping.TypeDesc.UseReflection)); } Writer.Write(")"); } @@ -2548,9 +2548,9 @@ private void WritePrimitive(string method, string name, string? ns, object? defa Writer.Write(", "); - if (mapping is EnumMapping) + if (mapping is EnumMapping enumMapping2) { - WriteEnumValue((EnumMapping)mapping, source); + WriteEnumValue(enumMapping2, source); } else { @@ -3450,8 +3450,8 @@ private void WriteMember(string source, AttributeAccessor attribute, TypeDesc me Writer.WriteLine("if (i != 0) sb.Append(\" \");"); Writer.Write("sb.Append("); } - if (attribute.Mapping is EnumMapping) - WriteEnumValue((EnumMapping)attribute.Mapping, "ai"); + if (attribute.Mapping is EnumMapping enumMapping) + WriteEnumValue(enumMapping, "ai"); else WritePrimitiveValue(arrayElementTypeDesc, "ai"); Writer.WriteLine(");"); @@ -3958,7 +3958,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa { string name = writeAccessor ? element.Name : element.Mapping!.TypeName!; string? ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping!.Namespace) : ""); - if (element.Mapping is NullableMapping) + if (element.Mapping is NullableMapping nullableMapping) { Writer.Write("if ("); Writer.Write(source); @@ -3969,7 +3969,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa if (!element.Mapping.TypeDesc.BaseTypeDesc.UseReflection) castedSource = $"(({fullTypeName}){source})"; ElementAccessor e = element.Clone(); - e.Mapping = ((NullableMapping)element.Mapping).BaseMapping; + e.Mapping = nullableMapping.BaseMapping; WriteElement(e.Any ? source : castedSource, e, arrayName, writeAccessor); Writer.Indent--; Writer.WriteLine("}"); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs index ea3c307d9e7dac..c8495bc7c7ea0e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs @@ -50,13 +50,13 @@ internal override void GenerateMethod(TypeMapping mapping) if (!GeneratedMethods.Add(mapping)) return; - if (mapping is StructMapping) + if (mapping is StructMapping structMapping) { - WriteStructMethod((StructMapping)mapping); + WriteStructMethod(structMapping); } - else if (mapping is EnumMapping) + else if (mapping is EnumMapping enumMapping) { - WriteEnumMethod((EnumMapping)mapping); + WriteEnumMethod(enumMapping); } } @@ -75,10 +75,10 @@ internal Type GenerateEnd() return null; if (!xmlMapping.GenerateSerializer) throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); - if (xmlMapping is XmlTypeMapping) - return GenerateTypeElement((XmlTypeMapping)xmlMapping); - else if (xmlMapping is XmlMembersMapping) - return GenerateMembersElement((XmlMembersMapping)xmlMapping); + if (xmlMapping is XmlTypeMapping xmlTypeMapping) + return GenerateTypeElement(xmlTypeMapping); + else if (xmlMapping is XmlMembersMapping xmlMembersMapping) + return GenerateMembersElement(xmlMembersMapping); else throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); } @@ -194,7 +194,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; if (hasDefault) { - if (mapping is EnumMapping) + if (mapping is EnumMapping enumMapping) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe @@ -203,7 +203,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa source.Load(mapping.TypeDesc!.Type!); string? enumDefaultValue = null; - if (((EnumMapping)mapping).IsFlags) + if (enumMapping.IsFlags) { string[] values = ((string)defaultValue!).Split(null); for (int i = 0; i < values.Length; i++) @@ -238,9 +238,9 @@ private void WritePrimitive(string method, string name, string? ns, object? defa } Type argType; - if (mapping is EnumMapping) + if (mapping is EnumMapping enumMapping2) { - WriteEnumValue((EnumMapping)mapping, source, out argType); + WriteEnumValue(enumMapping2, source, out argType); argTypes.Add(argType); } else @@ -784,9 +784,9 @@ private void WriteEnumAndArrayTypes() { foreach (Mapping m in scope.TypeMappings) { - if (m is EnumMapping) + if (m is EnumMapping enumMapping) { - EnumMapping mapping = (EnumMapping)m; + EnumMapping mapping = enumMapping; ilg.InitElseIf(); WriteTypeCompare("t", mapping.TypeDesc!.Type!); // WriteXXXTypeCompare leave bool on the stack @@ -1260,8 +1260,8 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes methodName = "Append"; methodType = typeof(StringBuilder); } - if (attribute.Mapping is EnumMapping) - WriteEnumValue((EnumMapping)attribute.Mapping, new SourceInfo(aiVar, aiVar, null, arrayElementTypeDesc.Type, ilg), out argType); + if (attribute.Mapping is EnumMapping enumMapping) + WriteEnumValue(enumMapping, new SourceInfo(aiVar, aiVar, null, arrayElementTypeDesc.Type, ilg), out argType); else WritePrimitiveValue(arrayElementTypeDesc, new SourceInfo(aiVar, aiVar, null, arrayElementTypeDesc.Type, ilg), out argType); MethodInfo method = methodType.GetMethod( @@ -1852,9 +1852,9 @@ private void WriteText(SourceInfo source, TextAccessor text) { Type argType; ilg.Ldarg(0); - if (text.Mapping is EnumMapping) + if (text.Mapping is EnumMapping enumMapping) { - WriteEnumValue((EnumMapping)text.Mapping, source, out argType); + WriteEnumValue(enumMapping, source, out argType); } else { @@ -1897,7 +1897,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr { string name = writeAccessor ? element.Name : element.Mapping!.TypeName!; string? ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping!.Namespace) : ""); - if (element.Mapping is NullableMapping) + if (element.Mapping is NullableMapping nullableMapping) { if (source.Type == element.Mapping.TypeDesc!.Type) { @@ -1918,7 +1918,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr ilg.If(); SourceInfo castedSource = source.CastTo(element.Mapping.TypeDesc.BaseTypeDesc!); ElementAccessor e = element.Clone(); - e.Mapping = ((NullableMapping)element.Mapping).BaseMapping; + e.Mapping = nullableMapping.BaseMapping; WriteElement(e.Any ? source : castedSource, e, arrayName, writeAccessor); if (element.IsNullable) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs index c7edf3d604e6df..cad3e7c1d728bb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs @@ -60,8 +60,8 @@ internal bool toBoolean(XPathNodeIterator nodeIterator) if (str != null) return toBoolean(str); - if (result is double) return toBoolean((double)result); - if (result is bool) return (bool)result; + if (result is double d) return toBoolean(d); + if (result is bool b) return b; Debug.Assert(result is XPathNavigator, "Unknown value type"); return true; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs index b3e7b72a1b9dcb..54e653ed9a6f3f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs @@ -80,7 +80,7 @@ public override int CurrentPosition if (value is double) return value; if (value is bool) return value; if (value is XPathNavigator) return value; - if (value is int) return (double)(int)value; + if (value is int num) return (double)num; if (value == null) { @@ -109,13 +109,13 @@ public override int CurrentPosition return navigable.CreateNavigator(); } - if (value is short) return (double)(short)value; - if (value is long) return (double)(long)value; - if (value is uint) return (double)(uint)value; - if (value is ushort) return (double)(ushort)value; - if (value is ulong) return (double)(ulong)value; - if (value is float) return (double)(float)value; - if (value is decimal) return (double)(decimal)value; + if (value is short num2) return (double)num2; + if (value is long num3) return (double)num3; + if (value is uint num4) return (double)num4; + if (value is ushort num5) return (double)num5; + if (value is ulong num6) return (double)num6; + if (value is float f) return (double)f; + if (value is decimal d) return (double)d; return value.ToString()!; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FilterQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FilterQuery.cs index ee3256af0ab273..d467a0c61198c5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FilterQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FilterQuery.cs @@ -65,9 +65,9 @@ internal bool EvaluatePredicate() { object value = _cond.Evaluate(qyInput); if (value is XPathNodeIterator) return _cond.Advance() != null; - if (value is string) return ((string)value).Length != 0; - if (value is double) return (((double)value) == qyInput.CurrentPosition); - if (value is bool) return (bool)value; + if (value is string str) return str.Length != 0; + if (value is double d) return (d == qyInput.CurrentPosition); + if (value is bool b) return b; Debug.Assert(value is XPathNavigator, "Unknown value type"); return true; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs index 79972ea74fedc3..62be7e873d885b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs @@ -291,7 +291,7 @@ private Query ProcessFilter(Filter root, Flags flags, out Props props) { qyInput = new FilterQuery(qyInput, cond, /*noPosition:*/false); Query parent = _firstInput.qyInput; - if (!(parent is ContextQuery)) + if (parent is not ContextQuery) { // we don't need to wrap filter with MergeFilterQuery when cardinality is parent <: ? _firstInput.qyInput = new ContextQuery(); _firstInput = null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathParser.cs index 0605cc8c426d4a..8dcdf2daaa48a7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathParser.cs @@ -562,7 +562,7 @@ private Function ParseMethod(AstNode? qyInput) switch (pi.ArgTypes[i]) { case XPathResultType.NodeSet: - if (!(arg is Variable) && !(arg is Function && arg.ReturnType == XPathResultType.Any)) + if (arg is not Variable && !(arg is Function && arg.ReturnType == XPathResultType.Any)) { throw XPathException.Create(SR.Xp_InvalidArgumentType, name, _scanner.SourceText); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs index 82bc9c1fe89363..4a1373a0506445 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs @@ -298,7 +298,7 @@ protected override QilNode Visit(QilNode nd) return null!; // DebugInfo: Sequence point just before generating code for this expression - if (_qil.IsDebug && nd.SourceLine != null && !(nd is QilIterator)) + if (_qil.IsDebug && nd.SourceLine != null && nd is not QilIterator) _helper.DebugSequencePoint(nd.SourceLine); // Expressions are constructed using one of several possible methods diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs index 7480892901b501..18510f692f9d35 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs @@ -147,10 +147,10 @@ private void WriteXmlType(QilNode node) /// protected override QilNode VisitChildren(QilNode node) { - if (node is QilLiteral) + if (node is QilLiteral qilLiteral) { // If literal is not handled elsewhere, print its string value - this.writer.WriteValue(Convert.ToString(((QilLiteral)node).Value, CultureInfo.InvariantCulture)); + this.writer.WriteValue(Convert.ToString(qilLiteral.Value, CultureInfo.InvariantCulture)); return node; } else if (node is QilReference reference) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs index b5970115029241..66811048ae0069 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs @@ -48,9 +48,9 @@ internal XmlQueryContext(XmlQueryRuntime runtime, object defaultDataSource, XmlR _argList = argList; _wsRules = wsRules; - if (defaultDataSource is XmlReader) + if (defaultDataSource is XmlReader xmlReader) { - _readerSettings = new QueryReaderSettings((XmlReader)defaultDataSource); + _readerSettings = new QueryReaderSettings(xmlReader); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs index 64bc683fe941e7..40c789881a583a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs @@ -110,8 +110,8 @@ internal XmlRawWriter? Writer private void SetWrappedWriter(XmlRawWriter writer) { // Reuse XmlAttributeCache so that it doesn't have to be recreated every time - if (Writer is XmlAttributeCache) - _attrCache = (XmlAttributeCache)Writer; + if (Writer is XmlAttributeCache xmlAttributeCache) + _attrCache = xmlAttributeCache; Writer = writer; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs index 3ae6b73cb4d410..91fa2b72db4fcf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs @@ -210,9 +210,9 @@ public void DebugSetGlobalValue(string name, object value) { return item.TypedValue; } - else if (item is RtfNavigator) + else if (item is RtfNavigator rtfNavigator) { - return ((RtfNavigator)item).ToNavigator(); + return rtfNavigator.ToNavigator(); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs index 77988ad4f8dc61..ae986d821da9fe 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs @@ -82,7 +82,7 @@ protected int BreakSortingTie(XmlSortKey that) protected int CompareToEmpty(object? obj) { XmlEmptySortKey? that = obj as XmlEmptySortKey; - Debug.Assert(that != null && !(this is XmlEmptySortKey)); + Debug.Assert(that != null && this is not XmlEmptySortKey); return that.IsEmptyGreatest ? -1 : 1; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs index 841b4bf8ae795c..32493144db5a6f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs @@ -89,7 +89,7 @@ public static bool CannotBeNodeSet(QilNode n) { XmlQueryType xt = n.XmlType!; // Do not report compile error if n is a VarPar, whose inferred type forbids nodes (SQLBUDT 339398) - return xt.IsAtomicValue && !xt.IsEmpty && !(n is QilIterator); + return xt.IsAtomicValue && !xt.IsEmpty && n is not QilIterator; } public QilNode SafeDocOrderDistinct(QilNode n) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryCardinality.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryCardinality.cs index 832791a32b9853..2b41e00fe6fb05 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryCardinality.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryCardinality.cs @@ -122,9 +122,9 @@ public bool Equals(XmlQueryCardinality other) /// public override bool Equals([NotNullWhen(true)] object? other) { - if (other is XmlQueryCardinality) + if (other is XmlQueryCardinality xmlQueryCardinality) { - return Equals((XmlQueryCardinality)other); + return Equals(xmlQueryCardinality); } return false; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs index 56ab87994828a0..91f82a65976df7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs @@ -142,7 +142,7 @@ protected override QilNode VisitReference(QilNode n) } // If prevArg is not an iterator, cache it in an iterator, and return it - if (!(_invokeArgs[prevArg] is QilIterator)) + if (_invokeArgs[prevArg] is not QilIterator) { QilIterator var = _fac.BaseFactory.Let(_invokeArgs[prevArg]); _iterStack.Push(var); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs index 20e82a4a9374e4..d8ebfa2a52f661 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs @@ -581,18 +581,18 @@ internal NavigatorInput ResolveDocument(Uri absoluteUri) object? input = _xmlResolver.GetEntity(absoluteUri, null, null); string resolved = absoluteUri.ToString(); - if (input is Stream) + if (input is Stream stream) { - XmlTextReaderImpl tr = new XmlTextReaderImpl(resolved, (Stream)input); + XmlTextReaderImpl tr = new XmlTextReaderImpl(resolved, stream); { tr.XmlResolver = _xmlResolver; } // reader is closed by Compiler.LoadDocument() return new NavigatorInput(Compiler.LoadDocument(tr).CreateNavigator(), resolved, _rootScope); } - else if (input is XPathNavigator) + else if (input is XPathNavigator xPathNavigator) { - return new NavigatorInput((XPathNavigator)input, resolved, _rootScope); + return new NavigatorInput(xPathNavigator, resolved, _rootScope); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs index 67fe7f2276ab01..b9c0057a7b93d5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs @@ -60,9 +60,9 @@ internal void setGroupingSize(int sizeGroup) { double dblVal; - if (value is int) + if (value is int num) { - dblVal = (int)value; + dblVal = num; } else { @@ -368,7 +368,7 @@ private static object SimplifyValue(object value) // so we need intermediate string value. // If it's already a double we would like to keep it as double. // So this function converts to string only if result is nodeset or RTF - Debug.Assert(!(value is int)); + Debug.Assert(value is not int); if (Type.GetTypeCode(value.GetType()) == TypeCode.Object) { XPathNodeIterator? nodeset = value as XPathNodeIterator; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs index b2c1254412ce50..64ee13dbd79244 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs @@ -174,18 +174,18 @@ internal XPathNavigator GetNavigator(Uri ruri) } object? input = _resolver.GetEntity(ruri, null, null); - if (input is Stream) + if (input is Stream stream) { - XmlTextReaderImpl tr = new XmlTextReaderImpl(ruri.ToString(), (Stream)input); + XmlTextReaderImpl tr = new XmlTextReaderImpl(ruri.ToString(), stream); { tr.XmlResolver = _resolver; } // reader is closed by Compiler.LoadDocument() result = ((IXPathNavigable)Compiler.LoadDocument(tr)).CreateNavigator(); } - else if (input is XPathNavigator) + else if (input is XPathNavigator xPathNavigator) { - result = (XPathNavigator)input; + result = xPathNavigator; } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs index e4925381fe629c..81128297cc6546 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs @@ -200,13 +200,13 @@ private void CheckAttributeSets_RecurceInContainer(Hashtable markTable, Containe } foreach (Action action in container.containedActions) { - if (action is UseAttributeSetsAction) + if (action is UseAttributeSetsAction useAttributeSetsAction) { - CheckAttributeSets_RecurceInList(markTable, ((UseAttributeSetsAction)action).UsedSets!); + CheckAttributeSets_RecurceInList(markTable, useAttributeSetsAction.UsedSets!); } - else if (action is ContainerAction) + else if (action is ContainerAction containerAction) { - CheckAttributeSets_RecurceInContainer(markTable, (ContainerAction)action); + CheckAttributeSets_RecurceInContainer(markTable, containerAction); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateAction.cs index fb891888296dce..1fedc9fa3c9afd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateAction.cs @@ -136,7 +136,7 @@ private void AnalyzePriority(Compiler compiler) UnionExpr? union; while ((union = query as UnionExpr) != null) { - Debug.Assert(!(union.qy2 is UnionExpr), "only qy1 can be union"); + Debug.Assert(union.qy2 is not UnionExpr, "only qy1 can be union"); TemplateAction copy = this.CloneWithoutName(); compiler.QueryStore.Add(new TheQuery( new CompiledXpathExpr(union.qy2, expr.Expression, false), diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs index bdd2e16bf285ac..662a15780ca541 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs @@ -919,7 +919,7 @@ public override object Invoke(XsltContext xsltContext, object[] args, XPathNavig } Debug.Assert(resultCollection.Count != 0); Debug.Assert(newList.Count != 0); - if (!(resultCollection[0] is ArrayList)) + if (resultCollection[0] is not ArrayList) { // Transform resultCollection from ArrayList(XPathNavigator) to ArrayList(ArrayList(XPathNavigator)) Debug.Assert(resultCollection[0] is XPathNavigator); diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs index 8964532a481896..a56cb13ea7c2aa 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs @@ -34,7 +34,7 @@ public T Project(T value, Func project) if (NeedsProjection(value)) { // NeedsProjection should guarantee this. - Debug.Assert(!(value is IProjectable) || ((IProjectable)value).Projector != this); + Debug.Assert(value is not IProjectable || ((IProjectable)value).Projector != this); return project(value); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs index f170f67573d5cb..dee3f79c6182af 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs @@ -88,7 +88,7 @@ internal unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions utf8Decoder ??= MetadataStringDecoder.DefaultUTF8; - if (!(utf8Decoder.Encoding is UTF8Encoding)) + if (utf8Decoder.Encoding is not UTF8Encoding) { Throw.InvalidArgument(SR.MetadataStringDecoderEncodingMustBeUtf8, nameof(utf8Decoder)); } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs index 4f0ec58549b67f..ad1327c595a22b 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs @@ -265,7 +265,7 @@ public static bool HasSameMetadataDefinitionAsCore(this M thisMember, MemberI ArgumentNullException.ThrowIfNull(other); // Ensure that "other" is one of our MemberInfo objects. Do this check before calling any methods on it! - if (!(other is M)) + if (other is not M) return false; if (thisMember.MetadataToken != other.MetadataToken) diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs index 10449accd7ce9c..778030eda3122e 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs @@ -103,14 +103,14 @@ internal void InitSerialize(object obj, ISurrogateSelector? surrogateSelector, S } InitSiWrite(); } - else if (obj is ISerializable) + else if (obj is ISerializable serializable) { if (!_objectType.IsSerializable) { throw new SerializationException(SR.Format(SR.Serialization_NonSerType, _objectType.FullName, _objectType.Assembly.FullName)); } _si = new SerializationInfo(_objectType, converter); - ((ISerializable)obj).GetObjectData(_si, context); + serializable.GetObjectData(_si, context); InitSiWrite(); CheckTypeForwardedFrom(_cache, _objectType, _binderAssemblyString); } @@ -724,9 +724,9 @@ private int Position(string? name) // Retrieves the member type from the MemberInfo internal Type GetMemberType(MemberInfo objMember) { - if (objMember is FieldInfo) + if (objMember is FieldInfo fieldInfo) { - return ((FieldInfo)objMember).FieldType; + return fieldInfo.FieldType; } throw new SerializationException(SR.Format(SR.Serialization_SerMemberInfo, objMember.GetType())); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs index 2e6620a3c13f75..265c207b5a8167 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs @@ -78,9 +78,9 @@ internal void Serialize(object graph, BinaryFormatterWriter serWriter) // GetNext will return either an object or a WriteObjectInfo. // A WriteObjectInfo is returned if this object was member of another object - if (obj is WriteObjectInfo) + if (obj is WriteObjectInfo writeObjectInfo) { - objectInfo = (WriteObjectInfo)obj; + objectInfo = writeObjectInfo; } else { diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs index 6d94a23dc8fcd3..a7261292fd9071 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs @@ -340,7 +340,7 @@ private bool DoValueTypeFixup(FieldInfo? memberToFix, ObjectHolder holder, objec //If the outermost container isn't an array, we need to grab it. Otherwise, we just need to hang onto //the boxed object that we already grabbed. We'll assign the boxed object back into the array as the //last step. - if (!(holder.ObjectValue is Array) && holder.ObjectValue != null) + if (holder.ObjectValue is not Array && holder.ObjectValue != null) { fixupObj = holder.ObjectValue; Debug.Assert(fixupObj != null, "[ObjectManager.DoValueTypeFixup]FixupObj!=null"); @@ -510,7 +510,7 @@ internal void CompleteObject(ObjectHolder holder, bool bObjectFullyComplete) Debug.Assert(fixupInfo is MemberInfo); //Fixup the member directly. MemberInfo tempMember = (MemberInfo)fixupInfo; - if (tempMember is FieldInfo) + if (tempMember is FieldInfo fieldInfo) { // If we have a valuetype that's been boxed to an object and requires a fixup, // there are two possible states: @@ -523,7 +523,7 @@ internal void CompleteObject(ObjectHolder holder, bool bObjectFullyComplete) // to true when we do this. if (holder.RequiresValueTypeFixup && holder.ValueTypeFixupPerformed) { - if (!DoValueTypeFixup((FieldInfo)tempMember, holder, tempObjectHolder.ObjectValue)) + if (!DoValueTypeFixup(fieldInfo, holder, tempObjectHolder.ObjectValue)) { throw new SerializationException(SR.Serialization_PartialValueTypeFixup); } @@ -667,7 +667,7 @@ public void RegisterObject(object obj, long objectID, SerializationInfo? info, l { throw new ArgumentOutOfRangeException(nameof(objectID), SR.ArgumentOutOfRange_ObjectID); } - if (member != null && !(member is FieldInfo)) // .NET Framework checks specifically for RuntimeFieldInfo and SerializationFieldInfo, but the former is an implementation detail in corelib + if (member != null && member is not FieldInfo) // .NET Framework checks specifically for RuntimeFieldInfo and SerializationFieldInfo, but the former is an implementation detail in corelib { throw new SerializationException(SR.Serialization_UnknownMemberInfo); } @@ -687,9 +687,9 @@ public void RegisterObject(object obj, long objectID, SerializationInfo? info, l } //The object is interested in DeserializationEvents so lets register it. - if (obj is IDeserializationCallback) + if (obj is IDeserializationCallback deserializationCallback) { - DeserializationEventHandler d = new DeserializationEventHandler(((IDeserializationCallback)obj).OnDeserialization); + DeserializationEventHandler d = new DeserializationEventHandler(deserializationCallback.OnDeserialization); AddOnDeserialization(d); } @@ -774,7 +774,7 @@ internal void CompleteISerializableObject(object obj, SerializationInfo? info, S { ArgumentNullException.ThrowIfNull(obj); - if (!(obj is ISerializable)) + if (obj is not ISerializable) { throw new ArgumentException(SR.Serialization_NotISer); } @@ -861,9 +861,9 @@ public virtual void DoFixups() //If our count is 0, we're done and should just return if (_fixupCount == 0) { - if (TopObject is TypeLoadExceptionHolder) + if (TopObject is TypeLoadExceptionHolder typeLoadExceptionHolder) { - throw new SerializationException(SR.Format(SR.Serialization_TypeLoadFailure, ((TypeLoadExceptionHolder)TopObject).TypeName)); + throw new SerializationException(SR.Format(SR.Serialization_TypeLoadFailure, typeLoadExceptionHolder.TypeName)); } return; } @@ -929,7 +929,7 @@ public virtual void RecordFixup(long objectToBeFixed, MemberInfo member, long ob throw new ArgumentOutOfRangeException(objectToBeFixed <= 0 ? nameof(objectToBeFixed) : nameof(objectRequired), SR.Serialization_IdTooSmall); } ArgumentNullException.ThrowIfNull(member); - if (!(member is FieldInfo)) // .NET Framework checks specifically for RuntimeFieldInfo and SerializationFieldInfo, but the former is an implementation detail in corelib + if (member is not FieldInfo) // .NET Framework checks specifically for RuntimeFieldInfo and SerializationFieldInfo, but the former is an implementation detail in corelib { throw new SerializationException(SR.Format(SR.Serialization_InvalidType, member.GetType())); } @@ -1056,9 +1056,9 @@ internal ObjectHolder( _surrogate = surrogate; _markForFixupWhenAvailable = false; - if (obj is TypeLoadExceptionHolder) + if (obj is TypeLoadExceptionHolder typeLoadExceptionHolder) { - _typeLoad = (TypeLoadExceptionHolder)obj; + _typeLoad = typeLoadExceptionHolder; } if (idOfContainingObj != 0 && ((field != null && field.FieldType.IsValueType) || arrayIndex != null)) @@ -1327,9 +1327,9 @@ internal void SetObjectValue(object? obj, ObjectManager manager) { _reachable = true; } - if (obj is TypeLoadExceptionHolder) + if (obj is TypeLoadExceptionHolder typeLoadExceptionHolder) { - _typeLoad = (TypeLoadExceptionHolder)obj; + _typeLoad = typeLoadExceptionHolder; } if (_markForFixupWhenAvailable) diff --git a/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/DiagnosticUtility.cs b/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/DiagnosticUtility.cs index 46b0dde85c686b..a897ffee1ed619 100644 --- a/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/DiagnosticUtility.cs +++ b/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/DiagnosticUtility.cs @@ -15,7 +15,7 @@ public static bool IsFatal(Exception exception) while (exception != null) { // NetFx checked for FatalException and FatalInternalException as well, which were ServiceModel constructs. - if ((exception is OutOfMemoryException && !(exception is InsufficientMemoryException)) || + if ((exception is OutOfMemoryException && exception is not InsufficientMemoryException) || exception is ThreadAbortException) { return true; @@ -29,12 +29,12 @@ public static bool IsFatal(Exception exception) { exception = exception.InnerException!; } - else if (exception is AggregateException) + else if (exception is AggregateException aggregateException) { // AggregateExceptions have a collection of inner exceptions, which may themselves be other // wrapping exceptions (including nested AggregateExceptions). Recursively walk this // hierarchy. The (singular) InnerException is included in the collection. - var innerExceptions = ((AggregateException)exception).InnerExceptions; + var innerExceptions = aggregateException.InnerExceptions; foreach (Exception innerException in innerExceptions) { if (IsFatal(innerException)) diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs index f720693a77d219..06b4cdef304fbe 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs @@ -280,7 +280,7 @@ public static GenericAce CreateFromBinaryForm(byte[] binaryForm, int offset) // As a final check, confirm that the advertised ACE header length // was the actual parsed length - if (((!(result is ObjectAce)) && ((binaryForm[offset + 2] << 0) + (binaryForm[offset + 3] << 8) != result.BinaryLength)) + if (((result is not ObjectAce) && ((binaryForm[offset + 2] << 0) + (binaryForm[offset + 3] << 8) != result.BinaryLength)) // This is needed because object aces created through ADSI have the advertised ACE length // greater than the actual length by 32 (bug in ADSI). || ((result is ObjectAce) && ((binaryForm[offset + 2] << 0) + (binaryForm[offset + 3] << 8) != result.BinaryLength) && (((binaryForm[offset + 2] << 0) + (binaryForm[offset + 3] << 8) - 32) != result.BinaryLength))) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs index f8564b06eaaba8..0db794662f6929 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs @@ -51,8 +51,8 @@ internal CanonicalXml(XmlNodeList nodeList, XmlResolver? resolver, bool includeC private static void MarkNodeAsIncluded(XmlNode node) { - if (node is ICanonicalizableNode) - ((ICanonicalizableNode)node).IsInNodeSet = true; + if (node is ICanonicalizableNode canonicalizableNode) + canonicalizableNode.IsInNodeSet = true; } private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument inputRoot, XmlDocument root) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlNodeList.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlNodeList.cs index 35dd40e3cfcd9f..13b8f932984fbb 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlNodeList.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlNodeList.cs @@ -33,7 +33,7 @@ public override int Count // IList methods public int Add(object? value) { - if (!(value is XmlNode)) + if (value is not XmlNode) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, "node"); return _nodeArray.Add(value); } @@ -55,7 +55,7 @@ public int IndexOf(object? value) public void Insert(int index, object? value) { - if (!(value is XmlNode)) + if (value is not XmlNode) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _nodeArray.Insert(index, value); } @@ -85,7 +85,7 @@ public bool IsReadOnly get { return _nodeArray[index]; } set { - if (!(value is XmlNode)) + if (value is not XmlNode) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _nodeArray[index] = value; } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs index edd847aa085a3b..084d94e4c461aa 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs @@ -442,8 +442,8 @@ public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string? symme throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); } // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table - if (kek is SymmetricAlgorithm) - return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)kek); + if (kek is SymmetricAlgorithm symmetricAlgorithm) + return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, symmetricAlgorithm); // kek is an RSA key: get fOAEP from the algorithm, default to false fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl); @@ -536,7 +536,7 @@ public void AddKeyNameMapping(string keyName, object keyObject) ArgumentNullException.ThrowIfNull(keyName); ArgumentNullException.ThrowIfNull(keyObject); - if (!(keyObject is SymmetricAlgorithm) && !(keyObject is RSA)) + if (keyObject is not SymmetricAlgorithm && keyObject is not RSA) throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform); _keyNameMapping.Add(keyName, keyObject); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionPropertyCollection.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionPropertyCollection.cs index 6246b541f61b96..fbb45c1d9503a0 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionPropertyCollection.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionPropertyCollection.cs @@ -27,7 +27,7 @@ public int Count /// int IList.Add(object? value) { - if (!(value is EncryptionProperty)) + if (value is not EncryptionProperty) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); return _props.Add(value); @@ -46,7 +46,7 @@ public void Clear() /// bool IList.Contains(object? value) { - if (!(value is EncryptionProperty)) + if (value is not EncryptionProperty) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); return _props.Contains(value); @@ -60,7 +60,7 @@ public bool Contains(EncryptionProperty value) /// int IList.IndexOf(object? value) { - if (!(value is EncryptionProperty)) + if (value is not EncryptionProperty) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); return _props.IndexOf(value); @@ -74,7 +74,7 @@ public int IndexOf(EncryptionProperty value) /// void IList.Insert(int index, object? value) { - if (!(value is EncryptionProperty)) + if (value is not EncryptionProperty) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _props.Insert(index, value); @@ -88,7 +88,7 @@ public void Insert(int index, EncryptionProperty value) /// void IList.Remove(object? value) { - if (!(value is EncryptionProperty)) + if (value is not EncryptionProperty) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _props.Remove(value); @@ -138,7 +138,7 @@ public EncryptionProperty this[int index] get { return _props[index]; } set { - if (!(value is EncryptionProperty)) + if (value is not EncryptionProperty) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _props[index] = value; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs index 9541f24bf224f0..ddd65dc083fe86 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs @@ -107,8 +107,8 @@ private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument private static void MarkNodeAsIncluded(XmlNode node) { - if (node is ICanonicalizableNode) - ((ICanonicalizableNode)node).IsInNodeSet = true; + if (node is ICanonicalizableNode canonicalizableNode) + canonicalizableNode.IsInNodeSet = true; } } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs index 79c6750bcb0fc7..9eb0779ab48c2a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs @@ -263,7 +263,7 @@ public void LoadXml(XmlElement value) // let the transform read the children of the transformElement for data transform.LoadInnerXml(transformElement.ChildNodes); // Hack! this is done to get around the lack of here() function support in XPath - if (transform is XmlDsigEnvelopedSignatureTransform) + if (transform is XmlDsigEnvelopedSignatureTransform xmlDsigEnvelopedSignatureTransform) { // Walk back to the Signature tag. Find the nearest signature ancestor // Signature-->SignedInfo-->Reference-->Transforms-->Transform @@ -298,7 +298,7 @@ public void LoadXml(XmlElement value) position++; if (node == signatureTag) { - ((XmlDsigEnvelopedSignatureTransform)transform).SignaturePosition = position; + xmlDsigEnvelopedSignatureTransform.SignaturePosition = position; break; } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs index b90981c89a29ad..bd8204ae36307d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs @@ -29,7 +29,7 @@ public int Add(object? value) { ArgumentNullException.ThrowIfNull(value); - if (!(value is DataReference) && !(value is KeyReference)) + if (value is not DataReference && value is not KeyReference) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); return _references.Add(value); @@ -55,7 +55,7 @@ public void Insert(int index, object? value) { ArgumentNullException.ThrowIfNull(value); - if (!(value is DataReference) && !(value is KeyReference)) + if (value is not DataReference && value is not KeyReference) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _references.Insert(index, value); @@ -99,7 +99,7 @@ public EncryptedReference this[int index] if (value == null) throw new ArgumentNullException(nameof(value)); - if (!(value is DataReference) && !(value is KeyReference)) + if (value is not DataReference && value is not KeyReference) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); _references[index] = value; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs index 336bc1d7ed1c06..8fd49988088ab1 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs @@ -136,15 +136,15 @@ internal Stream TransformToOctetStream(object? inputObject, XmlResolver? resolve { return inputStream; } - if (currentInput is XmlNodeList) + if (currentInput is XmlNodeList xmlNodeList) { - CanonicalXml c14n = new CanonicalXml((XmlNodeList)currentInput, resolver, false); + CanonicalXml c14n = new CanonicalXml(xmlNodeList, resolver, false); MemoryStream? ms = new MemoryStream(c14n.GetBytes()); return ms; } - if (currentInput is XmlDocument) + if (currentInput is XmlDocument xmlDocument) { - CanonicalXml c14n = new CanonicalXml((XmlDocument)currentInput, resolver); + CanonicalXml c14n = new CanonicalXml(xmlDocument, resolver); MemoryStream? ms = new MemoryStream(c14n.GetBytes()); return ms; } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs index 9cae83b813411e..d0281b7fe267fb 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs @@ -261,7 +261,7 @@ internal static XmlNodeList AllDescendantNodes(XmlNode node, bool includeComment { foreach (XmlNode node1 in childNodes) { - if (includeComments || (!(node1 is XmlComment))) + if (includeComments || (node1 is not XmlComment)) { elementList.Add(node1); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs index 9289c7a6834de3..1af68dbca8f47d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs @@ -134,13 +134,13 @@ public override void LoadInnerXml(XmlNodeList nodeList) public override void LoadInput(object obj) { - if (obj is Stream) + if (obj is Stream stream) { - LoadStreamInput((Stream)obj); + LoadStreamInput(stream); } - else if (obj is XmlDocument) + else if (obj is XmlDocument xmlDocument) { - LoadXmlDocumentInput((XmlDocument)obj); + LoadXmlDocumentInput(xmlDocument); } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs index bc1ec82d31b3be..38432ad38c0cef 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs @@ -40,19 +40,19 @@ public override void LoadInnerXml(XmlNodeList nodeList) public override void LoadInput(object obj) { - if (obj is Stream) + if (obj is Stream stream) { - LoadStreamInput((Stream)obj); + LoadStreamInput(stream); return; } - if (obj is XmlNodeList) + if (obj is XmlNodeList xmlNodeList) { - LoadXmlNodeListInput((XmlNodeList)obj); + LoadXmlNodeListInput(xmlNodeList); return; } - if (obj is XmlDocument) + if (obj is XmlDocument xmlDocument) { - LoadXmlNodeListInput(((XmlDocument)obj).SelectNodes("//.")!); + LoadXmlNodeListInput(xmlDocument.SelectNodes("//.")!); return; } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs index ea087bdb0f72c3..9ffdad6e12792d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigC14NTransform.cs @@ -48,19 +48,19 @@ public override void LoadInnerXml(XmlNodeList nodeList) public override void LoadInput(object obj) { XmlResolver resolver = ResolverSet ? _xmlResolver : XmlResolverHelper.GetThrowingResolver(); - if (obj is Stream) + if (obj is Stream stream) { - _cXml = new CanonicalXml((Stream)obj, _includeComments, resolver, BaseURI!); + _cXml = new CanonicalXml(stream, _includeComments, resolver, BaseURI!); return; } - if (obj is XmlDocument) + if (obj is XmlDocument xmlDocument) { - _cXml = new CanonicalXml((XmlDocument)obj, resolver, _includeComments); + _cXml = new CanonicalXml(xmlDocument, resolver, _includeComments); return; } - if (obj is XmlNodeList) + if (obj is XmlNodeList xmlNodeList) { - _cXml = new CanonicalXml((XmlNodeList)obj, resolver, _includeComments); + _cXml = new CanonicalXml(xmlNodeList, resolver, _includeComments); } else { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs index 59f2517ab58c27..3fa418fd2dab50 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs @@ -58,19 +58,19 @@ public override void LoadInnerXml(XmlNodeList nodeList) public override void LoadInput(object obj) { - if (obj is Stream) + if (obj is Stream stream) { - LoadStreamInput((Stream)obj); + LoadStreamInput(stream); return; } - if (obj is XmlNodeList) + if (obj is XmlNodeList xmlNodeList) { - LoadXmlNodeListInput((XmlNodeList)obj); + LoadXmlNodeListInput(xmlNodeList); return; } - if (obj is XmlDocument) + if (obj is XmlDocument xmlDocument) { - LoadXmlDocumentInput((XmlDocument)obj); + LoadXmlDocumentInput(xmlDocument); return; } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs index 844601a0adcac7..bbfe5dac58d586 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigExcC14NTransform.cs @@ -75,17 +75,17 @@ public override void LoadInnerXml(XmlNodeList nodeList) public override void LoadInput(object obj) { XmlResolver resolver = (ResolverSet ? _xmlResolver : XmlResolverHelper.GetThrowingResolver()); - if (obj is Stream) + if (obj is Stream stream) { - _excCanonicalXml = new ExcCanonicalXml((Stream)obj, _includeComments, _inclusiveNamespacesPrefixList!, resolver, BaseURI!); + _excCanonicalXml = new ExcCanonicalXml(stream, _includeComments, _inclusiveNamespacesPrefixList!, resolver, BaseURI!); } - else if (obj is XmlDocument) + else if (obj is XmlDocument xmlDocument) { - _excCanonicalXml = new ExcCanonicalXml((XmlDocument)obj, _includeComments, _inclusiveNamespacesPrefixList!, resolver); + _excCanonicalXml = new ExcCanonicalXml(xmlDocument, _includeComments, _inclusiveNamespacesPrefixList!, resolver); } - else if (obj is XmlNodeList) + else if (obj is XmlNodeList xmlNodeList) { - _excCanonicalXml = new ExcCanonicalXml((XmlNodeList)obj, _includeComments, _inclusiveNamespacesPrefixList!, resolver); + _excCanonicalXml = new ExcCanonicalXml(xmlNodeList, _includeComments, _inclusiveNamespacesPrefixList!, resolver); } else throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(obj)); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs index 136cb3285f9a5c..855d91a224da9a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXPathTransform.cs @@ -117,17 +117,17 @@ public override void LoadInnerXml(XmlNodeList nodeList) public override void LoadInput(object obj) { - if (obj is Stream) + if (obj is Stream stream) { - LoadStreamInput((Stream)obj); + LoadStreamInput(stream); } - else if (obj is XmlNodeList) + else if (obj is XmlNodeList xmlNodeList) { - LoadXmlNodeListInput((XmlNodeList)obj); + LoadXmlNodeListInput(xmlNodeList); } - else if (obj is XmlDocument) + else if (obj is XmlDocument xmlDocument) { - LoadXmlDocumentInput((XmlDocument)obj); + LoadXmlDocumentInput(xmlDocument); } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs index 8fea4f4d853476..ae25e638cef214 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigXsltTransform.cs @@ -83,22 +83,22 @@ public override void LoadInput(object obj) { _inputStream?.Close(); _inputStream = new MemoryStream(); - if (obj is Stream) + if (obj is Stream stream) { - _inputStream = (Stream)obj; + _inputStream = stream; } - else if (obj is XmlNodeList) + else if (obj is XmlNodeList xmlNodeList) { - CanonicalXml xmlDoc = new CanonicalXml((XmlNodeList)obj, null!, _includeComments); + CanonicalXml xmlDoc = new CanonicalXml(xmlNodeList, null!, _includeComments); byte[] buffer = xmlDoc.GetBytes(); if (buffer == null) return; _inputStream.Write(buffer, 0, buffer.Length); _inputStream.Flush(); _inputStream.Position = 0; } - else if (obj is XmlDocument) + else if (obj is XmlDocument xmlDocument) { - CanonicalXml xmlDoc = new CanonicalXml((XmlDocument)obj, null!, _includeComments); + CanonicalXml xmlDoc = new CanonicalXml(xmlDocument, null!, _includeComments); byte[] buffer = xmlDoc.GetBytes(); if (buffer == null) return; _inputStream.Write(buffer, 0, buffer.Length); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.cs index c5f357fe342993..26c0b6107d5942 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.cs @@ -183,14 +183,14 @@ private static string ConfirmedOidValue(IFindPal findPal, object findValue, OidG private static X509KeyUsageFlags ConfirmedX509KeyUsage(object findValue) { - if (findValue is X509KeyUsageFlags) - return (X509KeyUsageFlags)findValue; + if (findValue is X509KeyUsageFlags x509KeyUsageFlags) + return x509KeyUsageFlags; - if (findValue is int) - return (X509KeyUsageFlags)(int)findValue; + if (findValue is int num) + return (X509KeyUsageFlags)num; - if (findValue is uint) - return (X509KeyUsageFlags)(uint)findValue; + if (findValue is uint num2) + return (X509KeyUsageFlags)num2; if (findValue is string findValueString) { diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateCollection.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateCollection.cs index 9c342269a29b98..bc7162a3cf3496 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateCollection.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateCollection.cs @@ -108,7 +108,7 @@ protected override void OnValidate(object value) { base.OnValidate(value); - if (!(value is X509Certificate)) + if (value is not X509Certificate) throw new ArgumentException(SR.Arg_InvalidType, nameof(value)); } } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs index 6b315cc485e674..0e6e9ab7a3a17c 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs @@ -44,9 +44,9 @@ internal SyndicationElementExtensionCollection(SyndicationElementExtensionCollec [RequiresDynamicCode(SyndicationFeedFormatter.RequiresDynamicCodeWarning)] public void Add(object extension) { - if (extension is SyndicationElementExtension) + if (extension is SyndicationElementExtension syndicationElementExtension) { - base.Add((SyndicationElementExtension)extension); + base.Add(syndicationElementExtension); } else { diff --git a/src/libraries/System.Speech/src/Internal/SapiInterop/SapiRecognizer.cs b/src/libraries/System.Speech/src/Internal/SapiInterop/SapiRecognizer.cs index a47fbb37c7ad71..c48e8977fb55a6 100644 --- a/src/libraries/System.Speech/src/Internal/SapiInterop/SapiRecognizer.cs +++ b/src/libraries/System.Speech/src/Internal/SapiInterop/SapiRecognizer.cs @@ -202,9 +202,9 @@ private static void SetProperty(ISpRecognizer sapiRecognizer, string name, objec { SAPIErrorCodes errorCode; - if (value is int) + if (value is int num) { - errorCode = (SAPIErrorCodes)sapiRecognizer.SetPropertyNum(name, (int)value); + errorCode = (SAPIErrorCodes)sapiRecognizer.SetPropertyNum(name, num); } else { diff --git a/src/libraries/System.Speech/src/Internal/SrgsParser/XmlParser.cs b/src/libraries/System.Speech/src/Internal/SrgsParser/XmlParser.cs index c7964e6de7d9a5..2507e0cb8a6502 100644 --- a/src/libraries/System.Speech/src/Internal/SrgsParser/XmlParser.cs +++ b/src/libraries/System.Speech/src/Internal/SrgsParser/XmlParser.cs @@ -1317,7 +1317,7 @@ private bool ProcessChildNodes(XmlReader reader, IElement? parent, IRule rule, s switch (reader.LocalName) { case "example": - if (!(parent is IRule) || !fFirstElement) + if (parent is not IRule || !fFirstElement) { ThrowSrgsException(SRID.InvalidExampleOrdering); } diff --git a/src/libraries/System.Speech/src/Recognition/GrammarBuilder.cs b/src/libraries/System.Speech/src/Recognition/GrammarBuilder.cs index 653b614edd2831..6fd8f884973f5b 100644 --- a/src/libraries/System.Speech/src/Recognition/GrammarBuilder.cs +++ b/src/libraries/System.Speech/src/Recognition/GrammarBuilder.cs @@ -505,7 +505,7 @@ internal override GrammarBuilderBase Clone() // Create an item which represents the grammar foreach (GrammarBuilderBase item in Items) { - if (!(item is RuleElement)) + if (item is not RuleElement) { IElement? element = item.CreateElement(elementFactory, root, root, ruleIds);