From 228e54135043daf27c4ed250f6d1c3f54090062f Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Thu, 9 Jun 2022 17:54:06 -0400 Subject: [PATCH 1/3] Enable IDE0020 (Use pattern matching) --- eng/CodeAnalysis.src.globalconfig | 2 +- .../src/System/RuntimeTypeHandle.cs | 3 +- .../MissingMetadataExceptionCreator.cs | 7 +-- .../Runtime/TypeLoader/TypeBuilder.cs | 16 ++--- .../Runtime/TypeLoader/TypeBuilderState.cs | 4 +- ...peLoaderEnvironment.LdTokenResultLookup.cs | 6 +- .../Internal/TypeSystem/TypeDesc.Runtime.cs | 8 +-- .../TypeSystem/TypeSystemContext.Runtime.cs | 4 +- .../TypedParts/Discovery/DiscoveredPart.cs | 3 +- .../src/System/Data/ConstraintCollection.cs | 3 +- .../Data/DataColumnPropertyDescriptor.cs | 13 +--- .../src/System/Data/DataRelation.cs | 3 +- .../Data/DataRelationPropertyDescriptor.cs | 12 +--- .../Data/DataTablePropertyDescriptor.cs | 12 +--- .../src/System/Data/Filter/BinaryNode.cs | 3 +- .../src/System/Data/SQLTypes/SQLBinary.cs | 4 +- .../src/System/Data/SQLTypes/SQLBoolean.cs | 4 +- .../src/System/Data/SQLTypes/SQLByte.cs | 4 +- .../src/System/Data/SQLTypes/SQLDateTime.cs | 4 +- .../src/System/Data/SQLTypes/SQLDouble.cs | 4 +- .../src/System/Data/SQLTypes/SQLGuid.cs | 4 +- .../src/System/Data/SQLTypes/SQLInt16.cs | 4 +- .../src/System/Data/SQLTypes/SQLInt32.cs | 4 +- .../src/System/Data/SQLTypes/SQLInt64.cs | 4 +- .../src/System/Data/SQLTypes/SQLMoney.cs | 4 +- .../src/System/Data/SQLTypes/SQLSingle.cs | 4 +- .../src/System/Data/SQLTypes/SQLString.cs | 4 +- .../src/System/Data/SimpleType.cs | 4 +- .../src/System/Data/XMLSchema.cs | 20 +++--- .../src/System/Data/XmlDataLoader.cs | 3 +- .../src/System/Data/xmlsaver.cs | 12 +--- .../System.Data.OleDb/src/OleDbConnection.cs | 3 +- .../AccountManagement/StoreCtx.cs | 6 +- .../DirectoryServices/DirectoryEntry.cs | 24 ++----- .../Interpreter/InstructionList.cs | 3 +- .../Runtime/Serialization/AccessorBuilder.cs | 6 +- .../Serialization/ClassDataContract.cs | 4 +- .../Runtime/Serialization/CodeGenerator.cs | 9 +-- .../Runtime/Serialization/DataContract.cs | 9 +-- .../Runtime/Serialization/SchemaExporter.cs | 3 +- .../src/System/Xml/Schema/Preprocessor.cs | 27 +++----- .../Xml/Schema/SchemaCollectionCompiler.cs | 39 ++++-------- .../Schema/SchemaCollectionpreProcessor.cs | 53 ++++++---------- .../System/Xml/Schema/SchemaSetCompiler.cs | 42 +++++-------- .../System/Xml/Schema/XmlSchemaValidator.cs | 6 +- .../System/Xml/Serialization/CodeGenerator.cs | 9 +-- .../System/Xml/Serialization/ImportContext.cs | 31 ++++----- .../Xml/Serialization/SchemaObjectWriter.cs | 9 +-- .../Serialization/SoapReflectionImporter.cs | 3 +- .../src/System/Xml/Serialization/Types.cs | 3 +- .../System/Xml/Serialization/XmlAttributes.cs | 3 +- .../Serialization/XmlReflectionImporter.cs | 3 +- .../Xml/Serialization/XmlSchemaExporter.cs | 25 +++----- .../Xml/Serialization/XmlSchemaImporter.cs | 63 +++++++------------ .../System/Xml/Serialization/XmlSchemas.cs | 12 ++-- .../Serialization/XmlSerializationReader.cs | 42 ++++++------- .../XmlSerializationReaderILGen.cs | 40 +++++------- .../Serialization/XmlSerializationWriter.cs | 61 ++++++++---------- .../XmlSerializationWriterILGen.cs | 53 +++++++--------- .../System/Xml/Serialization/XmlSerializer.cs | 3 +- .../src/System/Xml/Xsl/QIL/QilXmlWriter.cs | 4 +- 61 files changed, 272 insertions(+), 512 deletions(-) diff --git a/eng/CodeAnalysis.src.globalconfig b/eng/CodeAnalysis.src.globalconfig index 51da5a2e70b97..e272d238b4d85 100644 --- a/eng/CodeAnalysis.src.globalconfig +++ b/eng/CodeAnalysis.src.globalconfig @@ -1356,7 +1356,7 @@ dotnet_diagnostic.IDE0018.severity = suggestion dotnet_diagnostic.IDE0019.severity = suggestion # IDE0020: Use pattern matching to avoid is check followed by a cast (with variable) -dotnet_diagnostic.IDE0020.severity = suggestion +dotnet_diagnostic.IDE0020.severity = warning # IDE0021: Use expression body for constructors dotnet_diagnostic.IDE0021.severity = silent diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs index 83fce9bcd1cc1..433ecd599297b 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs @@ -32,9 +32,8 @@ private RuntimeTypeHandle(IntPtr value) public override bool Equals(object? obj) { - if (obj is RuntimeTypeHandle) + if (obj is RuntimeTypeHandle handle) { - RuntimeTypeHandle handle = (RuntimeTypeHandle)obj; return Equals(handle); } return false; diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/MissingMetadataExceptionCreator.cs b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/MissingMetadataExceptionCreator.cs index 8b25905240d7b..9258531aa42fe 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/MissingMetadataExceptionCreator.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/MissingMetadataExceptionCreator.cs @@ -99,16 +99,13 @@ public static string ComputeUsefulPertainantIfPossible(object pertainant) return type.ToDisplayStringIfAvailable(null); } - if (pertainant is MemberInfo) + if (pertainant is MemberInfo memberInfo) { - MemberInfo memberInfo = (MemberInfo)pertainant; - StringBuilder friendlyName = new StringBuilder(memberInfo.DeclaringType.ToDisplayStringIfAvailable(null)); friendlyName.Append('.'); friendlyName.Append(memberInfo.Name); - if (pertainant is MethodBase) + if (pertainant is MethodBase method) { - MethodBase method = (MethodBase)pertainant; bool first; // write out generic parameters diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs index 1db84afc02197..ab1bbfba737a4 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs @@ -266,10 +266,8 @@ internal void PrepareType(TypeDesc type) bool noExtraPreparation = false; // Set this to true for types which don't need other types to be prepared. I.e GenericTypeDefinitions - if (type is DefType) + if (type is DefType typeAsDefType) { - DefType typeAsDefType = (DefType)type; - if (typeAsDefType.HasInstantiation) { if (typeAsDefType.IsTypeDefinition) @@ -305,10 +303,8 @@ internal void PrepareType(TypeDesc type) { PrepareType(((ParameterizedType)type).ParameterType); - if (type is ArrayType) + if (type is ArrayType typeAsArrayType) { - ArrayType typeAsArrayType = (ArrayType)type; - if (typeAsArrayType.IsSzArray && !typeAsArrayType.ElementType.IsPointer) { TypeDesc.ComputeTemplate(state); @@ -1326,10 +1322,8 @@ private void FinishRuntimeType(TypeDesc type) var state = type.GetTypeBuilderState(); - if (type is DefType) + if (type is DefType typeAsDefType) { - DefType typeAsDefType = (DefType)type; - if (type.HasInstantiation) { // Type definitions don't need any further finishing once created by the EETypeCreator @@ -1367,10 +1361,8 @@ private void FinishRuntimeType(TypeDesc type) } else if (type is ParameterizedType) { - if (type is ArrayType) + if (type is ArrayType typeAsSzArrayType) { - ArrayType typeAsSzArrayType = (ArrayType)type; - state.HalfBakedRuntimeTypeHandle.SetRelatedParameterType(GetRuntimeTypeHandle(typeAsSzArrayType.ElementType)); state.HalfBakedRuntimeTypeHandle.SetComponentSize(state.ComponentSize.Value); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs index 85037bae3fa1e..dcc81310178d8 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs @@ -973,10 +973,8 @@ public int? FieldAlignment { return checked((ushort)((DefType)TypeBeingBuilt).InstanceFieldAlignment.AsInt); } - else if (TypeBeingBuilt is ArrayType) + else if (TypeBeingBuilt is ArrayType arrayType) { - ArrayType arrayType = (ArrayType)TypeBeingBuilt; - if (arrayType.ElementType is DefType) { return checked((ushort)((DefType)arrayType.ElementType).InstanceFieldAlignment.AsInt); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.LdTokenResultLookup.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.LdTokenResultLookup.cs index 1c1da35553b88..d4f4b18d0accb 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.LdTokenResultLookup.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.LdTokenResultLookup.cs @@ -100,9 +100,8 @@ public RuntimeFieldHandleKey(RuntimeTypeHandle declaringType, string fieldName) public override bool Equals(object obj) { - if (obj is RuntimeFieldHandleKey) + if (obj is RuntimeFieldHandleKey other) { - RuntimeFieldHandleKey other = (RuntimeFieldHandleKey)obj; return Equals(other); } return false; @@ -145,9 +144,8 @@ public RuntimeMethodHandleKey(RuntimeTypeHandle declaringType, string methodName public override bool Equals(object obj) { - if (obj is RuntimeMethodHandleKey) + if (obj is RuntimeMethodHandleKey other) { - RuntimeMethodHandleKey other = (RuntimeMethodHandleKey)obj; return Equals(other); } return false; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeDesc.Runtime.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeDesc.Runtime.cs index 66cd911473ffa..09332e167c4b0 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeDesc.Runtime.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeDesc.Runtime.cs @@ -84,10 +84,8 @@ internal bool RetrieveRuntimeTypeHandleIfPossible() if (state != null && state.AttemptedAndFailedToRetrieveTypeHandle) return false; - if (type is DefType) + if (type is DefType typeAsDefType) { - DefType typeAsDefType = (DefType)type; - TypeDesc typeDefinition = typeAsDefType.GetTypeDefinition(); RuntimeTypeHandle typeDefHandle = typeDefinition.RuntimeTypeHandle; if (typeDefHandle.IsNull()) @@ -155,10 +153,8 @@ internal bool RetrieveRuntimeTypeHandleIfPossible() } } } - else if (type is ParameterizedType) + else if (type is ParameterizedType typeAsParameterType) { - ParameterizedType typeAsParameterType = (ParameterizedType)type; - if (typeAsParameterType.ParameterType.RetrieveRuntimeTypeHandleIfPossible()) { RuntimeTypeHandle rtth; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs index 55923303d641e..1f2b9cd01f000 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs @@ -321,10 +321,8 @@ protected override int GetValueHashCode(MethodDesc value) protected override bool CompareKeyToValue(RuntimeMethodKey key, MethodDesc value) { - if (value is RuntimeMethodDesc) + if (value is RuntimeMethodDesc runtimeMethod) { - RuntimeMethodDesc runtimeMethod = (RuntimeMethodDesc)value; - if (key._unboxingStub != runtimeMethod.UnboxingStub) return false; diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs index 2f3f6dcc923eb..48e8d77d2b318 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs @@ -212,9 +212,8 @@ public IDictionary GetPartMetadata(TypeInfo partType) var partMetadata = new Dictionary(); foreach (var attr in _attributeContext.GetDeclaredAttributes(partType.AsType(), partType)) { - if (attr is PartMetadataAttribute) + if (attr is PartMetadataAttribute ma) { - var ma = (PartMetadataAttribute)attr; partMetadata.Add(ma.Name, ma.Value); } } 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 2efbd4faacaca..b410f4b96068d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs @@ -113,9 +113,8 @@ internal void Add(Constraint constraint, bool addUniqueWhenAddingForeign) } AddUniqueConstraint((UniqueConstraint)constraint); } - else if (constraint is ForeignKeyConstraint) + else if (constraint is ForeignKeyConstraint fk) { - ForeignKeyConstraint fk = (ForeignKeyConstraint)constraint; if (addUniqueWhenAddingForeign) { UniqueConstraint? key = fk.RelatedTable.Constraints.FindKeyConstraint(fk.RelatedColumnsReference); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumnPropertyDescriptor.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumnPropertyDescriptor.cs index a26a31506adf3..8e830656626e2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumnPropertyDescriptor.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumnPropertyDescriptor.cs @@ -43,16 +43,9 @@ public override AttributeCollection Attributes public override Type PropertyType => Column.DataType; - public override bool Equals([NotNullWhen(true)] object? other) - { - if (other is DataColumnPropertyDescriptor) - { - DataColumnPropertyDescriptor descriptor = (DataColumnPropertyDescriptor)other; - return (descriptor.Column == Column); - } - - return false; - } + public override bool Equals([NotNullWhen(true)] object? other) => + other is DataColumnPropertyDescriptor descriptor && + descriptor.Column == Column; public override int GetHashCode() => Column.GetHashCode(); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs index 4154474effaf4..71170c51c79a9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs @@ -796,9 +796,8 @@ internal void ValidateMultipleNestedRelations() foreach (Constraint cs in ChildTable.Constraints) { - if (cs is ForeignKeyConstraint) + if (cs is ForeignKeyConstraint fk) { - ForeignKeyConstraint fk = (ForeignKeyConstraint)cs; if (!XmlTreeGen.AutoGenerated(fk, true)) { throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRelationPropertyDescriptor.cs b/src/libraries/System.Data.Common/src/System/Data/DataRelationPropertyDescriptor.cs index 4732907089cc3..5ea84cfa17e60 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRelationPropertyDescriptor.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRelationPropertyDescriptor.cs @@ -21,15 +21,9 @@ internal DataRelationPropertyDescriptor(DataRelation dataRelation) : base(dataRe public override Type PropertyType => typeof(IBindingList); - public override bool Equals([NotNullWhen(true)] object? other) - { - if (other is DataRelationPropertyDescriptor) - { - DataRelationPropertyDescriptor descriptor = (DataRelationPropertyDescriptor)other; - return (descriptor.Relation == Relation); - } - return false; - } + public override bool Equals([NotNullWhen(true)] object? other) => + other is DataRelationPropertyDescriptor descriptor && + descriptor.Relation == Relation; public override int GetHashCode() => Relation.GetHashCode(); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTablePropertyDescriptor.cs b/src/libraries/System.Data.Common/src/System/Data/DataTablePropertyDescriptor.cs index 766f9db78e7fe..8a4668c7eac15 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTablePropertyDescriptor.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTablePropertyDescriptor.cs @@ -21,15 +21,9 @@ internal DataTablePropertyDescriptor(DataTable dataTable) : base(dataTable.Table public override Type PropertyType => typeof(IBindingList); - public override bool Equals([NotNullWhen(true)] object? other) - { - if (other is DataTablePropertyDescriptor) - { - DataTablePropertyDescriptor descriptor = (DataTablePropertyDescriptor)other; - return (descriptor.Table == Table); - } - return false; - } + public override bool Equals([NotNullWhen(true)] object? other) => + other is DataTablePropertyDescriptor descriptor && + descriptor.Table == Table; public override int GetHashCode() => Table.GetHashCode(); 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 6ace6e1629b39..0691bf567fe37 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 @@ -83,9 +83,8 @@ internal override ExpressionNode Optimize() if (_op == Operators.Is) { // only 'Is Null' or 'Is Not Null' are valid - if (_right is UnaryNode) + if (_right is UnaryNode un) { - UnaryNode un = (UnaryNode)_right; if (un._op != Operators.Not) { throw ExprException.InvalidIsSyntax(); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs index f6a45dbba5f2c..d684a8a410b72 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs @@ -338,10 +338,8 @@ public SqlGuid ToSqlGuid() // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlBinary) + if (value is SqlBinary i) { - SqlBinary i = (SqlBinary)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlBinary)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs index d7b723f9f05f0..746e0ce021e06 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs @@ -441,10 +441,8 @@ public SqlString ToSqlString() // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlBoolean) + if (value is SqlBoolean i) { - SqlBoolean i = (SqlBoolean)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlBoolean)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs index 3dc5548ffed7a..84a5abeb54fc0 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs @@ -450,10 +450,8 @@ public SqlString ToSqlString() // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlByte) + if (value is SqlByte i) { - SqlByte i = (SqlByte)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlByte)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs index 1edd44bedf338..2b246f2d40c76 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs @@ -597,10 +597,8 @@ public SqlString ToSqlString() // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlDateTime) + if (value is SqlDateTime i) { - SqlDateTime i = (SqlDateTime)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlDateTime)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs index 4cc9ac4e321e0..ed7eb544cb9fc 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs @@ -366,10 +366,8 @@ public SqlString ToSqlString() // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlDouble) + if (value is SqlDouble i) { - SqlDouble i = (SqlDouble)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlDouble)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs index 2742c25d53b53..c04d277164072 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs @@ -257,10 +257,8 @@ public SqlBinary ToSqlBinary() // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlGuid) + if (value is SqlGuid i) { - SqlGuid i = (SqlGuid)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlGuid)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs index d3879a06cf91b..163974ba3baa3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs @@ -451,10 +451,8 @@ public SqlString ToSqlString() // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlInt16) + if (value is SqlInt16 i) { - SqlInt16 i = (SqlInt16)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlInt16)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs index 8ce08e74e4403..8bf98ce1b30f5 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs @@ -466,10 +466,8 @@ public SqlString ToSqlString() // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlInt32) + if (value is SqlInt32 i) { - SqlInt32 i = (SqlInt32)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlInt32)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs index 393945b030395..6dcb0ae7d4822 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs @@ -525,10 +525,8 @@ public SqlString ToSqlString() // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlInt64) + if (value is SqlInt64 i) { - SqlInt64 i = (SqlInt64)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlInt64)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs index 64c0d168631c8..9f1bf8cc12a76 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs @@ -515,10 +515,8 @@ public SqlString ToSqlString() // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlMoney) + if (value is SqlMoney i) { - SqlMoney i = (SqlMoney)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlMoney)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs index 5fa7562824e13..e59897a89e12e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs @@ -376,10 +376,8 @@ public SqlString ToSqlString() // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlSingle) + if (value is SqlSingle i) { - SqlSingle i = (SqlSingle)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlSingle)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs index 6b11083135552..5e9e2f53f028e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs @@ -836,10 +836,8 @@ private void Print() { // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object? value) { - if (value is SqlString) + if (value is SqlString i) { - SqlString i = (SqlString)value; - return CompareTo(i); } throw ADP.WrongType(value!.GetType(), typeof(SqlString)); diff --git a/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs b/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs index 655256d8e3fbd..ab19e2e5d423a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs @@ -53,10 +53,8 @@ internal void LoadTypeValues(XmlSchemaSimpleType node) (node.Content is XmlSchemaSimpleTypeUnion)) throw ExceptionBuilder.SimpleTypeNotSupported(); - if (node.Content is XmlSchemaSimpleTypeRestriction) + if (node.Content is XmlSchemaSimpleTypeRestriction content) { - XmlSchemaSimpleTypeRestriction content = (XmlSchemaSimpleTypeRestriction)node.Content; - XmlSchemaSimpleType? ancestor = node.BaseXmlSchemaType as XmlSchemaSimpleType; if ((ancestor != null) && (ancestor.QualifiedName.Namespace != Keywords.XSDNS)) { 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 164b3731bdccb..a05f34d726bf0 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -186,9 +186,8 @@ private void CollectElementsAnnotations(XmlSchema schema, ArrayList schemaList) { _annotations!.Add((XmlSchemaAnnotation)item); } - if (item is XmlSchemaElement) + if (item is XmlSchemaElement elem) { - XmlSchemaElement elem = (XmlSchemaElement)item; _elements!.Add(elem); _elementsTable![elem.QualifiedName] = elem; } @@ -610,9 +609,8 @@ private static int DatasetElementCount(XmlSchemaObjectCollection elements) if (ct.ContentModel is XmlSchemaSimpleContent) { XmlSchemaAnnotated? cContent = ((XmlSchemaSimpleContent)(ct.ContentModel)).Content; - if (cContent is XmlSchemaSimpleContentExtension) + if (cContent is XmlSchemaSimpleContentExtension ccExtension) { - XmlSchemaSimpleContentExtension ccExtension = ((XmlSchemaSimpleContentExtension)cContent); if (HasAttributes(ccExtension.Attributes)) return null; } @@ -1058,9 +1056,8 @@ 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 ccExtension) { - XmlSchemaComplexContentExtension ccExtension = ((XmlSchemaComplexContentExtension)cContent); if (!(ct.BaseXmlSchemaType is XmlSchemaComplexType && FromInference)) HandleAttributes(ccExtension.Attributes, table, isBase); @@ -1102,9 +1099,8 @@ internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayL { Debug.Assert(ct.ContentModel is XmlSchemaSimpleContent, "expected simpleContent or complexContent"); XmlSchemaAnnotated cContent = ((XmlSchemaSimpleContent)(ct.ContentModel)).Content!; - if (cContent is XmlSchemaSimpleContentExtension) + if (cContent is XmlSchemaSimpleContentExtension ccExtension) { - XmlSchemaSimpleContentExtension ccExtension = ((XmlSchemaSimpleContentExtension)cContent); HandleAttributes(ccExtension.Attributes, table, isBase); if (ct.BaseXmlSchemaType is XmlSchemaComplexType) { @@ -1537,15 +1533,13 @@ internal static string GetInstanceName(XmlSchemaAnnotated node) Debug.Assert((node is XmlSchemaElement) || (node is XmlSchemaAttribute), "GetInstanceName should only be called on attribute or elements"); - if (node is XmlSchemaElement) + if (node is XmlSchemaElement el) { - XmlSchemaElement el = (XmlSchemaElement)node; instanceName = el.Name ?? el.RefName.Name; } - else if (node is XmlSchemaAttribute) + else if (node is XmlSchemaAttribute attr) { - XmlSchemaAttribute el = (XmlSchemaAttribute)node; - instanceName = el.Name ?? el.RefName.Name; + instanceName = attr.Name ?? attr.RefName.Name; } Debug.Assert((instanceName != null) && (instanceName.Length != 0), "instanceName cannot be null or empty. There's an error in the XSD compiler"); 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 ca41c924bdf60..9fbc27600048b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs @@ -513,9 +513,8 @@ private void LoadRows(DataRow? parentRow, XmlNode parentElement) for (XmlNode? n = parentElement.FirstChild; n != null; n = n.NextSibling) { - if (n is XmlElement) + if (n is XmlElement e) { - XmlElement e = (XmlElement)n; object? schema = _nodeToSchemaMap!.GetSchemaForNode(e, FIgnoreNamespace(e)); if (schema != null && schema is DataTable) 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 32f72f51f01b1..9c8fc0424476c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs +++ b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs @@ -1204,13 +1204,9 @@ internal XmlElement HandleRelation(DataRelation rel, XmlDocument dc) { for (XmlNode? n = schema.FirstChild; n != null; n = n.NextSibling) { - if (n is XmlElement) + if (n is XmlElement e && e.GetAttribute(Keywords.NAME) == name) { - XmlElement e = (XmlElement)n; - if (e.GetAttribute(Keywords.NAME) == name) - { - return e; - } + return e; } } return null; @@ -1992,10 +1988,8 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche XmlElement? constraint; DataColumn[] fields; - if (constraints[i] is UniqueConstraint) + if (constraints[i] is UniqueConstraint unique) { - UniqueConstraint unique = (UniqueConstraint)constraints[i]; - if (IsAutoGenerated(unique)) continue; diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs index 582f20230507d..0578552235e63 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs @@ -217,9 +217,8 @@ public void ResetState() if (IsOpen) { object? value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_CONNECTIONSTATUS); - if (value is int) + if (value is int connectionStatus) { - int connectionStatus = (int)value; switch (connectionStatus) { case ODB.DBPROPVAL_CS_UNINITIALIZED: // provider closed on us 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 4ad0ab90f05e6..74a269344ff1b 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 @@ -374,9 +374,8 @@ private void BuildFilterSet(Principal p, string[] propertySet, QbeFilterDescript value.GetType().ToString()); // Build the right filter based on type of the property value - if (value is PrincipalValueCollection) + if (value is PrincipalValueCollection trackingList) { - PrincipalValueCollection trackingList = (PrincipalValueCollection)value; foreach (string s in trackingList.Inserted) { object filter = FilterFactory.CreateFilter(propertyName); @@ -384,11 +383,10 @@ private void BuildFilterSet(Principal p, string[] propertySet, QbeFilterDescript qbeFilterDescription.FiltersToApply.Add(filter); } } - else if (value is X509Certificate2Collection) + else if (value is X509Certificate2Collection certCollection) { // Since QBE filter objects are always unpersisted, any certs in the collection // must have been inserted by the application. - X509Certificate2Collection certCollection = (X509Certificate2Collection)value; foreach (X509Certificate2 cert in certCollection) { object filter = FilterFactory.CreateFilter(propertyName); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs index dcdea0d5993f5..78150496bbb98 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs @@ -806,13 +806,9 @@ internal void FillCache(string propertyName) } catch (TargetInvocationException e) { - if (e.InnerException != null) + if (e.InnerException is COMException inner) { - if (e.InnerException is COMException) - { - COMException inner = (COMException)e.InnerException; - throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); - } + throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); } throw; @@ -843,13 +839,9 @@ internal void FillCache(string propertyName) } catch (TargetInvocationException e) { - if (e.InnerException != null) + if (e.InnerException is COMException inner) { - if (e.InnerException is COMException) - { - COMException inner = (COMException)e.InnerException; - throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); - } + throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); } throw; @@ -876,13 +868,9 @@ public void InvokeSet(string propertyName, params object?[]? args) } catch (TargetInvocationException e) { - if (e.InnerException != null) + if (e.InnerException is COMException inner) { - if (e.InnerException is COMException) - { - COMException inner = (COMException)e.InnerException; - throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); - } + throw new TargetInvocationException(e.Message, COMExceptionHelper.CreateFormattedComException(inner)); } throw; 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 4b36ac253dc33..4e9725abb10d0 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 @@ -357,9 +357,8 @@ public void EmitLoad(object? value, Type? type) return; } - if (value is int) + if (value is int i) { - int i = (int)value; if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue) { if (s_Ints == null) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/AccessorBuilder.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/AccessorBuilder.cs index a2052d19972c7..47b6f31ccd421 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/AccessorBuilder.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/AccessorBuilder.cs @@ -95,9 +95,8 @@ public static Getter CreateGetter(MemberInfo memberInfo) Justification = "The call to MakeGenericMethod is safe due to the fact that FastInvokerBuilder.CreateSetterInternal is not annotated.")] public static Setter CreateSetter(MemberInfo memberInfo) { - if (memberInfo is PropertyInfo) + if (memberInfo is PropertyInfo propInfo) { - PropertyInfo propInfo = (PropertyInfo)memberInfo; if (propInfo.CanWrite) { Type declaringType = propInfo.DeclaringType!; @@ -141,9 +140,8 @@ public static Setter CreateSetter(MemberInfo memberInfo) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.NoSetMethodForProperty, propInfo.DeclaringType, propInfo.Name))); } } - else if (memberInfo is FieldInfo) + else if (memberInfo is FieldInfo fieldInfo) { - FieldInfo fieldInfo = (FieldInfo)memberInfo; return (ref object obj, object? val) => { fieldInfo.SetValue(obj, val); 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 c90bc4a6a76aa..f559f30703660 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 @@ -960,10 +960,8 @@ private void ImportDataMembers() DataMember memberContract = new DataMember(member); - if (member is PropertyInfo) + if (member is PropertyInfo property) { - PropertyInfo property = (PropertyInfo)member; - MethodInfo? getMethod = property.GetMethod; if (getMethod != null && IsMethodOverriding(getMethod)) continue; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs index 9902146707a27..0879bcde79bae 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs @@ -609,9 +609,8 @@ private static bool IsStruct(Type objType) internal Type LoadMember(MemberInfo memberInfo) { Type? memberType; - if (memberInfo is FieldInfo) + if (memberInfo is FieldInfo fieldInfo) { - FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { @@ -637,9 +636,8 @@ internal Type LoadMember(MemberInfo memberInfo) Call(getMethod); } } - else if (memberInfo is MethodInfo) + else if (memberInfo is MethodInfo method) { - MethodInfo method = (MethodInfo)memberInfo; memberType = method.ReturnType; Call(method); } @@ -652,9 +650,8 @@ internal Type LoadMember(MemberInfo memberInfo) internal void StoreMember(MemberInfo memberInfo) { - if (memberInfo is FieldInfo) + if (memberInfo is FieldInfo fieldInfo) { - FieldInfo fieldInfo = (FieldInfo)memberInfo; if (fieldInfo.IsStatic) { if (_codeGenTrace != CodeGenTrace.None) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs index c3db619138ee3..b654711af2d5a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs @@ -2173,19 +2173,16 @@ private static bool IsMemberVisibleInSerializationModule(MemberInfo member) if (!IsTypeVisibleInSerializationModule(member.DeclaringType!)) return false; - if (member is MethodInfo) + if (member is MethodInfo method) { - MethodInfo method = (MethodInfo)member; return (method.IsAssembly || method.IsFamilyOrAssembly); } - else if (member is FieldInfo) + else if (member is FieldInfo field) { - FieldInfo field = (FieldInfo)member; return (field.IsAssembly || field.IsFamilyOrAssembly) && IsTypeVisible(field.FieldType); } - else if (member is ConstructorInfo) + else if (member is ConstructorInfo constructor) { - ConstructorInfo constructor = (ConstructorInfo)member; return (constructor.IsAssembly || constructor.IsFamilyOrAssembly); } 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 d85097f17acb5..8b6a976c1b23a 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 @@ -90,9 +90,8 @@ private void ExportDataContract(DataContract dataContract) { XmlSchema schema = GetSchema(dataContract.StableName.Namespace); - if (dataContract is ClassDataContract) + if (dataContract is ClassDataContract classDataContract) { - ClassDataContract classDataContract = (ClassDataContract)dataContract; if (classDataContract.IsISerializable) ExportISerializableDataContract(classDataContract, schema); else 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 723ee9d6a9b48..4f737057a7eeb 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 @@ -886,9 +886,8 @@ private void PreprocessRedefine(RedefineEntry redefineEntry) } } } - else if (items[i] is XmlSchemaAttributeGroup) + else if (items[i] is XmlSchemaAttributeGroup attributeGroup) { - XmlSchemaAttributeGroup attributeGroup = (XmlSchemaAttributeGroup)items[i]; PreprocessAttributeGroup(attributeGroup); attributeGroup.QualifiedName.SetNamespace(targetNS); //Since PreprocessAttributeGroup will use this.targetNamespace and that will be that of the root schema's if (redefine.AttributeGroups[attributeGroup.QualifiedName] != null) @@ -912,9 +911,8 @@ private void PreprocessRedefine(RedefineEntry redefineEntry) } } } - else if (items[i] is XmlSchemaComplexType) + else if (items[i] is XmlSchemaComplexType complexType) { - XmlSchemaComplexType complexType = (XmlSchemaComplexType)items[i]; PreprocessComplexType(complexType, false); complexType.QualifiedName.SetNamespace(targetNS); //Since PreprocessComplexType will use this.targetNamespace and that will be that of the root schema's if (redefine.SchemaTypes[complexType.QualifiedName] != null) @@ -942,9 +940,8 @@ private void PreprocessRedefine(RedefineEntry redefineEntry) } } } - else if (items[i] is XmlSchemaSimpleType) + else if (items[i] is XmlSchemaSimpleType simpleType) { - XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)items[i]; PreprocessSimpleType(simpleType, false); simpleType.QualifiedName.SetNamespace(targetNS); //Since PreprocessSimpleType will use this.targetNamespace and that will be that of the root schema's if (redefine.SchemaTypes[simpleType.QualifiedName] != null) @@ -1492,9 +1489,8 @@ private void PreprocessIdentityConstraint(XmlSchemaIdentityConstraint constraint valid = false; } - if (constraint is XmlSchemaKeyref) + if (constraint is XmlSchemaKeyref keyref) { - XmlSchemaKeyref keyref = (XmlSchemaKeyref)constraint; if (keyref.Refer.IsEmpty) { SendValidationEvent(SR.Sch_IdConstraintNoRefer, constraint); @@ -1570,9 +1566,8 @@ private void PreprocessSimpleType(XmlSchemaSimpleType simpleType, bool local) { SendValidationEvent(SR.Sch_NoSimpleTypeContent, simpleType); } - else if (simpleType.Content is XmlSchemaSimpleTypeRestriction) + else if (simpleType.Content is XmlSchemaSimpleTypeRestriction restriction) { - XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)simpleType.Content; //SetParent SetParent(restriction, simpleType); for (int i = 0; i < restriction.Facets.Count; ++i) @@ -1602,9 +1597,8 @@ private void PreprocessSimpleType(XmlSchemaSimpleType simpleType, bool local) PreprocessAnnotation(restriction); //set parent of annotation child of simple type restriction ValidateIdAttribute(restriction); } - else if (simpleType.Content is XmlSchemaSimpleTypeList) + else if (simpleType.Content is XmlSchemaSimpleTypeList list) { - XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)simpleType.Content; SetParent(list, simpleType); if (list.ItemType != null) @@ -1750,9 +1744,8 @@ private void PreprocessComplexType(XmlSchemaComplexType complexType, bool local) SetParent(content.Content, content); //simplecontent extension / restriction PreprocessAnnotation(content.Content); //annotation child of simple extension / restriction - if (content.Content is XmlSchemaSimpleContentExtension) + if (content.Content is XmlSchemaSimpleContentExtension contentExtension) { - XmlSchemaSimpleContentExtension contentExtension = (XmlSchemaSimpleContentExtension)content.Content; if (contentExtension.BaseTypeName.IsEmpty) { SendValidationEvent(SR.Sch_MissAttribute, "base", contentExtension); @@ -1809,9 +1802,8 @@ private void PreprocessComplexType(XmlSchemaComplexType complexType, bool local) SetParent(content.Content, content); //complexcontent extension / restriction PreprocessAnnotation(content.Content); //Annotation child of extension / restriction - if (content.Content is XmlSchemaComplexContentExtension) + if (content.Content is XmlSchemaComplexContentExtension contentExtension) { - XmlSchemaComplexContentExtension contentExtension = (XmlSchemaComplexContentExtension)content.Content; if (contentExtension.BaseTypeName.IsEmpty) { SendValidationEvent(SR.Sch_MissAttribute, "base", contentExtension); @@ -2002,9 +1994,8 @@ private void PreprocessParticle(XmlSchemaParticle particle) } } } - else if (particle is XmlSchemaGroupRef) + else if (particle is XmlSchemaGroupRef groupRef) { - XmlSchemaGroupRef groupRef = (XmlSchemaGroupRef)particle; if (groupRef.RefName.IsEmpty) { SendValidationEvent(SR.Sch_MissAttribute, "ref", groupRef); 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 55900a6b3269c..a7dcc6dc35bfe 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 @@ -332,12 +332,10 @@ private static void CleanupComplexType(XmlSchemaComplexType complexType) { if (complexType.ContentModel != null) { //simpleContent or complexContent - if (complexType.ContentModel is XmlSchemaSimpleContent) + if (complexType.ContentModel is XmlSchemaSimpleContent simpleContent) { - XmlSchemaSimpleContent simpleContent = (XmlSchemaSimpleContent)complexType.ContentModel; - if (simpleContent.Content is XmlSchemaSimpleContentExtension) + if (simpleContent.Content is XmlSchemaSimpleContentExtension simpleExtension) { - XmlSchemaSimpleContentExtension simpleExtension = (XmlSchemaSimpleContentExtension)simpleContent.Content; CleanupAttributes(simpleExtension.Attributes); } else @@ -537,9 +535,8 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) simpleType.IsProcessing = true; try { - if (simpleType.Content is XmlSchemaSimpleTypeList) + if (simpleType.Content is XmlSchemaSimpleTypeList list) { - XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)simpleType.Content; XmlSchemaDatatype datatype; simpleType.SetBaseSchemaType(DatatypeImplementation.AnySimpleType); if (list.ItemTypeName.IsEmpty) @@ -568,9 +565,8 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) simpleType.SetDatatype(datatype.DeriveByList(simpleType)); simpleType.SetDerivedBy(XmlSchemaDerivationMethod.List); } - else if (simpleType.Content is XmlSchemaSimpleTypeRestriction) + else if (simpleType.Content is XmlSchemaSimpleTypeRestriction restriction) { - XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)simpleType.Content; XmlSchemaDatatype datatype; if (restriction.BaseTypeName.IsEmpty) { @@ -725,9 +721,8 @@ private void CompileComplexType(XmlSchemaComplexType complexType) complexType.IsProcessing = true; if (complexType.ContentModel != null) { //simpleContent or complexContent - if (complexType.ContentModel is XmlSchemaSimpleContent) + if (complexType.ContentModel is XmlSchemaSimpleContent simpleContent) { - XmlSchemaSimpleContent simpleContent = (XmlSchemaSimpleContent)complexType.ContentModel; complexType.SetContentType(XmlSchemaContentType.TextOnly); if (simpleContent.Content is XmlSchemaSimpleContentExtension) { @@ -2264,9 +2259,8 @@ private void CompileElement(XmlSchemaElement xe) if (decl == null) { Debug.Assert(xe.ElementSchemaType != null); - if (xe.ElementSchemaType is XmlSchemaComplexType) + if (xe.ElementSchemaType is XmlSchemaComplexType complexType) { - XmlSchemaComplexType complexType = (XmlSchemaComplexType)xe.ElementSchemaType; CompileComplexType(complexType); if (complexType.ElementDecl != null) { @@ -2274,9 +2268,8 @@ private void CompileElement(XmlSchemaElement xe) // decl.LocalElements = complexType.LocalElementDecls; } } - else if (xe.ElementSchemaType is XmlSchemaSimpleType) + else if (xe.ElementSchemaType is XmlSchemaSimpleType simpleType) { - XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)xe.ElementSchemaType; CompileSimpleType(simpleType); if (simpleType.ElementDecl != null) { @@ -2382,9 +2375,8 @@ private ContentValidator CompileComplexContent(XmlSchemaComplexType complexType) } } PushComplexType(complexType); - if (particle is XmlSchemaAll) + if (particle is XmlSchemaAll all) { - XmlSchemaAll all = (XmlSchemaAll)particle; AllElementsContentValidator contentValidator = new AllElementsContentValidator(complexType.ContentType, all.Items.Count, all.MinOccurs == decimal.Zero); for (int i = 0; i < all.Items.Count; ++i) { @@ -2459,9 +2451,8 @@ private void DumpContentModelTo(StringBuilder sb, XmlSchemaParticle particle) sb.Append(((XmlSchemaAny)particle!).NamespaceList!.ToString()); sb.Append('>'); } - else if (particle is XmlSchemaAll) + else if (particle is XmlSchemaAll all) { - XmlSchemaAll all = (XmlSchemaAll)particle; sb.Append('['); bool first = true; for (int i = 0; i < all.Items.Count; ++i) @@ -2483,9 +2474,8 @@ private void DumpContentModelTo(StringBuilder sb, XmlSchemaParticle particle) } sb.Append(']'); } - else if (particle is XmlSchemaGroupBase) + else if (particle is XmlSchemaGroupBase gb) { - XmlSchemaGroupBase gb = (XmlSchemaGroupBase)particle; sb.Append('('); string delimeter = (particle is XmlSchemaChoice) ? " | " : ", "; bool first = true; @@ -2533,14 +2523,12 @@ private void DumpContentModelTo(StringBuilder sb, XmlSchemaParticle particle) private void BuildParticleContentModel(ParticleContentValidator contentValidator, XmlSchemaParticle particle) { - if (particle is XmlSchemaElement) + if (particle is XmlSchemaElement element) { - XmlSchemaElement element = (XmlSchemaElement)particle; contentValidator.AddName(element.QualifiedName, element); } - else if (particle is XmlSchemaAny) + else if (particle is XmlSchemaAny any) { - XmlSchemaAny any = (XmlSchemaAny)particle; contentValidator.AddNamespaceList(any.NamespaceList!, any); } else if (particle is XmlSchemaGroupBase) @@ -2597,9 +2585,8 @@ private void BuildParticleContentModel(ParticleContentValidator contentValidator private void CompileParticleElements(XmlSchemaComplexType complexType, XmlSchemaParticle particle) { - if (particle is XmlSchemaElement) + if (particle is XmlSchemaElement localElement) { - XmlSchemaElement localElement = (XmlSchemaElement)particle; CompileElement(localElement); if (complexType.LocalElements[localElement.QualifiedName] == null) { 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 07bf38d05f56b..f3f002d4530e3 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 @@ -178,10 +178,9 @@ private void LoadExternals(XmlSchema schema, XmlSchemaCollection? xsc) for (int j = 0; j < include.Schema.Includes.Count; ++j) { XmlSchemaExternal subInc = (XmlSchemaExternal)include.Schema.Includes[j]; - if (subInc is XmlSchemaImport) + if (subInc is XmlSchemaImport subImp) { - XmlSchemaImport subImp = (XmlSchemaImport)subInc; - subUri = subImp.BaseUri ?? (subImp.Schema != null && subImp.Schema.BaseUri != null ? subImp.Schema.BaseUri : null); + subUri = subImp.BaseUri ?? subImp.Schema?.BaseUri; if (subUri != null) { if (_schemaLocations![subUri] != null) @@ -478,9 +477,8 @@ private void Preprocess(XmlSchema schema, string? targetNamespace, Compositor co for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i]; - if (include is XmlSchemaRedefine) + if (include is XmlSchemaRedefine redefine) { - XmlSchemaRedefine redefine = (XmlSchemaRedefine)include; if (include.Schema != null) { PreprocessRedefine(redefine); @@ -543,39 +541,33 @@ private void Preprocess(XmlSchema schema, string? targetNamespace, Compositor co PreprocessAttribute(attribute); AddToTable(schema.Attributes, attribute.QualifiedName, attribute); } - else if (schema.Items[i] is XmlSchemaAttributeGroup) + else if (schema.Items[i] is XmlSchemaAttributeGroup attributeGroup) { - XmlSchemaAttributeGroup attributeGroup = (XmlSchemaAttributeGroup)schema.Items[i]; PreprocessAttributeGroup(attributeGroup); AddToTable(schema.AttributeGroups, attributeGroup.QualifiedName, attributeGroup); } - else if (schema.Items[i] is XmlSchemaComplexType) + else if (schema.Items[i] is XmlSchemaComplexType complexType) { - XmlSchemaComplexType complexType = (XmlSchemaComplexType)schema.Items[i]; PreprocessComplexType(complexType, false); AddToTable(schema.SchemaTypes, complexType.QualifiedName, complexType); } - else if (schema.Items[i] is XmlSchemaSimpleType) + else if (schema.Items[i] is XmlSchemaSimpleType simpleType) { - XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)schema.Items[i]; PreprocessSimpleType(simpleType, false); AddToTable(schema.SchemaTypes, simpleType.QualifiedName, simpleType); } - else if (schema.Items[i] is XmlSchemaElement) + else if (schema.Items[i] is XmlSchemaElement element) { - XmlSchemaElement element = (XmlSchemaElement)schema.Items[i]; PreprocessElement(element); AddToTable(schema.Elements, element.QualifiedName, element); } - else if (schema.Items[i] is XmlSchemaGroup) + else if (schema.Items[i] is XmlSchemaGroup group) { - XmlSchemaGroup group = (XmlSchemaGroup)schema.Items[i]; PreprocessGroup(group); AddToTable(schema.Groups, group.QualifiedName, group); } - else if (schema.Items[i] is XmlSchemaNotation) + else if (schema.Items[i] is XmlSchemaNotation notation) { - XmlSchemaNotation notation = (XmlSchemaNotation)schema.Items[i]; PreprocessNotation(notation); AddToTable(schema.Notations, notation.QualifiedName, notation); } @@ -620,9 +612,8 @@ private void PreprocessRedefine(XmlSchemaRedefine redefine) } } } - else if (redefine.Items[i] is XmlSchemaAttributeGroup) + else if (redefine.Items[i] is XmlSchemaAttributeGroup attributeGroup) { - XmlSchemaAttributeGroup attributeGroup = (XmlSchemaAttributeGroup)redefine.Items[i]; PreprocessAttributeGroup(attributeGroup); if (redefine.AttributeGroups[attributeGroup.QualifiedName] != null) { @@ -642,9 +633,8 @@ private void PreprocessRedefine(XmlSchemaRedefine redefine) } } } - else if (redefine.Items[i] is XmlSchemaComplexType) + else if (redefine.Items[i] is XmlSchemaComplexType complexType) { - XmlSchemaComplexType complexType = (XmlSchemaComplexType)redefine.Items[i]; PreprocessComplexType(complexType, false); if (redefine.SchemaTypes[complexType.QualifiedName] != null) { @@ -672,9 +662,8 @@ private void PreprocessRedefine(XmlSchemaRedefine redefine) } } } - else if (redefine.Items[i] is XmlSchemaSimpleType) + else if (redefine.Items[i] is XmlSchemaSimpleType simpleType) { - XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)redefine.Items[i]; PreprocessSimpleType(simpleType, false); if (redefine.SchemaTypes[simpleType.QualifiedName] != null) { @@ -1148,9 +1137,8 @@ private void PreprocessIdentityConstraint(XmlSchemaIdentityConstraint constraint SendValidationEvent(SR.Sch_IdConstraintNoFields, constraint); valid = false; } - if (constraint is XmlSchemaKeyref) + if (constraint is XmlSchemaKeyref keyref) { - XmlSchemaKeyref keyref = (XmlSchemaKeyref)constraint; if (keyref.Refer.IsEmpty) { SendValidationEvent(SR.Sch_IdConstraintNoRefer, constraint); @@ -1224,9 +1212,8 @@ private void PreprocessSimpleType(XmlSchemaSimpleType simpleType, bool local) { SendValidationEvent(SR.Sch_NoSimpleTypeContent, simpleType); } - else if (simpleType.Content is XmlSchemaSimpleTypeRestriction) + else if (simpleType.Content is XmlSchemaSimpleTypeRestriction restriction) { - XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)simpleType.Content; //SetParent SetParent(restriction, simpleType); for (int i = 0; i < restriction.Facets.Count; ++i) @@ -1256,9 +1243,8 @@ private void PreprocessSimpleType(XmlSchemaSimpleType simpleType, bool local) PreprocessAnnotation(restriction); //set parent of annotation child of simple type restriction ValidateIdAttribute(restriction); } - else if (simpleType.Content is XmlSchemaSimpleTypeList) + else if (simpleType.Content is XmlSchemaSimpleTypeList list) { - XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)simpleType.Content; SetParent(list, simpleType); if (list.ItemType != null) @@ -1402,9 +1388,8 @@ private void PreprocessComplexType(XmlSchemaComplexType complexType, bool local) SetParent(content.Content, content); //simplecontent extension / restriction PreprocessAnnotation(content.Content); //annotation child of simple extension / restriction - if (content.Content is XmlSchemaSimpleContentExtension) + if (content.Content is XmlSchemaSimpleContentExtension contentExtension) { - XmlSchemaSimpleContentExtension contentExtension = (XmlSchemaSimpleContentExtension)content.Content; if (contentExtension.BaseTypeName.IsEmpty) { SendValidationEvent(SR.Sch_MissAttribute, "base", contentExtension); @@ -1461,9 +1446,8 @@ private void PreprocessComplexType(XmlSchemaComplexType complexType, bool local) SetParent(content.Content, content); //complexcontent extension / restriction PreprocessAnnotation(content.Content); //Annotation child of extension / restriction - if (content.Content is XmlSchemaComplexContentExtension) + if (content.Content is XmlSchemaComplexContentExtension contentExtension) { - XmlSchemaComplexContentExtension contentExtension = (XmlSchemaComplexContentExtension)content.Content; if (contentExtension.BaseTypeName.IsEmpty) { SendValidationEvent(SR.Sch_MissAttribute, "base", contentExtension); @@ -1657,9 +1641,8 @@ private void PreprocessParticle(XmlSchemaParticle particle) } } } - else if (particle is XmlSchemaGroupRef) + else if (particle is XmlSchemaGroupRef groupRef) { - XmlSchemaGroupRef groupRef = (XmlSchemaGroupRef)particle; if (groupRef.RefName.IsEmpty) { SendValidationEvent(SR.Sch_MissAttribute, "ref", groupRef); 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 7de4c7d56ef58..1a26274cb86d1 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 @@ -326,12 +326,10 @@ private void CleanupComplexType(XmlSchemaComplexType complexType) if (complexType.ContentModel != null) { //simpleContent or complexContent - if (complexType.ContentModel is XmlSchemaSimpleContent) + if (complexType.ContentModel is XmlSchemaSimpleContent simpleContent) { - XmlSchemaSimpleContent simpleContent = (XmlSchemaSimpleContent)complexType.ContentModel; - if (simpleContent.Content is XmlSchemaSimpleContentExtension) + if (simpleContent.Content is XmlSchemaSimpleContentExtension simpleExtension) { - XmlSchemaSimpleContentExtension simpleExtension = (XmlSchemaSimpleContentExtension)simpleContent.Content; CleanupAttributes(simpleExtension.Attributes); } else @@ -343,9 +341,8 @@ private void CleanupComplexType(XmlSchemaComplexType complexType) else { // complexType.ContentModel is XmlSchemaComplexContent XmlSchemaComplexContent complexContent = (XmlSchemaComplexContent)complexType.ContentModel; - if (complexContent.Content is XmlSchemaComplexContentExtension) + if (complexContent.Content is XmlSchemaComplexContentExtension complexExtension) { - XmlSchemaComplexContentExtension complexExtension = (XmlSchemaComplexContentExtension)complexContent.Content; CleanupParticle(complexExtension.Particle); CleanupAttributes(complexExtension.Attributes); } @@ -637,9 +634,8 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) simpleType.IsProcessing = true; try { - if (simpleType.Content is XmlSchemaSimpleTypeList) + if (simpleType.Content is XmlSchemaSimpleTypeList list) { - XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)simpleType.Content; XmlSchemaDatatype datatype; simpleType.SetBaseSchemaType(DatatypeImplementation.AnySimpleType); if (list.ItemTypeName.IsEmpty) @@ -670,9 +666,8 @@ private void CompileSimpleType(XmlSchemaSimpleType simpleType) simpleType.SetDatatype(datatype.DeriveByList(simpleType)); simpleType.SetDerivedBy(XmlSchemaDerivationMethod.List); } - else if (simpleType.Content is XmlSchemaSimpleTypeRestriction) + else if (simpleType.Content is XmlSchemaSimpleTypeRestriction restriction) { - XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)simpleType.Content; XmlSchemaDatatype datatype; if (restriction.BaseTypeName.IsEmpty) { @@ -832,9 +827,8 @@ private void CompileComplexType(XmlSchemaComplexType complexType) { if (complexType.ContentModel != null) { //simpleContent or complexContent - if (complexType.ContentModel is XmlSchemaSimpleContent) + if (complexType.ContentModel is XmlSchemaSimpleContent simpleContent) { - XmlSchemaSimpleContent simpleContent = (XmlSchemaSimpleContent)complexType.ContentModel; complexType.SetContentType(XmlSchemaContentType.TextOnly); if (simpleContent.Content is XmlSchemaSimpleContentExtension) { @@ -1551,14 +1545,12 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart { return false; } - if (derivedParticle is XmlSchemaElement) + if (derivedParticle is XmlSchemaElement derivedElem) { //check for derived element being head of substitutionGroup - XmlSchemaElement derivedElem = (XmlSchemaElement)derivedParticle; derivedParticle = CannonicalizeElement(derivedElem); } - if (baseParticle is XmlSchemaElement) + if (baseParticle is XmlSchemaElement baseElem) { - XmlSchemaElement baseElem = (XmlSchemaElement)baseParticle; XmlSchemaParticle newBaseParticle; newBaseParticle = CannonicalizeElement(baseElem); if (newBaseParticle is XmlSchemaChoice) @@ -2743,9 +2735,8 @@ private void CompileElement(XmlSchemaElement xe) if (decl == null) { Debug.Assert(xe.ElementSchemaType != null); - if (xe.ElementSchemaType is XmlSchemaComplexType) + if (xe.ElementSchemaType is XmlSchemaComplexType complexType) { - XmlSchemaComplexType complexType = (XmlSchemaComplexType)xe.ElementSchemaType; CompileComplexType(complexType); if (complexType.ElementDecl != null) { @@ -2753,9 +2744,8 @@ private void CompileElement(XmlSchemaElement xe) // decl.LocalElements = complexType.LocalElementDecls; } } - else if (xe.ElementSchemaType is XmlSchemaSimpleType) + else if (xe.ElementSchemaType is XmlSchemaSimpleType simpleType) { - XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)xe.ElementSchemaType; CompileSimpleType(simpleType); if (simpleType.ElementDecl != null) { @@ -2871,9 +2861,8 @@ private ContentValidator CompileComplexContent(XmlSchemaComplexType complexType) } } PushComplexType(complexType); - if (particle is XmlSchemaAll) + if (particle is XmlSchemaAll all) { - XmlSchemaAll all = (XmlSchemaAll)particle; AllElementsContentValidator contentValidator = new AllElementsContentValidator(complexType.ContentType, all.Items.Count, all.MinOccurs == decimal.Zero); for (int i = 0; i < all.Items.Count; ++i) { @@ -2931,9 +2920,8 @@ private ContentValidator CompileComplexContent(XmlSchemaComplexType complexType) private bool BuildParticleContentModel(ParticleContentValidator contentValidator, XmlSchemaParticle particle) { bool hasWildCard = false; - if (particle is XmlSchemaElement) + if (particle is XmlSchemaElement element) { - XmlSchemaElement element = (XmlSchemaElement)particle; contentValidator.AddName(element.QualifiedName, element); } else if (particle is XmlSchemaAny) @@ -2996,9 +2984,8 @@ private bool BuildParticleContentModel(ParticleContentValidator contentValidator private void CompileParticleElements(XmlSchemaComplexType complexType, XmlSchemaParticle particle) { - if (particle is XmlSchemaElement) + if (particle is XmlSchemaElement localElement) { - XmlSchemaElement localElement = (XmlSchemaElement)particle; CompileElement(localElement); if (complexType.LocalElements[localElement.QualifiedName] == null) { @@ -3025,9 +3012,8 @@ private void CompileParticleElements(XmlSchemaComplexType complexType, XmlSchema private void CompileParticleElements(XmlSchemaParticle particle) { //For checking redefined group particle derivation - if (particle is XmlSchemaElement) + if (particle is XmlSchemaElement localElement) { - XmlSchemaElement localElement = (XmlSchemaElement)particle; CompileElement(localElement); } else if (particle is XmlSchemaGroupBase) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs index 25bfa8dd5303f..74c64a649c11e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs @@ -1614,9 +1614,8 @@ private void AddXsiAttributes(ArrayList attList) { if (_isRoot && _partialValidationType != null) { - if (_partialValidationType is XmlSchemaElement) + if (_partialValidationType is XmlSchemaElement element) { - XmlSchemaElement element = (XmlSchemaElement)_partialValidationType; if (elementName.Equals(element.QualifiedName)) { elementDecl = element.ElementDecl; @@ -1626,9 +1625,8 @@ private void AddXsiAttributes(ArrayList attList) SendValidationEvent(SR.Sch_SchemaElementNameMismatch, elementName.ToString(), element.QualifiedName.ToString()); } } - else if (_partialValidationType is XmlSchemaType) + else if (_partialValidationType is XmlSchemaType type) { //Element name is wildcard - XmlSchemaType type = (XmlSchemaType)_partialValidationType; elementDecl = type.ElementDecl; } 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 7618fc1a9ca8b..d0cfe8cb6b4dc 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 @@ -537,9 +537,8 @@ internal Type LoadMember(object obj, MemberInfo memberInfo) internal Type LoadMember(MemberInfo memberInfo) { Type? memberType; - if (memberInfo is FieldInfo) + if (memberInfo is FieldInfo fieldInfo) { - FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { @@ -576,9 +575,8 @@ internal Type LoadMember(MemberInfo memberInfo) internal Type LoadMemberAddress(MemberInfo memberInfo) { Type? memberType; - if (memberInfo is FieldInfo) + if (memberInfo is FieldInfo fieldInfo) { - FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { @@ -618,9 +616,8 @@ internal Type LoadMemberAddress(MemberInfo memberInfo) [RequiresUnreferencedCode("calls GetPropertyMethodFromBaseType")] internal void StoreMember(MemberInfo memberInfo) { - if (memberInfo is FieldInfo) + if (memberInfo is FieldInfo fieldInfo) { - FieldInfo fieldInfo = (FieldInfo)memberInfo; if (fieldInfo.IsStatic) { _ilGen!.Emit(OpCodes.Stsfld, fieldInfo); 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 9499f3243a041..aac4e7ca97eb2 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 @@ -328,9 +328,8 @@ internal void Depends(XmlSchemaObject? item, ArrayList refs) XmlSchemaParticle? particle = null; XmlSchemaObjectCollection? attributes = null; - if (item is XmlSchemaComplexType) + if (item is XmlSchemaComplexType ct) { - XmlSchemaComplexType ct = (XmlSchemaComplexType)item; if (ct.ContentModel != null) { XmlSchemaContent? content = ct.ContentModel.Content; @@ -339,27 +338,24 @@ internal void Depends(XmlSchemaObject? item, ArrayList refs) baseName = ((XmlSchemaComplexContentRestriction)content).BaseTypeName; attributes = ((XmlSchemaComplexContentRestriction)content).Attributes; } - else if (content is XmlSchemaSimpleContentRestriction) + else if (content is XmlSchemaSimpleContentRestriction restriction) { - XmlSchemaSimpleContentRestriction restriction = (XmlSchemaSimpleContentRestriction)content; if (restriction.BaseType != null) baseType = restriction.BaseType; else baseName = restriction.BaseTypeName; attributes = restriction.Attributes; } - else if (content is XmlSchemaComplexContentExtension) + else if (content is XmlSchemaComplexContentExtension complex) { - XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content; - attributes = extension.Attributes; - particle = extension.Particle; - baseName = extension.BaseTypeName; + attributes = complex.Attributes; + particle = complex.Particle; + baseName = complex.BaseTypeName; } - else if (content is XmlSchemaSimpleContentExtension) + else if (content is XmlSchemaSimpleContentExtension simple) { - XmlSchemaSimpleContentExtension extension = (XmlSchemaSimpleContentExtension)content; - attributes = extension.Attributes; - baseName = extension.BaseTypeName; + attributes = simple.Attributes; + baseName = simple.BaseTypeName; } } else @@ -367,9 +363,8 @@ internal void Depends(XmlSchemaObject? item, ArrayList refs) attributes = ct.Attributes; particle = ct.Particle; } - if (particle is XmlSchemaGroupRef) + if (particle is XmlSchemaGroupRef refGroup) { - XmlSchemaGroupRef refGroup = (XmlSchemaGroupRef)particle; particle = ((XmlSchemaGroup)_schemas.Find(refGroup.RefName, typeof(XmlSchemaGroup), false)!).Particle; } else if (particle is XmlSchemaGroupBase) @@ -377,18 +372,16 @@ internal void Depends(XmlSchemaObject? item, ArrayList refs) particle = (XmlSchemaGroupBase)particle; } } - else if (item is XmlSchemaSimpleType) + else if (item is XmlSchemaSimpleType simpleType) { - XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)item; XmlSchemaSimpleTypeContent? content = simpleType.Content; if (content is XmlSchemaSimpleTypeRestriction) { baseType = ((XmlSchemaSimpleTypeRestriction)content).BaseType; baseName = ((XmlSchemaSimpleTypeRestriction)content).BaseTypeName; } - else if (content is XmlSchemaSimpleTypeList) + else if (content is XmlSchemaSimpleTypeList list) { - XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)content; if (list.ItemTypeName != null && !list.ItemTypeName.IsEmpty) baseName = list.ItemTypeName; if (list.ItemType != 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 2d9e6b10224ea..7beb27220cc2b 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 @@ -95,23 +95,20 @@ internal static XmlQualifiedName NameOf(XmlSchemaObject? o) { return ((XmlSchemaNotation)o).QualifiedName; } - else if (o is XmlSchemaSequence) + else if (o is XmlSchemaSequence s) { - XmlSchemaSequence s = (XmlSchemaSequence)o; if (s.Items.Count == 0) return new XmlQualifiedName(".sequence", Namespace(o)); return NameOf(s.Items[0]); } - else if (o is XmlSchemaAll) + else if (o is XmlSchemaAll a) { - XmlSchemaAll a = (XmlSchemaAll)o; if (a.Items.Count == 0) return new XmlQualifiedName(".all", Namespace(o)); return NameOf(a.Items); } - else if (o is XmlSchemaChoice) + else if (o is XmlSchemaChoice c) { - XmlSchemaChoice c = (XmlSchemaChoice)o; if (c.Items.Count == 0) return new XmlQualifiedName(".choice", Namespace(o)); return NameOf(c.Items); 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 cb81d6e8c0c09..ac42ce01c5ced 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 @@ -508,9 +508,8 @@ private void SetArrayMappingType(ArrayMapping mapping) TypeMapping? existingMapping = (TypeMapping?)_types[uniqueName, ns]; while (existingMapping != null) { - if (existingMapping is ArrayMapping) + if (existingMapping is ArrayMapping arrayMapping) { - ArrayMapping arrayMapping = (ArrayMapping)existingMapping; if (AccessorMapping.ElementsMatch(arrayMapping.Elements, mapping.Elements)) { break; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs index 5f0ee4a7931f6..2289e3cdaf57c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs @@ -1379,9 +1379,8 @@ internal static PropertyInfo GetDefaultIndexer( { for (int i = 0; i < defaultMembers.Length; i++) { - if (defaultMembers[i] is PropertyInfo) + if (defaultMembers[i] is PropertyInfo defaultProp) { - PropertyInfo defaultProp = (PropertyInfo)defaultMembers[i]; if (defaultProp.DeclaringType != t) continue; if (!defaultProp.CanRead) continue; MethodInfo getMethod = defaultProp.GetMethod!; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs index 0a0cbd0649867..d34aa9fd4de81 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs @@ -95,9 +95,8 @@ public XmlAttributes(ICustomAttributeProvider provider) { _xmlArrayItems.Add((XmlArrayItemAttribute)attrs[i]); } - else if (attrs[i] is XmlAnyElementAttribute) + else if (attrs[i] is XmlAnyElementAttribute any) { - XmlAnyElementAttribute any = (XmlAnyElementAttribute)attrs[i]; if ((any.Name == null || any.Name.Length == 0) && any.GetNamespaceSpecified() && any.Namespace == null) { // ignore duplicate wildcards 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 f3fb4eb9fb230..b0f80adbeb7ba 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 @@ -1067,9 +1067,8 @@ private void SetArrayMappingType(ArrayMapping mapping, string? defaultNs, Type t TypeMapping? existingMapping = (TypeMapping?)_types[uniqueName, ns]; while (existingMapping != null) { - if (existingMapping is ArrayMapping) + if (existingMapping is ArrayMapping arrayMapping) { - ArrayMapping arrayMapping = (ArrayMapping)existingMapping; if (AccessorMapping.ElementsMatch(arrayMapping.Elements, mapping.Elements)) { break; 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 69a156058d0d5..c3b75d73ad7b3 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 @@ -119,9 +119,8 @@ private static bool IsAnyType(XmlSchemaType schemaType, bool mixed, bool unbound { if (complexType.IsMixed != mixed) return false; - if (complexType.Particle is XmlSchemaSequence) + if (complexType.Particle is XmlSchemaSequence sequence) { - XmlSchemaSequence sequence = (XmlSchemaSequence)complexType.Particle; if (sequence.Items.Count == 1 && sequence.Items[0] is XmlSchemaAny) { XmlSchemaAny any = (XmlSchemaAny)sequence.Items[0]; @@ -286,16 +285,14 @@ private void AddSchemaItem(XmlSchemaObject item, string? ns, string? referencing schema = AddSchema(ns); } - if (item is XmlSchemaElement) + if (item is XmlSchemaElement e) { - XmlSchemaElement e = (XmlSchemaElement)item; if (e.Form == XmlSchemaForm.Unqualified) throw new InvalidOperationException(SR.Format(SR.XmlIllegalForm, e.Name)); e.Form = XmlSchemaForm.None; } - else if (item is XmlSchemaAttribute) + else if (item is XmlSchemaAttribute a) { - XmlSchemaAttribute a = (XmlSchemaAttribute)item; if (a.Form == XmlSchemaForm.Unqualified) throw new InvalidOperationException(SR.Format(SR.XmlIllegalForm, a.Name)); a.Form = XmlSchemaForm.None; @@ -344,9 +341,8 @@ private bool SchemaContainsItem(XmlSchemaObject item, string ns) { foreach (object item in schema.Includes) { - if (item is XmlSchemaImport) + if (item is XmlSchemaImport import) { - XmlSchemaImport import = (XmlSchemaImport)item; if (NamespacesEqual(import.Namespace, ns)) { return import; @@ -380,9 +376,8 @@ private void ExportElementMapping(XmlSchemaElement element, Mapping mapping, str { if (mapping is ArrayMapping) ExportArrayMapping((ArrayMapping)mapping, ns, element); - else if (mapping is PrimitiveMapping) + else if (mapping is PrimitiveMapping pm) { - PrimitiveMapping pm = (PrimitiveMapping)mapping; if (pm.IsAnonymousType) { element.SchemaType = ExportAnonymousPrimitiveMapping(pm); @@ -723,9 +718,8 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content; extension.AnyAttribute = new XmlSchemaAnyAttribute(); } - else if (content is XmlSchemaComplexContentRestriction) + else if (content is XmlSchemaComplexContentRestriction restriction) { - XmlSchemaComplexContentRestriction restriction = (XmlSchemaComplexContentRestriction)content; restriction.AnyAttribute = new XmlSchemaAnyAttribute(); } else if (type.ContentModel.Content is XmlSchemaSimpleContentExtension) @@ -772,9 +766,8 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso attributes.Add(refAttribute); AddSchemaImport(accessor.Namespace, ns); } - if (accessor.Mapping is PrimitiveMapping) + if (accessor.Mapping is PrimitiveMapping pm) { - PrimitiveMapping pm = (PrimitiveMapping)accessor.Mapping; if (pm.IsList) { // create local simple type for the list-like attributes @@ -884,10 +877,8 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc if (value == null || value == DBNull.Value) return null; - if (mapping is EnumMapping) + if (mapping is EnumMapping em) { - EnumMapping em = (EnumMapping)mapping; - #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (value.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, SR.Format(SR.XmlInvalidDefaultValue, value, value.GetType().FullName))); 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 fbc15d44dc375..f021393ac772c 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 @@ -384,9 +384,8 @@ internal override void ImportDerivedTypes(XmlQualifiedName baseName) XmlSchemas.Preprocess(schema); foreach (object item in schema.SchemaTypes.Values) { - if (item is XmlSchemaType) + if (item is XmlSchemaType type) { - XmlSchemaType type = (XmlSchemaType)item; if (type.DerivedFrom == baseName && TypesInUse[type.Name, schema.TargetNamespace] == null) { ImportType(type.QualifiedName, typeof(TypeMapping), null, TypeFlags.CanBeElementValue, false); @@ -697,19 +696,17 @@ private TypeItems GetTypeItems(XmlSchemaType type) if (ct.ContentModel != null) { XmlSchemaContent? content = ct.ContentModel.Content; - if (content is XmlSchemaComplexContentExtension) + if (content is XmlSchemaComplexContentExtension complex) { - XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content; - items.Attributes = extension.Attributes; - items.AnyAttribute = extension.AnyAttribute; - particle = extension.Particle; + items.Attributes = complex.Attributes; + items.AnyAttribute = complex.AnyAttribute; + particle = complex.Particle; } - else if (content is XmlSchemaSimpleContentExtension) + else if (content is XmlSchemaSimpleContentExtension simple) { - XmlSchemaSimpleContentExtension extension = (XmlSchemaSimpleContentExtension)content; - items.Attributes = extension.Attributes; - items.AnyAttribute = extension.AnyAttribute; - items.baseSimpleType = extension.BaseTypeName; + items.Attributes = simple.Attributes; + items.AnyAttribute = simple.AnyAttribute; + items.baseSimpleType = simple.BaseTypeName; } } else @@ -718,9 +715,8 @@ private TypeItems GetTypeItems(XmlSchemaType type) items.AnyAttribute = ct.AnyAttribute; particle = ct.Particle; } - if (particle is XmlSchemaGroupRef) + if (particle is XmlSchemaGroupRef refGroup) { - XmlSchemaGroupRef refGroup = (XmlSchemaGroupRef)particle; items.Particle = FindGroup(refGroup.RefName).Particle; items.IsUnbounded = particle.IsMultipleOccurrence; } @@ -898,9 +894,8 @@ private bool GatherGroupChoices(XmlSchemaGroup group, NameTable choiceElements, [RequiresUnreferencedCode("Calls ImportAny")] private bool GatherGroupChoices(XmlSchemaParticle? particle, NameTable choiceElements, string identifier, string? ns, ref bool needExplicitOrder, bool allowDuplicates) { - if (particle is XmlSchemaGroupRef) + if (particle is XmlSchemaGroupRef refGroup) { - XmlSchemaGroupRef refGroup = (XmlSchemaGroupRef)particle; if (!refGroup.RefName.IsEmpty) { AddReference(refGroup.RefName, GroupsInUse, SR.XmlCircularGroupReference); @@ -912,9 +907,8 @@ private bool GatherGroupChoices(XmlSchemaParticle? particle, NameTable choiceEle RemoveReference(refGroup.RefName, GroupsInUse); } } - else if (particle is XmlSchemaGroupBase) + else if (particle is XmlSchemaGroupBase group) { - XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle; bool groupRepeats = group.IsMultipleOccurrence; XmlSchemaAny? any = null; bool duplicateElements = false; @@ -937,9 +931,8 @@ private bool GatherGroupChoices(XmlSchemaParticle? particle, NameTable choiceEle any = (XmlSchemaAny)item; } } - else if (item is XmlSchemaElement) + else if (item is XmlSchemaElement element) { - XmlSchemaElement element = (XmlSchemaElement)item; XmlSchemaElement? headElement = GetTopLevelElement(element); if (headElement != null) { @@ -1002,9 +995,8 @@ private static void AddScopeElements(INameScope? scope, ElementAccessor[] elemen [RequiresUnreferencedCode("calls ImportChoiceGroup")] private void ImportGroupMembers(XmlSchemaParticle? particle, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, bool groupRepeats, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool allowUnboundedElements) { - if (particle is XmlSchemaGroupRef) + if (particle is XmlSchemaGroupRef refGroup) { - XmlSchemaGroupRef refGroup = (XmlSchemaGroupRef)particle; if (!refGroup.RefName.IsEmpty) { AddReference(refGroup.RefName, GroupsInUse, SR.XmlCircularGroupReference); @@ -1012,10 +1004,8 @@ private void ImportGroupMembers(XmlSchemaParticle? particle, string identifier, RemoveReference(refGroup.RefName, GroupsInUse); } } - else if (particle is XmlSchemaGroupBase) + else if (particle is XmlSchemaGroupBase group) { - XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle; - if (group.IsMultipleOccurrence) groupRepeats = true; @@ -1061,9 +1051,8 @@ private XmlSchemaElement[] GetEquivalentElements(XmlSchemaElement element) for (int j = 0; j < schema.Items.Count; j++) { object item = schema.Items[j]; - if (item is XmlSchemaElement) + if (item is XmlSchemaElement equivalentElement) { - XmlSchemaElement equivalentElement = (XmlSchemaElement)item; if (!equivalentElement.IsAbstract && equivalentElement.SubstitutionGroup.Namespace == schema.TargetNamespace && equivalentElement.SubstitutionGroup.Name == element.Name) @@ -1269,9 +1258,8 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string? arrayMapping.TypeName = identifier; arrayMapping.Namespace = ns; - if (item is XmlSchemaChoice) + if (item is XmlSchemaChoice choice) { - XmlSchemaChoice choice = (XmlSchemaChoice)item; if (!choice.IsMultipleOccurrence) return null; bool needExplicitOrder = false; @@ -1506,9 +1494,8 @@ private static bool KeepXmlnsDeclarations(XmlSchemaType type, out string? xmlnsM { foreach (XmlNode? node in nodes) { - if (node is XmlElement) + if (node is XmlElement e) { - XmlElement e = (XmlElement)node; if (e.Name == "keepNamespaceDeclarations") { if (e.LastNode is XmlText) @@ -1651,9 +1638,8 @@ private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string i if (mapping != null) return mapping; - if (dataType.Content is XmlSchemaSimpleTypeRestriction) + if (dataType.Content is XmlSchemaSimpleTypeRestriction restriction) { - XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)dataType.Content; foreach (object o in restriction.Facets) { if (o is XmlSchemaEnumerationFacet) @@ -1676,10 +1662,9 @@ private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string i } else if (dataType.Content is XmlSchemaSimpleTypeList || dataType.Content is XmlSchemaSimpleTypeUnion) { - if (dataType.Content is XmlSchemaSimpleTypeList) + // check if we have enumeration list + if (dataType.Content is XmlSchemaSimpleTypeList list) { - // check if we have enumeration list - XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)dataType.Content; if (list.ItemType != null) { mapping = ImportDataType(list.ItemType, typeNs, identifier, null, flags, true); @@ -1733,9 +1718,8 @@ private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string i CodeIdentifiers constants = new CodeIdentifiers(); XmlSchemaSimpleTypeContent? content = dataType.Content; - if (content is XmlSchemaSimpleTypeRestriction) + if (content is XmlSchemaSimpleTypeRestriction restriction) { - XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)content; for (int i = 0; i < restriction.Facets.Count; i++) { object facet = restriction.Facets[i]; @@ -1860,9 +1844,8 @@ internal static XmlQualifiedName BaseTypeName(XmlSchemaSimpleType dataType) { return ((XmlSchemaSimpleTypeRestriction)content).BaseTypeName; } - else if (content is XmlSchemaSimpleTypeList) + else if (content is XmlSchemaSimpleTypeList list) { - XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)content; if (list.ItemTypeName != null && !list.ItemTypeName.IsEmpty) return list.ItemTypeName; if (list.ItemType != null) 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 d47f7384f8a84..239f647073a23 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 @@ -324,9 +324,8 @@ public static bool IsDataSet(XmlSchema schema) { foreach (XmlSchemaObject o in schema.Items) { - if (o is XmlSchemaElement) + if (o is XmlSchemaElement e) { - XmlSchemaElement e = (XmlSchemaElement)o; if (e.UnhandledAttributes != null) { foreach (XmlAttribute a in e.UnhandledAttributes) @@ -491,9 +490,8 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) { while (item.Parent != null) { - if (item.Parent is XmlSchemaType) + if (item.Parent is XmlSchemaType type) { - XmlSchemaType type = (XmlSchemaType)item.Parent; if (type.Name != null && type.Name.Length != 0) { return type.QualifiedName; @@ -536,9 +534,8 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) { item = SR.Format(SR.XmlSchemaNamedItem, ns, "group", ((XmlSchemaGroup)o).Name, details); } - else if (o is XmlSchemaElement) + else if (o is XmlSchemaElement e) { - XmlSchemaElement e = ((XmlSchemaElement)o); if (e.Name == null || e.Name.Length == 0) { XmlQualifiedName parentName = XmlSchemas.GetParentName(o); @@ -558,9 +555,8 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) { item = SR.Format(SR.XmlSchemaNamedItem, ns, "attributeGroup", ((XmlSchemaAttributeGroup)o).Name, details); } - else if (o is XmlSchemaAttribute) + else if (o is XmlSchemaAttribute a) { - XmlSchemaAttribute a = ((XmlSchemaAttribute)o); if (a.Name == null || a.Name.Length == 0) { XmlQualifiedName parentName = XmlSchemas.GetParentName(o); 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 e9a9a7a997e73..f5f4dfbb2183e 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 @@ -1252,9 +1252,8 @@ private void UnknownNode(XmlNode? unknownNode, object? o, string? qnames) private void GetCurrentPosition(out int lineNumber, out int linePosition) { - if (Reader is IXmlLineInfo) + if (Reader is IXmlLineInfo lineInfo) { - IXmlLineInfo lineInfo = (IXmlLineInfo)Reader; lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } @@ -3096,18 +3095,18 @@ private void WriteEnumAndArrayTypes() { if (m.IsSoap) continue; - if (m is EnumMapping) + + if (m is EnumMapping enumMapping) { - EnumMapping mapping = (EnumMapping)m; Writer.Write("if ("); - WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); + WriteQNameEqual("xsiType", enumMapping.TypeName, enumMapping.Namespace); Writer.WriteLine(") {"); Writer.Indent++; Writer.WriteLine("Reader.ReadStartElement();"); - string? methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(enumMapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, enumMapping.TypeDesc!.Name)); #endif Writer.Write("object e = "); Writer.Write(methodName); @@ -3117,22 +3116,21 @@ private void WriteEnumAndArrayTypes() Writer.Indent--; Writer.WriteLine("}"); } - else if (m is ArrayMapping) + else if (m is ArrayMapping arrayMapping) { - ArrayMapping mapping = (ArrayMapping)m; - if (mapping.TypeDesc!.HasDefaultConstructor) + if (arrayMapping.TypeDesc!.HasDefaultConstructor) { Writer.Write("if ("); - WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); + WriteQNameEqual("xsiType", arrayMapping.TypeName, arrayMapping.Namespace); Writer.WriteLine(") {"); Writer.Indent++; MemberMapping memberMapping = new MemberMapping(); - memberMapping.TypeDesc = mapping.TypeDesc; - memberMapping.Elements = mapping.Elements; + memberMapping.TypeDesc = arrayMapping.TypeDesc; + memberMapping.Elements = arrayMapping.Elements; Member member = new Member(this, "a", "z", 0, memberMapping); - TypeDesc td = mapping.TypeDesc; - string fullTypeName = mapping.TypeDesc.CSharpName; + TypeDesc td = arrayMapping.TypeDesc; + string fullTypeName = arrayMapping.TypeDesc.CSharpName; if (td.UseReflection) { if (td.IsArray) @@ -3143,7 +3141,7 @@ private void WriteEnumAndArrayTypes() else Writer.Write(fullTypeName); Writer.Write(" a = "); - if (mapping.TypeDesc.IsValueType) + if (arrayMapping.TypeDesc.IsValueType) { Writer.Write(RaCodeGen.GetStringForCreateInstance(fullTypeName, td.UseReflection, false, false)); Writer.WriteLine(";"); @@ -3151,7 +3149,7 @@ private void WriteEnumAndArrayTypes() else Writer.WriteLine("null;"); - WriteArray(member.Source, member.ArrayName, mapping, false, false, -1); + WriteArray(member.Source, member.ArrayName, arrayMapping, false, false, -1); Writer.WriteLine("return a;"); Writer.Indent--; Writer.WriteLine("}"); @@ -3803,10 +3801,8 @@ private void WriteAttribute(Member member) { AttributeAccessor attribute = member.Mapping.Attribute!; - if (attribute.Mapping is SpecialMapping) + if (attribute.Mapping is SpecialMapping special) { - SpecialMapping special = (SpecialMapping)attribute.Mapping; - if (special.TypeDesc!.Kind == TypeKind.Attribute) { WriteSourceBegin(member.ArraySource); @@ -4084,9 +4080,8 @@ private void WriteText(Member member) { TextAccessor text = member.Mapping.Text!; - if (text.Mapping is SpecialMapping) + if (text.Mapping is SpecialMapping special) { - SpecialMapping special = (SpecialMapping)text.Mapping; WriteSourceBeginTyped(member.ArraySource, special.TypeDesc); switch (special.TypeDesc!.Kind) { @@ -4814,9 +4809,8 @@ private void WriteElement(string source, string? arrayName, string? choiceSource Writer.WriteLine(";"); } } - else if (element.Mapping is SpecialMapping) + else if (element.Mapping is SpecialMapping special) { - SpecialMapping special = (SpecialMapping)element.Mapping; switch (special.TypeDesc!.Kind) { case TypeKind.Node: 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 3f52cefcef674..34cc8e81b8bb7 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 @@ -1192,11 +1192,10 @@ private void WriteEnumAndArrayTypes() { foreach (Mapping m in scope.TypeMappings) { - if (m is EnumMapping) + if (m is EnumMapping enumMapping) { - EnumMapping mapping = (EnumMapping)m; ilg.InitElseIf(); - WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); + WriteQNameEqual("xsiType", enumMapping.TypeName, enumMapping.Namespace); ilg.AndIf(); MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", @@ -1211,16 +1210,16 @@ private void WriteEnumAndArrayTypes() ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); - string? methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(enumMapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, enumMapping.TypeDesc!.Name)); #endif LocalBuilder eLoc = ilg.DeclareOrGetLocal(typeof(object), "e"); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, methodName!, CodeGenerator.PrivateMethodAttributes, - mapping.TypeDesc!.Type, + enumMapping.TypeDesc!.Type, new Type[] { typeof(string) } ); MethodInfo XmlSerializationReader_CollapseWhitespace = typeof(XmlSerializationReader).GetMethod( @@ -1254,25 +1253,24 @@ private void WriteEnumAndArrayTypes() ilg.Br(ilg.ReturnLabel); // Caller own calling ilg.EndIf(); } - else if (m is ArrayMapping) + else if (m is ArrayMapping arrayMapping) { - ArrayMapping mapping = (ArrayMapping)m; - if (mapping.TypeDesc!.HasDefaultConstructor) + if (arrayMapping.TypeDesc!.HasDefaultConstructor) { ilg.InitElseIf(); - WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); + WriteQNameEqual("xsiType", arrayMapping.TypeName, arrayMapping.Namespace); ilg.AndIf(); ilg.EnterScope(); MemberMapping memberMapping = new MemberMapping(); - memberMapping.TypeDesc = mapping.TypeDesc; - memberMapping.Elements = mapping.Elements; + memberMapping.TypeDesc = arrayMapping.TypeDesc; + memberMapping.Elements = arrayMapping.Elements; string aVar = "a"; string zVar = "z"; Member member = new Member(this, aVar, zVar, 0, memberMapping); - TypeDesc td = mapping.TypeDesc; - LocalBuilder aLoc = ilg.DeclareLocal(mapping.TypeDesc.Type!, aVar); - if (mapping.TypeDesc.IsValueType) + TypeDesc td = arrayMapping.TypeDesc; + LocalBuilder aLoc = ilg.DeclareLocal(arrayMapping.TypeDesc.Type!, aVar); + if (arrayMapping.TypeDesc.IsValueType) { ReflectionAwareILGen.ILGenForCreateInstance(ilg, td.Type!, false, false); } @@ -1280,7 +1278,7 @@ private void WriteEnumAndArrayTypes() ilg.Load(null); ilg.Stloc(aLoc); - WriteArray(member.Source, member.ArrayName, mapping, false, false, -1, 0); + WriteArray(member.Source, member.ArrayName, arrayMapping, false, false, -1, 0); ilg.Ldloc(aLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); @@ -2066,10 +2064,8 @@ private void WriteAttribute(Member member) { AttributeAccessor attribute = member.Mapping.Attribute!; - if (attribute.Mapping is SpecialMapping) + if (attribute.Mapping is SpecialMapping special) { - SpecialMapping special = (SpecialMapping)attribute.Mapping; - if (special.TypeDesc!.Kind == TypeKind.Attribute) { WriteSourceBegin(member.ArraySource); @@ -2354,9 +2350,8 @@ private void WriteText(Member member) { TextAccessor text = member.Mapping.Text!; - if (text.Mapping is SpecialMapping) + if (text.Mapping is SpecialMapping special) { - SpecialMapping special = (SpecialMapping)text.Mapping; WriteSourceBeginTyped(member.ArraySource, special.TypeDesc); switch (special.TypeDesc!.Kind) { @@ -3215,9 +3210,8 @@ private void WriteElement(string source, string? arrayName, string? choiceSource // 'If' begins in checkForNull above ilg.EndIf(); } - else if (element.Mapping is SpecialMapping) + else if (element.Mapping is SpecialMapping special) { - SpecialMapping special = (SpecialMapping)element.Mapping; switch (special.TypeDesc!.Kind) { case TypeKind.Node: 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 11449885a9a6e..bf943459b78ce 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 @@ -3431,9 +3431,8 @@ private void WriteMember(string source, AttributeAccessor attribute, TypeDesc me [RequiresUnreferencedCode("calls WritePrimitive")] private void WriteAttribute(string source, AttributeAccessor attribute, string parent) { - if (attribute.Mapping is SpecialMapping) + if (attribute.Mapping is SpecialMapping special) { - SpecialMapping special = (SpecialMapping)attribute.Mapping; if (special.TypeDesc!.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) { Writer.Write("WriteXmlAttribute("); @@ -3848,9 +3847,8 @@ private void WriteElements(string source, string? enumSource, ElementAccessor[] private void WriteText(string source, TextAccessor text) { - if (text.Mapping is PrimitiveMapping) + if (text.Mapping is PrimitiveMapping primitive) { - PrimitiveMapping mapping = (PrimitiveMapping)text.Mapping; Writer.Write("WriteValue("); if (text.Mapping is EnumMapping) { @@ -3858,14 +3856,13 @@ private void WriteText(string source, TextAccessor text) } else { - WritePrimitiveValue(mapping.TypeDesc!, source, false); + WritePrimitiveValue(primitive.TypeDesc!, source, false); } Writer.WriteLine(");"); } - else if (text.Mapping is SpecialMapping) + else if (text.Mapping is SpecialMapping simple) { - SpecialMapping mapping = (SpecialMapping)text.Mapping; - switch (mapping.TypeDesc!.Kind) + switch (simple.TypeDesc!.Kind) { case TypeKind.Node: Writer.Write(source); @@ -3906,10 +3903,9 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa Writer.WriteLine("}"); } } - else if (element.Mapping is ArrayMapping) + else if (element.Mapping is ArrayMapping arrayMapping) { - ArrayMapping mapping = (ArrayMapping)element.Mapping; - if (mapping.IsSoap) + if (arrayMapping.IsSoap) { Writer.Write("WritePotentiallyReferencingElement("); WriteQuotedCSharpString(name); @@ -3920,7 +3916,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa if (!writeAccessor) { Writer.Write(", "); - Writer.Write(RaCodeGen.GetStringForTypeof(mapping.TypeDesc!.CSharpName, mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForTypeof(arrayMapping.TypeDesc!.CSharpName, arrayMapping.TypeDesc.UseReflection)); Writer.Write(", true, "); } else @@ -3932,20 +3928,20 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } else if (element.IsUnbounded) { - TypeDesc td = mapping.TypeDesc!.CreateArrayTypeDesc(); + TypeDesc td = arrayMapping.TypeDesc!.CreateArrayTypeDesc(); string fullTypeName = td.CSharpName; string elementArrayName = $"el{arrayName}"; string arrayIndex = $"c{elementArrayName}"; Writer.WriteLine("{"); Writer.Indent++; - WriteArrayLocalDecl(fullTypeName, elementArrayName, source, mapping.TypeDesc); + WriteArrayLocalDecl(fullTypeName, elementArrayName, source, arrayMapping.TypeDesc); if (element.IsNullable) { WriteNullCheckBegin(elementArrayName, element); } else { - if (mapping.TypeDesc.IsNullable) + if (arrayMapping.TypeDesc.IsNullable) { Writer.Write("if ("); Writer.Write(elementArrayName); @@ -3993,17 +3989,17 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } else { - string fullTypeName = mapping.TypeDesc!.CSharpName; + string fullTypeName = arrayMapping.TypeDesc!.CSharpName; Writer.WriteLine("{"); Writer.Indent++; - WriteArrayLocalDecl(fullTypeName, arrayName, source, mapping.TypeDesc); + WriteArrayLocalDecl(fullTypeName, arrayName, source, arrayMapping.TypeDesc); if (element.IsNullable) { WriteNullCheckBegin(arrayName, element); } else { - if (mapping.TypeDesc.IsNullable) + if (arrayMapping.TypeDesc.IsNullable) { Writer.Write("if ("); Writer.Write(arrayName); @@ -4013,7 +4009,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa Writer.Indent++; } WriteStartElement(name, ns, false); - WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, arrayName, null); + WriteArrayItems(arrayMapping.ElementsSortedByDerivation!, null, null, arrayMapping.TypeDesc, arrayName, null); WriteEndElement(); Writer.Indent--; Writer.WriteLine("}"); @@ -4042,24 +4038,21 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa WritePrimitive("WriteElementString", name, ns, element.Default, source, element.Mapping, false, true, element.IsNullable); } } - else if (element.Mapping is PrimitiveMapping) + else if (element.Mapping is PrimitiveMapping primitiveMapping) { - PrimitiveMapping mapping = (PrimitiveMapping)element.Mapping; - if (mapping.TypeDesc == QnameTypeDesc) - WriteQualifiedNameElement(name, ns, element.Default, source, element.IsNullable, mapping.IsSoap, mapping); + if (primitiveMapping.TypeDesc == QnameTypeDesc) + WriteQualifiedNameElement(name, ns, element.Default, source, element.IsNullable, primitiveMapping.IsSoap, primitiveMapping); else { - string suffixNullable = mapping.IsSoap ? "Encoded" : "Literal"; - string suffixRaw = mapping.TypeDesc!.XmlEncodingNotRequired ? "Raw" : ""; + string suffixNullable = primitiveMapping.IsSoap ? "Encoded" : "Literal"; + string suffixRaw = primitiveMapping.TypeDesc!.XmlEncodingNotRequired ? "Raw" : ""; WritePrimitive(element.IsNullable ? ("WriteNullableString" + suffixNullable + suffixRaw) : ("WriteElementString" + suffixRaw), - name, ns, element.Default, source, mapping, mapping.IsSoap, true, element.IsNullable); + name, ns, element.Default, source, primitiveMapping, primitiveMapping.IsSoap, true, element.IsNullable); } } - else if (element.Mapping is StructMapping) + else if (element.Mapping is StructMapping structMapping) { - StructMapping mapping = (StructMapping)element.Mapping; - - if (mapping.IsSoap) + if (structMapping.IsSoap) { Writer.Write("WritePotentiallyReferencingElement("); WriteQuotedCSharpString(name); @@ -4070,7 +4063,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa if (!writeAccessor) { Writer.Write(", "); - Writer.Write(RaCodeGen.GetStringForTypeof(mapping.TypeDesc!.CSharpName, mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForTypeof(structMapping.TypeDesc!.CSharpName, structMapping.TypeDesc.UseReflection)); Writer.Write(", true, "); } else @@ -4081,11 +4074,11 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } else { - string? methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(structMapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name) + Environment.StackTrace); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, structMapping.TypeDesc!.Name) + Environment.StackTrace); #endif Writer.Write(methodName); Writer.Write("("); @@ -4099,7 +4092,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } Writer.Write(", "); Writer.Write(source); - if (mapping.TypeDesc!.IsNullable) + if (structMapping.TypeDesc!.IsNullable) { Writer.Write(", "); WriteValue(element.IsNullable); 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 18ab8b6e1481e..df965008c18f3 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 @@ -1368,9 +1368,8 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes [RequiresUnreferencedCode("calls WritePrimitive")] private void WriteAttribute(SourceInfo source, AttributeAccessor attribute, string parent) { - if (attribute.Mapping is SpecialMapping) + if (attribute.Mapping is SpecialMapping special) { - SpecialMapping special = (SpecialMapping)attribute.Mapping; if (special.TypeDesc!.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) { System.Diagnostics.Debug.Assert(parent == "o" || parent == "p"); @@ -1864,9 +1863,8 @@ private void WriteElements(SourceInfo source, string? enumSource, ElementAccesso [RequiresUnreferencedCode("calls Load")] private void WriteText(SourceInfo source, TextAccessor text) { - if (text.Mapping is PrimitiveMapping) + if (text.Mapping is PrimitiveMapping primitiveMapping) { - PrimitiveMapping mapping = (PrimitiveMapping)text.Mapping; Type argType; ilg.Ldarg(0); if (text.Mapping is EnumMapping) @@ -1875,7 +1873,7 @@ private void WriteText(SourceInfo source, TextAccessor text) } else { - WritePrimitiveValue(mapping.TypeDesc!, source, out argType); + WritePrimitiveValue(primitiveMapping.TypeDesc!, source, out argType); } MethodInfo XmlSerializationWriter_WriteValue = typeof(XmlSerializationWriter).GetMethod( "WriteValue", @@ -1884,10 +1882,9 @@ private void WriteText(SourceInfo source, TextAccessor text) )!; ilg.Call(XmlSerializationWriter_WriteValue); } - else if (text.Mapping is SpecialMapping) + else if (text.Mapping is SpecialMapping specialMapping) { - SpecialMapping mapping = (SpecialMapping)text.Mapping; - switch (mapping.TypeDesc!.Kind) + switch (specialMapping.TypeDesc!.Kind) { case TypeKind.Node: MethodInfo WriteTo = source.Type!.GetMethod( @@ -1946,9 +1943,8 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr } ilg.EndIf(); } - else if (element.Mapping is ArrayMapping) + else if (element.Mapping is ArrayMapping arrayMapping) { - ArrayMapping mapping = (ArrayMapping)element.Mapping; if (element.IsUnbounded) { throw Globals.NotSupported("Unreachable: IsUnbounded is never set true!"); @@ -1956,15 +1952,15 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr else { ilg.EnterScope(); - string fullTypeName = mapping.TypeDesc!.CSharpName; - WriteArrayLocalDecl(fullTypeName, arrayName, source, mapping.TypeDesc); + string fullTypeName = arrayMapping.TypeDesc!.CSharpName; + WriteArrayLocalDecl(fullTypeName, arrayName, source, arrayMapping.TypeDesc); if (element.IsNullable) { WriteNullCheckBegin(arrayName, element); } else { - if (mapping.TypeDesc.IsNullable) + if (arrayMapping.TypeDesc.IsNullable) { ilg.Ldloc(ilg.GetLocal(arrayName)); ilg.Load(null); @@ -1972,7 +1968,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr } } WriteStartElement(name, ns, false); - WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, arrayName, null); + WriteArrayItems(arrayMapping.ElementsSortedByDerivation!, null, null, arrayMapping.TypeDesc, arrayName, null); WriteEndElement(); if (element.IsNullable) { @@ -1980,7 +1976,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr } else { - if (mapping.TypeDesc.IsNullable) + if (arrayMapping.TypeDesc.IsNullable) { ilg.EndIf(); } @@ -1992,27 +1988,26 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr { WritePrimitive("WriteElementString", name, ns, element.Default, source, element.Mapping, false, true, element.IsNullable); } - else if (element.Mapping is PrimitiveMapping) + else if (element.Mapping is PrimitiveMapping primitiveMapping) { - PrimitiveMapping mapping = (PrimitiveMapping)element.Mapping; - if (mapping.TypeDesc == QnameTypeDesc) - WriteQualifiedNameElement(name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, element.IsNullable, mapping); + if (primitiveMapping.TypeDesc == QnameTypeDesc) + { + WriteQualifiedNameElement(name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, element.IsNullable, primitiveMapping); + } else { - string suffixRaw = mapping.TypeDesc!.XmlEncodingNotRequired ? "Raw" : ""; + string suffixRaw = primitiveMapping.TypeDesc!.XmlEncodingNotRequired ? "Raw" : ""; WritePrimitive(element.IsNullable ? ("WriteNullableStringLiteral" + suffixRaw) : ("WriteElementString" + suffixRaw), - name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, mapping, false, true, element.IsNullable); + name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, primitiveMapping, false, true, element.IsNullable); } } - else if (element.Mapping is StructMapping) + else if (element.Mapping is StructMapping structMapping) { - StructMapping mapping = (StructMapping)element.Mapping; - - string? methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(structMapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, structMapping.TypeDesc!.Name)); #endif List argTypes = new List(); ilg.Ldarg(0); @@ -2020,9 +2015,9 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr argTypes.Add(typeof(string)); ilg.Ldstr(GetCSharpString(ns)); argTypes.Add(typeof(string)); - source.Load(mapping.TypeDesc!.Type); - argTypes.Add(mapping.TypeDesc.Type!); - if (mapping.TypeDesc.IsNullable) + source.Load(structMapping.TypeDesc!.Type); + argTypes.Add(structMapping.TypeDesc.Type!); + if (structMapping.TypeDesc.IsNullable) { ilg.Ldc(element.IsNullable); argTypes.Add(typeof(bool)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs index cc50d72f09a71..dc048410ebd7c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs @@ -489,9 +489,8 @@ private XmlMapping GetMapping() if (e is TargetInvocationException) e = e.InnerException; - if (xmlReader is IXmlLineInfo) + if (xmlReader is IXmlLineInfo lineInfo) { - IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader; throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e); } else 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 670aff81778bb..7946d52b56a2d 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 @@ -153,10 +153,8 @@ protected override QilNode VisitChildren(QilNode node) this.writer.WriteValue(Convert.ToString(((QilLiteral)node).Value, CultureInfo.InvariantCulture)); return node; } - else if (node is QilReference) + else if (node is QilReference reference) { - QilReference reference = (QilReference)node; - // Write the generated identifier for this iterator this.writer.WriteAttributeString("id", _ngen.NameOf(node)); From a705ce1f8f552e66a85977bf174c6152194e9683 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Thu, 16 Jun 2022 16:58:19 -0400 Subject: [PATCH 2/3] Update src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs Co-authored-by: Buyaa Namnan --- .../src/System/Xml/Serialization/XmlSerializationWriter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 bf943459b78ce..3c6c9c85a2f02 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 @@ -3850,9 +3850,9 @@ private void WriteText(string source, TextAccessor text) if (text.Mapping is PrimitiveMapping primitive) { Writer.Write("WriteValue("); - if (text.Mapping is EnumMapping) + if (text.Mapping is EnumMapping enum) { - WriteEnumValue((EnumMapping)text.Mapping, source); + WriteEnumValue(enum, source); } else { From 3f878a1602bca30e5bd478fb718887c51ea782bf Mon Sep 17 00:00:00 2001 From: Buyaa Namnan Date: Thu, 16 Jun 2022 15:11:55 -0700 Subject: [PATCH 3/3] Update variable naming --- .../src/System/Xml/Serialization/XmlSerializationWriter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 3c6c9c85a2f02..dd7a49f244d8f 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 @@ -3850,9 +3850,9 @@ private void WriteText(string source, TextAccessor text) if (text.Mapping is PrimitiveMapping primitive) { Writer.Write("WriteValue("); - if (text.Mapping is EnumMapping enum) + if (text.Mapping is EnumMapping enumMapping) { - WriteEnumValue(enum, source); + WriteEnumValue(enumMapping, source); } else {