From 9b0621d1f68a6d212b30150a603cae2815517869 Mon Sep 17 00:00:00 2001 From: 0xd4d Date: Wed, 11 Nov 2020 20:44:14 +0100 Subject: [PATCH] Use is not null --- .../ConvertToNetstandardReferences.cs | 4 +- DnSpyCommon.props | 2 +- .../Example1.Extension/CodeCtxMenus.cs | 8 +- .../Example1.Extension/TreeViewCtxMenus.cs | 8 +- .../AssemblyChildNodeTabContent.cs | 2 +- .../Example2.Extension/NewDsDocument.cs | 2 +- .../Example2.Extension/OutputTextPane.cs | 2 +- .../CSharp/AssemblyInfoTransform.cs | 2 +- .../CSharp/CSharpDecompiler.cs | 12 +- .../CSharp/DecompilePartialTransform.cs | 8 +- .../CSharp/DecompileTypeMethodsTransform.cs | 18 +- .../IL/ILDecompiler.cs | 14 +- .../ILAst/ILAstDecompiler.cs | 28 +-- .../Settings/CSharpVBDecompilerSettings.cs | 2 +- .../Settings/ILSettings.cs | 2 +- .../VisualBasic/ILSpyEnvironmentProvider.cs | 10 +- .../VisualBasic/VBDecompiler.cs | 6 +- .../VisualBasic/VBTextOutputFormatter.cs | 62 ++--- .../XmlDoc/AddXmlDocTransform.cs | 6 +- .../XmlDoc/XmlDocLine.cs | 2 +- .../Settings/CSharpDecompilerSettingsPage.cs | 2 +- .../DecompilerAppSettingsModifiedListener.cs | 2 +- Extensions/dnSpy.Analyzer/AnalyzerService.cs | 20 +- Extensions/dnSpy.Analyzer/Commands.cs | 4 +- .../TreeNodes/AttributeAppliedToNode.cs | 14 +- .../dnSpy.Analyzer/TreeNodes/Commands.cs | 18 +- .../TreeNodes/EventAccessorNode.cs | 2 +- .../TreeNodes/EventFiredByNode.cs | 8 +- .../dnSpy.Analyzer/TreeNodes/EventNode.cs | 6 +- .../TreeNodes/EventOverriddenNode.cs | 8 +- .../TreeNodes/EventOverridesNode.cs | 2 +- .../TreeNodes/FieldAccessNode.cs | 2 +- .../dnSpy.Analyzer/TreeNodes/Helpers.cs | 6 +- .../InterfaceEventImplementedByNode.cs | 4 +- .../InterfaceMethodImplementedByNode.cs | 4 +- .../InterfacePropertyImplementedByNode.cs | 2 +- .../TreeNodes/MethodOverriddenNode.cs | 2 +- .../TreeNodes/MethodUsedByNode.cs | 12 +- .../TreeNodes/MethodUsesNode.cs | 4 +- .../TreeNodes/PropertyAccessorNode.cs | 2 +- .../dnSpy.Analyzer/TreeNodes/PropertyNode.cs | 4 +- .../TreeNodes/PropertyOverriddenNode.cs | 8 +- .../TreeNodes/PropertyOverridesNode.cs | 2 +- .../TreeNodes/ScopedWhereUsedAnalyzer.cs | 4 +- .../dnSpy.Analyzer/TreeNodes/SearchNode.cs | 16 +- .../TreeNodes/TypeExposedByNode.cs | 12 +- .../TreeNodes/TypeExtensionMethodsNode.cs | 2 +- .../TreeNodes/TypeInstantiationsNode.cs | 2 +- .../TreeNodes/TypeUsedByNode.cs | 12 +- .../TreeNodes/VirtualMethodUsedByNode.cs | 10 +- Extensions/dnSpy.Analyzer/TreeTraversal.cs | 4 +- .../Assembly/AssemblyCommands.cs | 12 +- .../Commands/CloseAllMissingFilesCommand.cs | 4 +- .../CloseOldInMemoryModulesCommand.cs | 4 +- .../CodeContextMenuHandlerCommandProxy.cs | 6 +- .../dnSpy.AsmEditor/Commands/CommandUtils.cs | 4 +- .../Commands/DeletableNodes.cs | 4 +- .../Commands/DeletedTypeUpdater.cs | 4 +- .../Commands/DocumentsContextMenuHandler.cs | 2 +- .../Commands/EditMenuHandlerCommandProxy.cs | 6 +- .../Commands/EventNodeCreator.cs | 6 +- .../Commands/IndexObservableCollection.cs | 4 +- .../Commands/InstructionCommands.cs | 4 +- .../Commands/ListBoxHelperBase.cs | 10 +- .../Commands/NestedTypeNodeCreator.cs | 4 +- .../dnSpy.AsmEditor/Commands/RefFinder.cs | 2 +- .../Commands/RootDocumentNodeCreator.cs | 6 +- .../Commands/TypeNodeCreator.cs | 2 +- .../Compiler/AddClassCommands.cs | 8 +- .../Compiler/AddClassMembersCommands.cs | 8 +- .../Compiler/AddMembersCodeVM.cs | 2 +- .../Compiler/AddUpdatedNodesHelper.cs | 34 +-- .../dnSpy.AsmEditor/Compiler/Commands.cs | 10 +- .../Compiler/EditAssemblyCommands.cs | 8 +- .../Compiler/EditClassCommands.cs | 12 +- .../dnSpy.AsmEditor/Compiler/EditClassVM.cs | 2 +- .../Compiler/EditCodeDlg.xaml.cs | 2 +- .../dnSpy.AsmEditor/Compiler/EditCodeVM.cs | 18 +- .../Compiler/EditCodeVMCreator.cs | 2 +- .../Compiler/EditMethodCodeVM.cs | 2 +- .../Compiler/ExistingTypeNodeUpdater.cs | 6 +- .../Compiler/ImportSigComparer.cs | 218 +++++++++--------- .../Compiler/MDEditor/BlobMDHeap.cs | 2 +- .../Compiler/MDEditor/GuidMDHeap.cs | 2 +- .../MDEditor/ImageCor20HeaderSectionData.cs | 2 +- .../Compiler/MDEditor/MDWriter.cs | 2 +- .../Compiler/MDEditor/StringsMDHeap.cs | 2 +- .../Compiler/MDEditor/TablesHeapWriter.cs | 6 +- .../Compiler/MDEditor/TablesMDHeap.cs | 2 +- .../Compiler/MDEditor/USMDHeap.cs | 2 +- .../Compiler/MDEditor/UnknownMDHeap.cs | 2 +- .../Compiler/MDEditorPatcher.cs | 8 +- .../Compiler/MDPatcherUtils.cs | 4 +- .../Compiler/MergeWithAssemblyCommand.cs | 8 +- .../Compiler/MetadataReferenceFinder.cs | 8 +- .../Compiler/ModuleImporter.MemberLookup.cs | 6 +- .../Compiler/ModuleImporter.cs | 118 +++++----- .../ModuleImporterAssemblyResolver.cs | 2 +- .../dnSpy.AsmEditor/Compiler/ModulePatcher.cs | 2 +- .../Compiler/RawModuleBytes.cs | 2 +- .../Compiler/RawModuleBytesProvider.cs | 2 +- .../Compiler/RemappedTypeTokens.cs | 2 +- .../Compiler/ResourceNodeCreator.cs | 2 +- .../dnSpy.AsmEditor/Compiler/TIAHelper.cs | 6 +- .../Converters/CilObjectConverter.cs | 2 +- .../DnlibDialogs/CAArgumentVM.cs | 14 +- .../DnlibDialogs/CANamedArgumentVM.cs | 6 +- .../DnlibDialogs/ConstantTypeVM.cs | 2 +- .../BooleanToGridrowLengthConverter.cs | 2 +- .../DnlibDialogs/CreateTypeSigArrayVM.cs | 6 +- .../DnlibDialogs/CustomAttributeOptions.cs | 2 +- .../DnlibDialogs/CustomAttributeVM.cs | 12 +- .../DnlibDialogs/EnumDataFieldVM.cs | 16 +- .../DnlibDialogs/GenericParamVM.cs | 4 +- .../dnSpy.AsmEditor/DnlibDialogs/ImplMapVM.cs | 2 +- .../dnSpy.AsmEditor/DnlibDialogs/ListVM.cs | 4 +- .../DnlibDialogs/MarshalTypeVM.cs | 6 +- .../DnlibDialogs/MemberPickerVM.cs | 10 +- .../DnlibDialogs/MemberRefVM.cs | 16 +- .../DnlibDialogs/MethodDefVM.cs | 2 +- .../DnlibDialogs/MethodSigCreatorVM.cs | 8 +- .../DnlibDialogs/MethodSpecVM.cs | 4 +- .../DnlibDialogs/ModelUtils.cs | 4 +- .../DnlibDialogs/ObjectListDataFieldVM.cs | 4 +- .../DnlibDialogs/ParamDefVM.cs | 2 +- .../DnlibDialogs/SecurityAttributeVM.cs | 6 +- .../DnlibDialogs/TypeDefOrRefAndCAVM.cs | 4 +- .../DnlibDialogs/TypeDefOrRefAndCAsVM.cs | 2 +- .../DnlibDialogs/TypeSigCreatorVM.cs | 18 +- .../dnSpy.AsmEditor/DnlibDialogs/TypeSigVM.cs | 6 +- .../dnSpy.AsmEditor/Event/EventDefCommands.cs | 18 +- .../dnSpy.AsmEditor/Event/EventOptionsVM.cs | 14 +- .../dnSpy.AsmEditor/Field/FieldDefCommands.cs | 18 +- .../dnSpy.AsmEditor/Field/FieldOptionsVM.cs | 4 +- Extensions/dnSpy.AsmEditor/Hex/Commands.cs | 92 ++++---- ...xAddressReferenceFileTabContentProvider.cs | 4 +- .../Hex/HexBoxDocumentTabContent.cs | 2 +- .../dnSpy.AsmEditor/Hex/HexBufferService.cs | 8 +- .../Hex/HexUndoableDocumentsProvider.cs | 4 +- .../Hex/MDTableContextMenuCommands.cs | 18 +- .../dnSpy.AsmEditor/Hex/Nodes/HexNode.cs | 2 +- .../Hex/Nodes/ImageCor20HeaderNode.cs | 2 +- .../Hex/Nodes/MetadataTableRecordNode.cs | 4 +- .../dnSpy.AsmEditor/Hex/Nodes/PENode.cs | 8 +- .../Hex/Nodes/PETreeNodeDataProvider.cs | 10 +- .../Hex/Nodes/TablesStreamNode.cs | 2 +- ...okenReferenceDocumentTabContentProvider.cs | 2 +- Extensions/dnSpy.AsmEditor/Hex/PE/HexField.cs | 4 +- .../PE/HexFileStructureInfoProviderImpl.cs | 24 +- .../Hex/PE/MetadataTableRecordVM.cs | 4 +- .../dnSpy.AsmEditor/Hex/PE/MetadataTableVM.cs | 2 +- .../Hex/PE/PEStructureProvider.cs | 6 +- .../Method/MethodDefCommands.cs | 22 +- .../Method/MethodDefOptions.cs | 2 +- .../dnSpy.AsmEditor/Method/MethodOptionsVM.cs | 2 +- .../dnSpy.AsmEditor/MethodBody/BodyUtils.cs | 6 +- .../dnSpy.AsmEditor/MethodBody/CilBodyVM.cs | 18 +- .../MethodBody/ExceptionHandlerVM.cs | 6 +- .../MethodBody/ExceptionHandlersListHelper.cs | 4 +- .../MethodBody/FastClickButton.cs | 2 +- .../MethodBody/InstructionOperandControl.cs | 4 +- .../MethodBody/InstructionOperandVM.cs | 16 +- .../MethodBody/InstructionVM.cs | 2 +- .../MethodBody/InstructionsListHelper.cs | 12 +- .../MethodBody/LocalsListHelper.cs | 2 +- .../MethodBody/MethodBodyCommands.cs | 8 +- .../MethodBody/SwitchOperandVM.cs | 2 +- .../dnSpy.AsmEditor/Module/ModuleCommands.cs | 52 ++--- .../dnSpy.AsmEditor/Module/ModuleOptions.cs | 2 +- .../dnSpy.AsmEditor/Module/ModuleOptionsVM.cs | 18 +- .../Namespace/NamespaceCommands.cs | 28 +-- .../Property/PropertyDefCommands.cs | 12 +- .../Property/PropertyOptionsVM.cs | 4 +- .../Resources/ImageResourceElementVM.cs | 2 +- .../Resources/NodeAndResource.cs | 2 +- .../Resources/NodeAndResourceElement.cs | 2 +- .../Resources/ResourceCommands.cs | 62 ++--- .../Resources/ResourceElementControl.xaml.cs | 6 +- .../Resources/ResourceElementVM.cs | 2 +- .../Resources/ResourceOptions.cs | 4 +- .../dnSpy.AsmEditor/Resources/ResourceVM.cs | 4 +- .../dnSpy.AsmEditor/Resources/UserTypeVM.cs | 2 +- .../SaveModule/DocumentSaver.cs | 8 +- .../SaveModule/MmapDisabler.cs | 4 +- .../dnSpy.AsmEditor/SaveModule/ModuleSaver.cs | 2 +- .../SaveModule/SaveModuleCommand.cs | 6 +- .../SaveModule/SaveModuleOptionsVM.cs | 8 +- .../SaveModule/SaveMultiModuleVM.cs | 4 +- Extensions/dnSpy.AsmEditor/TheExtension.cs | 2 +- .../dnSpy.AsmEditor/Types/TypeDefCommands.cs | 30 +-- .../dnSpy.AsmEditor/Types/TypeDefOptions.cs | 2 +- .../dnSpy.AsmEditor/Types/TypeOptionsVM.cs | 4 +- .../DsDocumentUndoableDocumentsProvider.cs | 14 +- .../UndoRedo/UndoCommandService.cs | 32 +-- .../ViewHelpers/CreateTypeSigArray.cs | 2 +- .../ViewHelpers/EditCustomAttribute.cs | 2 +- .../ViewHelpers/EditDeclSecurity.cs | 2 +- .../ViewHelpers/EditGenericParam.cs | 2 +- .../dnSpy.AsmEditor/ViewHelpers/EditImage.cs | 2 +- .../ViewHelpers/EditMemberRef.cs | 2 +- .../ViewHelpers/EditMethodSpec.cs | 2 +- .../ViewHelpers/EditParamDef.cs | 2 +- .../ViewHelpers/EditSecurityAttribute.cs | 2 +- .../ViewHelpers/EditTypeDefOrRefAndCA.cs | 2 +- .../ViewHelpers/OpenAssembly.cs | 2 +- .../dnSpy.BamlDecompiler/Baml/BamlNode.cs | 2 +- .../dnSpy.BamlDecompiler/Baml/BamlRecords.cs | 2 +- .../dnSpy.BamlDecompiler/Baml/KnownThings.cs | 2 +- .../dnSpy.BamlDecompiler/BamlDisassembler.cs | 6 +- .../PropertyWithStaticResourceIdHandler.cs | 2 +- Extensions/dnSpy.BamlDecompiler/IHandlers.cs | 4 +- .../Rewrite/ConnectionIdRewritePass.cs | 8 +- .../Rewrite/MarkupExtensionRewritePass.cs | 6 +- .../Xaml/XamlExtension.cs | 2 +- .../dnSpy.BamlDecompiler/Xaml/XamlProperty.cs | 10 +- .../Xaml/XamlResourceKey.cs | 2 +- .../dnSpy.BamlDecompiler/Xaml/XamlType.cs | 6 +- .../dnSpy.BamlDecompiler/XamlContext.cs | 4 +- .../dnSpy.BamlDecompiler/XamlDecompiler.cs | 2 +- .../dnSpy.BamlDecompiler/XmlnsDictionary.cs | 6 +- .../AppHostInfoGenerator/Program.cs | 4 +- .../AntiAntiDebug/CorDebugUtils.cs | 4 +- .../AntiAntiDebug/ECallManager.cs | 4 +- .../ManagedDebuggerPatcherX86.cs | 2 +- ...BreakpointLocationFormatterProviderImpl.cs | 2 +- .../DbgBreakpointGlyphFormatterImpl.cs | 6 +- .../CallStack/DbgEngineStackWalkerImpl.cs | 2 +- .../CallStack/ILDbgEngineStackFrame.cs | 2 +- .../DAC/ClrDacImpl.cs | 6 +- .../DAC/ClrDacProvider.cs | 2 +- .../AttachToProcess/DebuggableProcesses.cs | 2 +- .../DotNetCommonStartDebuggingOptionsPage.cs | 2 +- .../Impl/AppHostUtils.cs | 2 +- .../Impl/DbgEngineImpl.Breakpoints.cs | 4 +- .../Impl/DbgEngineImpl.Evaluation.cs | 36 +-- .../Impl/DbgEngineImpl.ModuleDef.cs | 6 +- .../Impl/DbgEngineImpl.Threads.cs | 24 +- .../Impl/DbgEngineImpl.cs | 52 ++--- .../Impl/DebuggerThread.cs | 2 +- .../Impl/DmdDynamicModuleHelperImpl.cs | 2 +- .../Impl/DnlibAssemblyResolverImpl.cs | 2 +- .../Impl/DotNetDbgEngineImpl.cs | 2 +- .../Impl/DotNetDbgProcessStarter.cs | 2 +- .../Impl/DotNetFrameworkDbgEngineImpl.cs | 2 +- ...gCorDebugInternalRuntimeImpl.NativeCode.cs | 2 +- .../DbgCorDebugInternalRuntimeImpl.cs | 54 ++--- .../Evaluation/DbgDotNetRawValueFactory.cs | 8 +- .../Impl/Evaluation/DbgDotNetValueImpl.cs | 2 +- .../Impl/Evaluation/DmdEvaluatorImpl.cs | 6 +- .../Impl/Evaluation/EvalArgumentConverter.cs | 42 ++-- .../Hooks/CorDebugValueConverterImpl.cs | 4 +- .../Impl/Evaluation/NullableTypeUtils.cs | 4 +- .../Impl/ModuleCreator.cs | 4 +- .../Metadata/DbgAssemblyInfoProviderImpl.cs | 2 +- .../Metadata/DbgDynamicModuleProviderImpl.cs | 12 +- .../Steppers/DbgDotNetEngineStepperImpl.cs | 38 +-- .../Utilities/DotNetHelpers.cs | 2 +- .../dndbg/DotNet/CorDeclSecurity.cs | 2 +- .../dndbg/DotNet/CorModuleDef.cs | 22 +- .../dndbg/DotNet/CorPropertyDef.cs | 2 +- .../dndbg/DotNet/CorTypeDef.cs | 10 +- .../dndbg/DotNet/CorTypeSpec.cs | 2 +- .../dndbg/Engine/COMObject.cs | 4 +- .../dndbg/Engine/CorAppDomain.cs | 2 +- .../dndbg/Engine/CorAssembly.cs | 4 +- .../dndbg/Engine/CorChain.cs | 2 +- .../dndbg/Engine/CorClass.cs | 2 +- .../dndbg/Engine/CorCode.cs | 2 +- .../dndbg/Engine/CorEval.cs | 8 +- .../dndbg/Engine/CorFrame.cs | 4 +- .../dndbg/Engine/CorFunction.cs | 8 +- .../dndbg/Engine/CorFunctionBreakpoint.cs | 2 +- .../dndbg/Engine/CorMDA.cs | 2 +- .../dndbg/Engine/CorModule.cs | 4 +- .../dndbg/Engine/CorModuleDefHelper.cs | 10 +- .../dndbg/Engine/CorProcess.cs | 2 +- .../dndbg/Engine/CorStepper.cs | 2 +- .../dndbg/Engine/CorThread.cs | 2 +- .../dndbg/Engine/CorType.cs | 2 +- .../dndbg/Engine/CorValue.cs | 4 +- .../dndbg/Engine/CoreCLRHelper.cs | 2 +- .../dndbg/Engine/DebugCallbackEventArgs.cs | 2 +- .../dndbg/Engine/DebuggerCollection.cs | 2 +- .../dndbg/Engine/DebuggerState.cs | 6 +- .../dndbg/Engine/DnAssembly.cs | 4 +- .../dndbg/Engine/DnDebugger.cs | 90 ++++---- .../dndbg/Engine/DnEval.cs | 8 +- .../dndbg/Engine/DnModule.cs | 4 +- .../dndbg/Engine/DnProcess.cs | 2 +- .../ILValue.cs | 2 +- .../Impl/DebuggerILInterpreter.cs | 100 ++++---- .../Tests/FakeDebuggerRuntime.cs | 2 +- .../Tests/InterpreterTest.cs | 2 +- .../CustomAttributesHelper.cs | 76 +++--- .../DmdAppDomain.cs | 2 +- .../DmdAssembly.cs | 6 +- .../DmdAssemblyName.cs | 2 +- .../DmdAssemblyNameFormatter.cs | 6 +- .../DmdMemberFormatter.cs | 14 +- .../DmdObject.cs | 2 +- .../DmdPropertyInfo.cs | 4 +- .../DmdReadOnlyAssemblyName.cs | 2 +- .../DmdSigComparer.cs | 4 +- .../dnSpy.Debugger.DotNet.Metadata/DmdType.cs | 8 +- .../DmdTypeName.cs | 6 +- .../DmdWellKnownTypeUtils.cs | 2 +- .../Impl/COMD/DmdComMetadataReader.cs | 44 ++-- .../Impl/COMD/DmdEventDefCOMD.cs | 2 +- .../Impl/COMD/DmdGenericParameterTypeCOMD.cs | 4 +- .../Impl/COMD/DmdPropertyDefCOMD.cs | 2 +- .../Impl/COMD/LazyList.cs | 6 +- .../Impl/DmdAppDomainImpl.cs | 54 ++--- .../Impl/DmdAssemblyImpl.cs | 8 +- .../Impl/DmdByRefType.cs | 4 +- .../Impl/DmdConstructorDef.cs | 6 +- .../Impl/DmdConstructorRef.cs | 10 +- .../Impl/DmdCustomAttributeReader.cs | 4 +- .../Impl/DmdDeclSecurityReader.cs | 10 +- .../Impl/DmdEventDef.cs | 6 +- .../Impl/DmdFieldDef.cs | 2 +- .../Impl/DmdFieldRef.cs | 10 +- .../Impl/DmdGenericInstanceType.cs | 2 +- .../Impl/DmdGenericInstanceTypeRef.cs | 4 +- .../Impl/DmdGenericParameterType.cs | 4 +- .../Impl/DmdGenericParameterTypeImpl.cs | 2 +- .../Impl/DmdLazyMetadataReader.cs | 2 +- .../Impl/DmdMDArrayType.cs | 6 +- .../Impl/DmdMemberInfoComparer.cs | 8 +- .../Impl/DmdMetadataReaderBase.cs | 36 +-- .../Impl/DmdMethodDef.cs | 6 +- .../Impl/DmdMethodRef.cs | 10 +- .../Impl/DmdMethodSpec.cs | 2 +- .../Impl/DmdMethodSpecRef.cs | 6 +- .../Impl/DmdModuleImpl.cs | 6 +- .../Impl/DmdParameterDef.cs | 2 +- .../Impl/DmdPointerType.cs | 4 +- .../Impl/DmdPropertyDef.cs | 12 +- .../Impl/DmdSZArrayType.cs | 4 +- .../Impl/DmdTypeBase.cs | 48 ++-- .../Impl/DmdTypeDef.cs | 2 +- .../Impl/DmdTypeNameParser.cs | 10 +- .../Impl/DmdTypeRef.cs | 4 +- .../Impl/MD/DmdEcma335MetadataReader.cs | 20 +- .../Impl/MD/DmdGenericParameterTypeMD.cs | 4 +- .../Impl/ReflectionTests.cs | 26 +-- .../Impl/WellKnownMemberResolver.cs | 4 +- .../TIAHelper.cs | 12 +- .../AntiAntiDebug/DisableAntiAntiDebugCode.cs | 4 +- .../CallStack/DbgEngineStackWalkerImpl.cs | 2 +- .../Dialogs/AttachToProcess/ProcessUtils.cs | 2 +- .../AttachToProcess/UnityDataReceiver.cs | 2 +- .../MonoStartDebuggingOptionsPageBase.cs | 2 +- .../Impl/DbgEngineImpl.Breakpoints.cs | 8 +- .../Impl/DbgEngineImpl.Evaluation.cs | 28 +-- .../Impl/DbgEngineImpl.Steppers.cs | 2 +- .../Impl/DbgEngineImpl.Threads.cs | 18 +- .../Impl/DbgEngineImpl.cs | 46 ++-- .../Impl/DebuggerThread.cs | 2 +- .../Impl/EvalReflectionUtils.cs | 2 +- .../Evaluation/DbgDotNetRawValueFactory.cs | 32 +-- .../Impl/Evaluation/DbgDotNetValueImpl.cs | 8 +- .../DbgMonoDebugInternalRuntimeImpl.cs | 70 +++--- .../Impl/Evaluation/DmdEvaluatorImpl.cs | 6 +- .../Impl/Evaluation/EvalArgumentConverter.cs | 10 +- .../Hooks/MonoDebugValueConverterImpl.cs | 4 +- .../Impl/Evaluation/MethodCache.cs | 6 +- .../Impl/Evaluation/MonoDebugTypeCreator.cs | 2 +- .../Impl/FuncEvalFactory.cs | 2 +- .../Impl/ModuleCreator.cs | 4 +- .../Impl/MonoExeFinder.cs | 12 +- .../Impl/MonoTypeLoader.cs | 6 +- .../Impl/ObjectConstants.cs | 4 +- .../Impl/ReflectionTypeCreator.cs | 12 +- .../Metadata/DbgAssemblyInfoProviderImpl.cs | 2 +- .../Steppers/DbgDotNetEngineStepperImpl.cs | 14 +- ...BreakpointLocationFormatterProviderImpl.cs | 2 +- .../TextEditor/ClassBreakpointCommands.cs | 22 +- .../DbgBreakpointGlyphFormatterImpl.cs | 6 +- .../DeleteBreakpointsInRemovedModules.cs | 4 +- .../Code/DbgCodeLocationSerializerImpl.cs | 2 +- .../Code/DbgDotNetDebugInfoServiceImpl.cs | 2 +- .../Code/DbgDotNetDecompilerServiceImpl.cs | 2 +- .../Code/DbgMethodDebugInfoProvider.cs | 6 +- .../Code/DecompilerOutputImpl.cs | 4 +- .../Code/DotNetReferenceNavigator.cs | 6 +- .../DbgRuntimeNativeCodeProviderImpl.cs | 12 +- .../Disassembly/DecompiledCodeProvider.cs | 2 +- .../Disassembly/DecompilerOutputImpl.cs | 4 +- .../DbgDotNetEngineValueNodeFactoryService.cs | 2 +- .../Engine/DbgDotNetLanguageServiceImpl.cs | 4 +- .../Engine/DbgDotNetValueCreator.cs | 4 +- .../Engine/DbgEngineAutosProviderImpl.cs | 2 +- .../Engine/DbgEngineExceptionsProviderImpl.cs | 2 +- .../DbgEngineExpressionEvaluatorImpl.cs | 28 +-- .../Engine/DbgEngineLanguageImpl.cs | 4 +- .../Engine/DbgEngineLocalsProviderImpl.cs | 8 +- .../DbgEngineReturnValuesProviderImpl.cs | 2 +- .../Engine/DbgEngineValueNodeFactoryImpl.cs | 6 +- .../Engine/DbgEngineValueNodeImpl.cs | 16 +- .../Engine/DbgModuleReferenceProvider.cs | 16 +- .../Engine/Interpreter/ArrayILValue.cs | 8 +- .../Engine/Interpreter/DebuggerRuntimeImpl.cs | 78 +++---- ...Runtime_CompilerServices_RuntimeHelpers.cs | 2 +- ...yn_ExpressionEvaluator_IntrinsicMethods.cs | 2 +- .../Evaluation/Engine/StateWithKey.cs | 4 +- .../BreakWhenThrownExceptionCommand.cs | 4 +- .../Metadata/ClassLoader.cs | 6 +- .../Metadata/Commands.cs | 2 +- .../DbgAssemblyInfoProviderService.cs | 2 +- .../DbgDynamicModuleProviderService.cs | 2 +- .../Metadata/DbgInMemoryModuleService.cs | 38 +-- .../Metadata/DbgMetadataServiceImpl.cs | 10 +- .../Metadata/DbgModuleIdProviderService.cs | 2 +- .../Metadata/DsDocumentProvider.cs | 4 +- .../Metadata/DynamicModuleDefDocument.cs | 2 +- .../Metadata/Internal/DbgRawMetadataImpl.cs | 2 +- .../Internal/DbgRawMetadataServiceImpl.cs | 2 +- .../Metadata/MemoryModuleDefDocument.cs | 4 +- .../Metadata/ModuleLoaderDlg.xaml.cs | 4 +- .../Metadata/ModuleLoaderVM.cs | 2 +- .../Metadata/RuntimeAssemblyResolver.cs | 4 +- .../Metadata/TreeViewUpdater.cs | 18 +- .../Steppers/Engine/CompilerUtils.cs | 4 +- .../Steppers/Engine/DbgEngineStepperImpl.cs | 80 +++---- .../Steppers/Engine/TaskEvalUtils.cs | 18 +- .../dnSpy.Debugger.DotNet/UI/UIDispatcher.cs | 2 +- .../DbgHookedNativeFunctionProviderImpl.cs | 8 +- .../PreventNativeDebuggerDetection.cs | 2 +- .../ProcessMemoryBlockAllocator.cs | 2 +- .../Attach/AttachableProcessInfo.cs | 2 +- .../Attach/AttachableProcessesServiceImpl.cs | 10 +- .../Code/BreakpointConditionsFormatter.cs | 2 +- .../Code/BreakpointImageUtilities.cs | 2 +- .../Breakpoints/Code/BreakpointsSerializer.cs | 10 +- .../CondChecker/BreakpointBreakChecker.cs | 6 +- .../DbgCodeBreakpointConditionChecker.cs | 14 +- .../DbgCodeBreakpointFilterChecker.cs | 2 +- .../DbgFilterExpressionEvaluatorService.cs | 6 +- .../CondChecker/TracepointMessageCreator.cs | 20 +- .../DbgBreakpointLocationFormatterService.cs | 2 +- .../DbgBreakpointLocationSerializerService.cs | 8 +- .../DbgCodeBreakpointHitCountServiceImpl.cs | 4 +- .../Breakpoints/Code/DbgCodeBreakpointImpl.cs | 2 +- .../Code/DbgCodeBreakpointsServiceImpl.cs | 12 +- .../Code/RemoveTemporaryBreakpoints.cs | 2 +- .../Breakpoints/Code/ResetHitCount.cs | 4 +- .../BreakpointGlyphPopupControl.xaml.cs | 8 +- .../BreakpointGlyphTextMarkerHandler.cs | 10 +- ...tGlyphTextMarkerLocationProviderService.cs | 2 +- .../Code/TextEditor/BreakpointMarker.cs | 8 +- .../TextEditor/TextViewBreakpointService.cs | 6 +- .../Modules/BreakpointsSerializer.cs | 8 +- .../Modules/DbgModuleBreakpointImpl.cs | 8 +- .../DbgModuleBreakpointsServiceImpl.cs | 4 +- .../CallStack/DbgCallStackServiceImpl.cs | 10 +- .../CallStack/TextEditor/CallStackMarker.cs | 16 +- .../DbgTextViewCodeLocationService.cs | 2 +- .../DbgUI/CurrentStatementUpdater.cs | 4 +- .../DbgUI/DbgProcessStarterService.cs | 2 +- .../dnSpy.Debugger/DbgUI/DebuggerImpl.cs | 24 +- .../DbgUI/DocumentViewerCommands.cs | 2 +- .../DbgUI/StartDebuggingOptionsMru.cs | 2 +- .../DbgUI/StartDebuggingOptionsProvider.cs | 4 +- .../AttachToProcessDlg.xaml.cs | 2 +- .../AttachToProcess/AttachToProcessVM.cs | 12 +- .../ShowCodeBreakpointSettingsService.cs | 2 +- .../ShowCodeBreakpointSettingsVM.cs | 4 +- .../Disassembly/DisassemblyOperations.cs | 4 +- .../Evaluation/DbgExpressionEvaluatorImpl.cs | 4 +- .../Evaluation/DbgLanguageServiceImpl.cs | 2 +- .../Evaluation/DbgRuntimeObjectIdService.cs | 2 +- .../Evaluation/DbgValueNodeFactoryImpl.cs | 2 +- .../Evaluation/DbgValueNodeImpl.cs | 6 +- .../Evaluation/UI/ValueNodesProviderImpl.cs | 8 +- .../UI/VariablesWindowContentBase.cs | 2 +- .../UI/VariablesWindowControl.xaml.cs | 6 +- .../ViewModel/Impl/DbgValueNodeReader.cs | 6 +- .../Impl/LanguageEditValueProvider.cs | 2 +- .../Evaluation/ViewModel/Impl/RawNode.cs | 24 +- .../ViewModel/Impl/ValueNodeFormatter.cs | 8 +- .../ViewModel/Impl/ValueNodeImpl.cs | 30 +-- .../Evaluation/ViewModel/Impl/ValueNodesVM.cs | 10 +- .../Impl/VariablesWindowOperationsImpl.cs | 26 +-- .../Impl/VariablesWindowsCommands.cs | 4 +- .../DbgExceptionFormatterService.cs | 2 +- .../DbgExceptionSettingsServiceImpl.cs | 4 +- .../Exceptions/ExceptionConditionsChecker.cs | 2 +- .../Exceptions/ExceptionsFileReader.cs | 4 +- .../dnSpy.Debugger/Impl/DbgAppDomainImpl.cs | 2 +- ...ineBoundCodeBreakpointMessageExtensions.cs | 8 +- .../DbgManagerImpl.BoundBreakpointsManager.cs | 6 +- .../Impl/DbgManagerImpl.BreakAllHelper.cs | 4 +- .../Impl/DbgManagerImpl.CurrentObjects.cs | 2 +- .../DbgManagerImpl.StopDebuggingHelper.cs | 2 +- .../dnSpy.Debugger/Impl/DbgManagerImpl.cs | 60 ++--- .../dnSpy.Debugger/Impl/DbgModuleImpl.cs | 6 +- .../Impl/DbgObjectFactoryImpl.cs | 14 +- .../dnSpy.Debugger/Impl/DbgProcessImpl.cs | 4 +- .../dnSpy.Debugger/Impl/DbgRuntimeImpl.cs | 10 +- .../dnSpy.Debugger/Impl/DbgThreadImpl.cs | 10 +- .../dnSpy.Debugger/Impl/DebuggerThread.cs | 2 +- .../Impl/SwitchToDebuggedProcess.cs | 2 +- .../Settings/DebuggerAppSettingsPage.cs | 2 +- .../dnSpy.Debugger/Shared/DispatcherTimer.cs | 2 +- .../dnSpy.Debugger/Steppers/DbgStepperImpl.cs | 6 +- .../Text/ClassifiedTextWriter.cs | 2 +- .../CallStack/CallStackOperations.cs | 16 +- .../ToolWindows/CallStack/Commands.cs | 2 +- .../ToolWindows/CallStack/StackFrameVM.cs | 4 +- .../CodeBreakpointsOperations.cs | 4 +- .../ToolWindows/Exceptions/AddExceptionVM.cs | 4 +- .../ToolWindows/Exceptions/Commands.cs | 2 +- .../ToolWindows/Exceptions/ExceptionsVM.cs | 2 +- .../ToolWindows/FormatterUtils.cs | 2 +- .../ToolWindows/LazyToolWindowVMHelper.cs | 2 +- .../ToolWindows/Logger/OutputLogger.cs | 14 +- .../ToolWindows/Memory/BufferFileCreator.cs | 4 +- .../ToolWindows/Memory/Commands.cs | 4 +- .../Memory/DebuggerHexBufferStream.cs | 2 +- .../ToolWindows/Memory/MemoryWindowService.cs | 2 +- .../Memory/ProcessHexBufferProvider.cs | 4 +- .../ModuleBreakpointsOperations.cs | 2 +- .../ToolWindows/Modules/Commands.cs | 2 +- .../ToolWindows/Modules/ModuleFormatter.cs | 4 +- .../ToolWindows/Modules/ModulesOperations.cs | 8 +- .../ToolWindows/Modules/ModulesSaver.cs | 6 +- .../ToolWindows/Modules/ModulesVM.cs | 4 +- .../Processes/ProcessesOperations.cs | 4 +- .../ToolWindows/SimpleProcessVM.cs | 2 +- .../Threads/ThreadCategoryService.cs | 2 +- .../ToolWindows/Threads/ThreadFormatter.cs | 4 +- .../ToolWindows/Threads/ThreadUtilities.cs | 2 +- .../ToolWindows/Threads/ThreadVM.cs | 8 +- .../ToolWindows/Threads/ThreadsOperations.cs | 2 +- .../ToolWindows/Threads/ThreadsVM.cs | 4 +- .../ToolWindows/Watch/WatchContentFactory.cs | 2 +- .../WatchVariablesWindowValueNodesProvider.cs | 2 +- .../Watch/WatchWindowExpressionsSettings.cs | 2 +- .../ToolWindows/Watch/WpfMemLeakWorkaround.cs | 2 +- .../dnSpy.Debugger/UI/Wpf/SmartTextBlock.cs | 2 +- .../UI/Wpf/TextBlockContentInfo.cs | 2 +- .../Common/ScriptControlVM.cs | 30 +-- .../Compiler/FrameworkDetector.cs | 2 +- .../Compiler/RoslynLanguageCompiler.cs | 10 +- .../dnSpy.Roslyn/Debugger/AliasConstants.cs | 2 +- .../CSharp/CSharpExpressionCompiler.cs | 4 +- .../LanguageExpressionCompiler.cs | 12 +- .../VisualBasicExpressionCompiler.cs | 2 +- .../DbgFilterExpressionEvaluatorImpl.cs | 8 +- .../EvalDelegateCreator.cs | 14 +- .../CSharp/CSharpStackFrameFormatter.cs | 8 +- .../Formatters/CSharp/CSharpTypeFormatter.cs | 12 +- .../Formatters/CSharp/CSharpValueFormatter.cs | 8 +- .../DebuggerDisplayAttributeFormatter.cs | 10 +- .../Formatters/KeyValuePairTypeUtils.cs | 4 +- .../Debugger/Formatters/NullableTypeUtils.cs | 4 +- .../Debugger/Formatters/StateMachineUtils.cs | 12 +- .../Debugger/Formatters/ToStringFormatter.cs | 2 +- .../VisualBasicStackFrameFormatter.cs | 8 +- .../VisualBasic/VisualBasicTypeFormatter.cs | 12 +- .../VisualBasic/VisualBasicValueFormatter.cs | 8 +- .../Debugger/GetLocalsAssemblyBuilder.cs | 12 +- .../dnSpy.Roslyn/Debugger/StateWithKey.cs | 8 +- .../ValueNodes/AggregateValueNodeProvider.cs | 2 +- .../ValueNodes/ArrayValueNodeProvider.cs | 6 +- .../CSharp/CSharpValueNodeFactory.cs | 4 +- .../ValueNodes/DbgDotNetTypeVariablesNode.cs | 4 +- .../ValueNodes/DbgDotNetValueNodeImpl.cs | 6 +- .../DbgDotNetValueNodeProviderFactory.cs | 20 +- .../ValueNodes/DebuggerTypeProxyFinder.cs | 12 +- .../DynamicViewMembersValueNodeProvider.cs | 2 +- .../ValueNodes/EnumerableDebugViewHelper.cs | 8 +- .../ValueNodes/LanguageValueNodeFactory.cs | 10 +- .../ValueNodes/MemberValueNodeInfo.cs | 2 +- .../ValueNodes/MembersValueNodeProvider.cs | 34 +-- .../ValueNodes/PointerValueNodeProvider.cs | 4 +- .../ValueNodes/ReflectionAssemblyLoader.cs | 2 +- .../ResultsViewMembersValueNodeProvider.cs | 4 +- .../ValueNodes/TupleValueNodeProvider.cs | 4 +- .../VisualBasicValueNodeFactory.cs | 4 +- .../RoslynDocumentationProvider.cs | 2 +- .../Classification/CompletionClassifier.cs | 4 +- .../Completions/CommandTargetFilter.cs | 14 +- .../Completions/CompletionToolTipProvider.cs | 2 +- .../Completions/RoslynCompletionSet.cs | 16 +- .../InformationQuickInfoContentVM.cs | 14 +- .../Intellisense/QuickInfo/QuickInfoSource.cs | 4 +- .../SignatureHelp/CommandTargetFilter.cs | 6 +- .../Intellisense/SignatureHelp/Parameter.cs | 4 +- .../Intellisense/SignatureHelp/Signature.cs | 4 +- .../SignatureHelp/SignatureHelpSession.cs | 12 +- .../SignatureHelp/SignatureHelpTaggerEx.cs | 4 +- .../Optimizations/FirstUseOptimization.cs | 12 +- .../RoslynClassificationTypes.cs | 2 +- .../Text/Classification/RoslynClassifier.cs | 10 +- .../Text/RoslynMefHostServices.cs | 2 +- .../dnSpy.Roslyn/Text/Tagging/AsyncTagger.cs | 8 +- .../dnSpy.Roslyn/Text/Tagging/RoslynTagger.cs | 4 +- .../Text/Tagging/RoslynTaggerAsyncState.cs | 2 +- dnSpy/dnSpy.Console/Program.cs | 38 +-- .../Code/DbgMethodDebugInfo.cs | 6 +- .../Evaluation/DbgDotNetRuntimeExtensions.cs | 2 +- .../Evaluation/DbgDotNetValueResult.cs | 2 +- .../DbgDotNetCompilationResult.cs | 2 +- .../Text/DbgDotNetTextOutput.cs | 2 +- .../DbgFilterExpressionEvaluator.cs | 2 +- .../DbgMessageEventArgs.cs | 4 +- dnSpy/dnSpy.Contracts.Debugger/DbgObject.cs | 2 +- .../Evaluation/DbgValueNode.cs | 4 +- .../Evaluation/PredefinedFormatSpecifiers.cs | 6 +- .../Exceptions/DbgExceptionSettings.cs | 2 +- .../Steppers/DbgStepper.cs | 2 +- dnSpy/dnSpy.Contracts.DnSpy/App/MsgBox.cs | 2 +- .../AsmEditor/Compiler/CompilationResult.cs | 2 +- .../AsmEditor/Compiler/CompilerDiagnostic.cs | 2 +- .../Bookmarks/BMObject.cs | 2 +- .../Controls/FastTextBlock.cs | 10 +- .../Controls/MetroWindow.cs | 8 +- .../ToolWindows/EditValueControl.xaml.cs | 2 +- .../ToolWindows/ListBoxSelectedItemsAP.cs | 28 +-- .../Documents/AnnotationsImpl.cs | 2 +- .../Documents/DsDocument.cs | 14 +- .../Documents/FilenameKey.cs | 2 +- .../Documents/IDsDocument.cs | 4 +- .../TreeView/DocumentTreeNodeData.cs | 6 +- .../Documents/TreeView/ModuleDocumentNode.cs | 2 +- .../Documents/TreeView/NodeFormatter.cs | 12 +- ...umentTreeViewCollectionChangedEventArgs.cs | 6 +- .../Documents/TreeView/PEDocumentNode.cs | 2 +- .../TreeView/Resources/Deserializer.cs | 2 +- .../TreeView/Resources/ResourceElementNode.cs | 2 +- .../Resources/SerializedImageUtilities.cs | 2 +- .../SerializedResourceElementNode.cs | 2 +- .../Hex/Editor/HexGroups/LocalGroupOptions.cs | 2 +- .../Hex/Editor/HexStructureInfoAggregator.cs | 4 +- .../Hex/Files/DotNet/HeapData.cs | 4 +- .../Hex/Files/DotNet/TablesHeaderData.cs | 2 +- .../Hex/Files/DotNet/TokenData.cs | 2 +- .../Hex/Files/HexBufferFile.cs | 2 +- .../Hex/HexBufferLine.cs | 8 +- .../Hex/HexBufferLineFormatterOptions.cs | 2 +- dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBytes.cs | 2 +- .../dnSpy.Contracts.DnSpy/Hex/HexLineSpan.cs | 2 +- dnSpy/dnSpy.Contracts.DnSpy/Hex/HexSpan.cs | 2 +- .../Hex/NormalizedHexBufferSpanCollection.cs | 4 +- .../Images/ImageOptions.cs | 4 +- .../Intellisense/BestMatchSelector.cs | 4 +- .../Language/Intellisense/CompletionFilter.cs | 4 +- .../Language/Intellisense/DsCompletionSet.cs | 10 +- .../AutomationPeerMemoryLeakWorkaround.cs | 26 +-- .../dnSpy.Contracts.DnSpy/MVVM/DataFieldVM.cs | 2 +- .../MVVM/Dialogs/ProgressDlg.xaml.cs | 4 +- .../MVVM/Dialogs/ProgressVM.cs | 2 +- dnSpy/dnSpy.Contracts.DnSpy/MVVM/EnumVM.cs | 4 +- .../MVVM/GridViewColumnSorter.cs | 6 +- .../MVVM/InitDataTemplateAP.cs | 2 +- .../MVVM/IsDraggableAP.cs | 2 +- dnSpy/dnSpy.Contracts.DnSpy/MVVM/ListVM.cs | 2 +- .../Menus/CommandTargetMenuItemBase.cs | 4 +- .../Menus/MenuItemBase.cs | 14 +- .../Scripting/UIUtils.cs | 6 +- .../Search/FlagsDocumentTreeNodeFilter.cs | 6 +- .../SameModuleDocumentTreeNodeFilter.cs | 2 +- .../Search/SearchComparers.cs | 16 +- .../ThemeClassificationFormatDefinition.cs | 8 +- .../ThemeMarkerFormatDefinition.cs | 4 +- .../ToolWindows/Search/SearchMatcher.cs | 2 +- .../TreeView/AsyncNodeProvider.cs | 2 +- .../TreeView/TreeNodeData.cs | 4 +- .../Utilities/UIUtilities.cs | 10 +- .../Decompiler/AddressReference.cs | 2 +- .../Decompiler/CustomAttributesUtils.cs | 12 +- .../Decompiler/Extensions.cs | 12 +- .../Decompiler/GenericArgumentResolver.cs | 18 +- .../Decompiler/InstructionReference.cs | 2 +- .../Decompiler/MetadataTextColorProvider.cs | 16 +- .../Decompiler/MethodDebugInfo.cs | 2 +- .../Decompiler/MethodDebugInfoBuilder.cs | 2 +- .../Decompiler/MethodStatementReference.cs | 2 +- .../Decompiler/TokenReference.cs | 2 +- .../Decompiler/TypesHierarchyHelpers.cs | 12 +- .../Decompiler/XmlDoc/XmlDocKeyProvider.cs | 14 +- .../Decompiler/XmlDoc/XmlDocLoader.cs | 4 +- .../XmlDoc/XmlDocumentationProvider.cs | 6 +- .../Resources/ResourceHelper.cs | 16 +- .../Text/ITextColorWriterExtensions.cs | 6 +- dnSpy/dnSpy.Contracts.Logic/Text/Indenter.cs | 2 +- .../Utilities/GacInfo.cs | 4 +- .../Utilities/SimpleTypeConverter.cs | 12 +- .../CSharp/CSharpFormatter.cs | 86 +++---- dnSpy/dnSpy.Decompiler/DecompilerBase.cs | 10 +- dnSpy/dnSpy.Decompiler/FilenameUtils.cs | 2 +- dnSpy/dnSpy.Decompiler/FormatterMethodInfo.cs | 8 +- dnSpy/dnSpy.Decompiler/IL/ILLanguageHelper.cs | 6 +- .../MSBuild/BamlResourceProjectFile.cs | 6 +- .../MSBuild/DefaultNamespaceFinder.cs | 8 +- dnSpy/dnSpy.Decompiler/MSBuild/DotNetUtils.cs | 6 +- .../MSBuild/FilenameCreator.cs | 6 +- .../MSBuild/MSBuildProjectCreator.cs | 4 +- dnSpy/dnSpy.Decompiler/MSBuild/Project.cs | 44 ++-- .../dnSpy.Decompiler/MSBuild/ProjectWriter.cs | 28 +-- .../MSBuild/ResXProjectFile.cs | 4 +- .../MSBuild/ResourceNameCreator.cs | 48 ++-- .../MSBuild/SettingsProjectFile.cs | 28 +-- .../MSBuild/SettingsTypeProjectFile.cs | 6 +- .../MSBuild/WinFormsProjectFile.cs | 6 +- .../MSBuild/XamlTypeProjectFile.cs | 8 +- dnSpy/dnSpy.Decompiler/TargetFrameworkInfo.cs | 8 +- dnSpy/dnSpy.Decompiler/TypeFormatterUtils.cs | 20 +- .../Utils/StateMachineHelpers.cs | 4 +- .../VisualBasic/VisualBasicFormatter.cs | 82 +++---- .../BackgroundImage/BackgroundImageService.cs | 4 +- .../BackgroundImageSettingsService.cs | 4 +- .../HexViewBackgroundImageService.cs | 2 +- .../BackgroundImage/ImageSourceService.cs | 20 +- dnSpy/dnSpy/BackgroundImage/RawSettings.cs | 2 +- .../TextViewBackgroundImageService.cs | 2 +- .../BookmarkLocationFormatterProviderImpl.cs | 4 +- .../DotNet/BookmarkLocationSerializerImpl.cs | 2 +- .../BookmarkDocumentProviderImpl.cs | 4 +- .../DeleteBookmarksInRemovedModules.cs | 4 +- .../Impl/BookmarkLocationFormatterService.cs | 2 +- .../Impl/BookmarkLocationSerializerService.cs | 6 +- .../Bookmarks/Impl/BookmarksSerializer.cs | 2 +- .../Bookmarks/Impl/BookmarksServiceImpl.cs | 6 +- .../Navigator/BookmarkNavigatorImpl.cs | 2 +- ...kGlyphTextMarkerLocationProviderService.cs | 2 +- .../Bookmarks/TextEditor/BookmarkMarker.cs | 10 +- .../TextEditor/TextViewBookmarkService.cs | 8 +- .../Bookmarks/BookmarksOperations.cs | 4 +- .../ToolWindows/LazyToolWindowVMHelper.cs | 2 +- dnSpy/dnSpy/Commands/CommandService.cs | 2 +- .../Commands/RegisteredCommandElement.cs | 2 +- dnSpy/dnSpy/Controls/FastTreeNodeView.cs | 6 +- dnSpy/dnSpy/Controls/Screen.cs | 2 +- dnSpy/dnSpy/Controls/StackedContent.cs | 10 +- dnSpy/dnSpy/Controls/WinSysButton.cs | 2 +- dnSpy/dnSpy/Controls/WpfFocusService.cs | 2 +- dnSpy/dnSpy/Culture/CultureService.cs | 10 +- dnSpy/dnSpy/Decompiler/MethodDebugService.cs | 20 +- .../Viewer/DisassemblyDocumentTabContent.cs | 2 +- .../Viewer/X86/DisassemblyContentGenerator.cs | 8 +- .../X86/DisassemblyContentProviderFactory.cs | 2 +- .../X86/DisassemblyContentProviderImpl.cs | 2 +- dnSpy/dnSpy/Disassembly/X86/BlockFactory.cs | 2 +- dnSpy/dnSpy/Documents/AssemblyResolver.cs | 54 ++--- .../Documents/DefaultDsDocumentLoader.cs | 2 +- .../Documents/DefaultDsDocumentProvider.cs | 12 +- dnSpy/dnSpy/Documents/DotNetPathProvider.cs | 8 +- dnSpy/dnSpy/Documents/DsDocumentLoader.cs | 4 +- dnSpy/dnSpy/Documents/DsDocumentService.cs | 30 +-- dnSpy/dnSpy/Documents/MethodAnnotations.cs | 2 +- .../Tabs/AppCommandLineArgsHandler.cs | 10 +- dnSpy/dnSpy/Documents/Tabs/Commands.cs | 8 +- .../dnSpy/Documents/Tabs/CopyTokenCommand.cs | 10 +- .../Documents/Tabs/DecompilationCache.cs | 12 +- .../Documents/Tabs/DefaultDocumentList.cs | 28 +-- .../Tabs/Dialogs/ExportToProjectVM.cs | 4 +- .../dnSpy/Documents/Tabs/Dialogs/GACFileVM.cs | 4 +- .../Tabs/Dialogs/OpenDocumentListVM.cs | 2 +- .../Tabs/Dialogs/OpenDocumentsHelper.cs | 4 +- .../Documents/Tabs/Dialogs/OpenFromGACVM.cs | 2 +- .../DocViewer/BlockStructureCollection.cs | 2 +- .../Tabs/DocViewer/BracePairCollection.cs | 6 +- .../Tabs/DocViewer/BracePairService.cs | 18 +- .../Documents/Tabs/DocViewer/Commands.cs | 8 +- .../DocViewer/DecompileDocumentTabContent.cs | 14 +- .../Tabs/DocViewer/DocumentViewer.cs | 10 +- .../DocViewer/DocumentViewerContentFactory.cs | 2 +- .../Tabs/DocViewer/DocumentViewerControl.cs | 26 +-- ...DocumentViewerHighlightReferencesTagger.cs | 30 +-- .../DocViewer/DocumentViewerMouseProcessor.cs | 8 +- .../Tabs/DocViewer/DocumentViewerOutput.cs | 2 +- .../DocumentViewerUIElementService.cs | 4 +- .../Tabs/DocViewer/DocumentWriterService.cs | 4 +- .../DocViewer/LazyBlockStructureCollection.cs | 2 +- .../SpanDataReferenceInfoExtensions.cs | 6 +- .../DocViewer/ToolTips/CodeToolTipProvider.cs | 2 +- .../DocViewer/ToolTips/CodeToolTipWriter.cs | 6 +- ...bReferenceDocumentViewerToolTipProvider.cs | 14 +- .../ToolTips/DocumentViewerToolTipService.cs | 4 +- .../XmlParser.XamlAttributeParser.cs | 12 +- .../Documents/Tabs/DocViewer/XmlParser.cs | 20 +- dnSpy/dnSpy/Documents/Tabs/DocumentList.cs | 4 +- .../Tabs/DocumentTabContentFactoryService.cs | 6 +- .../Documents/Tabs/DocumentTabSerializer.cs | 2 +- .../Documents/Tabs/DocumentTabService.cs | 54 ++--- .../Tabs/DocumentTabUIContextLocator.cs | 6 +- .../Tabs/DsDocumentInfoSerializer.cs | 2 +- .../Documents/Tabs/EntryPointCommands.cs | 16 +- .../dnSpy/Documents/Tabs/GoToTokenCommand.cs | 4 +- .../Documents/Tabs/NavigationCommands.cs | 2 +- dnSpy/dnSpy/Documents/Tabs/NodeDecompiler.cs | 6 +- ...NodeReferenceDocumentTabContentProvider.cs | 2 +- .../Documents/Tabs/RefreshResourcesCommand.cs | 6 +- .../dnSpy/Documents/Tabs/ResourceCommands.cs | 12 +- dnSpy/dnSpy/Documents/Tabs/SaveCommands.cs | 32 +-- dnSpy/dnSpy/Documents/Tabs/SaveService.cs | 4 +- .../dnSpy/Documents/Tabs/SearchMsdnCommand.cs | 12 +- dnSpy/dnSpy/Documents/Tabs/SerializedTabs.cs | 16 +- .../AssemblyExplorerAppSettingsPage.cs | 2 +- dnSpy/dnSpy/Documents/Tabs/TabCommands.cs | 24 +- dnSpy/dnSpy/Documents/Tabs/TabContentImpl.cs | 24 +- dnSpy/dnSpy/Documents/Tabs/TabHistory.cs | 6 +- ...NodeReferenceDocumentTabContentProvider.cs | 16 +- .../Documents/TargetFrameworkAttributeInfo.cs | 2 +- .../TreeView/AssemblyDocumentNodeImpl.cs | 4 +- .../TreeView/AssemblyReferenceNodeImpl.cs | 2 +- .../TreeView/BaseTypeFolderNodeImpl.cs | 2 +- .../Documents/TreeView/BaseTypeNodeImpl.cs | 8 +- .../TreeView/DefaultDsDocumentNodeProvider.cs | 6 +- .../Documents/TreeView/DerivedTypeNodeImpl.cs | 6 +- .../Documents/TreeView/DerivedTypesFinder.cs | 4 +- .../TreeView/DerivedTypesFolderNodeImpl.cs | 2 +- .../TreeView/DocumentTreeNodeGroups.cs | 4 +- .../Documents/TreeView/DocumentTreeView.cs | 28 +-- .../dnSpy/Documents/TreeView/EventNodeImpl.cs | 6 +- .../TreeView/MemberReferenceFinder.cs | 2 +- .../TreeView/ModuleDocumentNodeImpl.cs | 4 +- .../Documents/TreeView/NamespaceNodeImpl.cs | 2 +- .../Documents/TreeView/PEDocumentNodeImpl.cs | 4 +- .../TreeView/ReferencesFolderNodeImpl.cs | 4 +- .../TreeView/Resources/ImageResourceNode.cs | 6 +- .../Resources/ResourceElementSetNodeImpl.cs | 4 +- .../TreeView/Resources/ResourceNodeFactory.cs | 4 +- ...zedImageListStreamerResourceElementNode.cs | 6 +- .../SerializedImageResourceElementNode.cs | 4 +- dnSpy/dnSpy/Documents/TreeView/RootNode.cs | 4 +- .../TreeView/TypeReferencesFolderNodeImpl.cs | 26 +-- dnSpy/dnSpy/Events/WeakEventList.cs | 4 +- dnSpy/dnSpy/Extension/ExtensionService.cs | 4 +- .../Hex/Adornments/HexToolTipProviderImpl.cs | 2 +- .../Classification/HexClassifierAggregator.cs | 4 +- dnSpy/dnSpy/Hex/Commands/GoToMetadataVM.cs | 8 +- .../Hex/Commands/HexCommandOperations.cs | 10 +- .../dnSpy/Hex/ContextMenuCommands/Commands.cs | 4 +- .../Hex/Editor/ActiveColumnHighlighter.cs | 2 +- .../dnSpy/Hex/Editor/ColumnLineSeparators.cs | 4 +- .../Hex/Editor/CurrentLineHighlighter.cs | 6 +- .../Hex/Editor/CurrentValueHighlighter.cs | 16 +- .../Editor/DefaultHexViewMouseProcessor.cs | 8 +- .../dnSpy/Hex/Editor/HexAdornmentLayerImpl.cs | 14 +- dnSpy/dnSpy/Hex/Editor/HexCaretImpl.cs | 10 +- dnSpy/dnSpy/Hex/Editor/HexCaretLayer.cs | 2 +- .../Hex/Editor/HexEditorFactoryServiceImpl.cs | 4 +- dnSpy/dnSpy/Hex/Editor/HexEditorOptions.cs | 14 +- dnSpy/dnSpy/Hex/Editor/HexGlyphMargin.cs | 26 +-- .../Editor/HexIntraTextAdornmentService.cs | 28 +-- .../Hex/Editor/HexKeyProcessorCollection.cs | 2 +- .../Editor/HexMarginContextMenuServiceImpl.cs | 8 +- dnSpy/dnSpy/Hex/Editor/HexMarkerService.cs | 16 +- dnSpy/dnSpy/Hex/Editor/HexMouseLocation.cs | 2 +- .../Hex/Editor/HexMouseProcessorCollection.cs | 4 +- .../Editor/HexPopupSpaceReservationAgent.cs | 6 +- dnSpy/dnSpy/Hex/Editor/HexSelectionImpl.cs | 4 +- dnSpy/dnSpy/Hex/Editor/HexSelectionLayer.cs | 2 +- .../Editor/HexSpaceReservationStackImpl.cs | 4 +- .../HexStructureInfoAggregatorFactoryImpl.cs | 2 +- .../Editor/HexViewMouseProcessorCollection.cs | 4 +- .../Editor/Search/HexSearchServiceFactory.cs | 2 +- .../Hex/Editor/Search/HexViewSearchService.cs | 32 +-- .../Hex/Editor/WpfHexViewContainerMargin.cs | 2 +- .../Hex/Editor/WpfHexViewImpl.LayoutHelper.cs | 8 +- .../Editor/WpfHexViewImpl.MouseHoverHelper.cs | 4 +- dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.cs | 38 +-- .../Editor/WpfHexViewLineCollectionImpl.cs | 4 +- .../WpfHexViewMarginProviderCollectionImpl.cs | 2 +- dnSpy/dnSpy/Hex/Editor/ZoomControlMargin.cs | 12 +- .../Files/DefaultHexStructureInfoProvider.cs | 4 +- .../DefaultHexFileStructureInfoProvider.cs | 2 +- .../DotNetHexFileStructureInfoProvider.cs | 6 +- .../Files/DnSpy/ToolTipObjectFactoryImpl.cs | 2 +- dnSpy/dnSpy/Hex/Files/DotNet/BlobHeapImpl.cs | 6 +- .../DotNetHexFileStructureInfoProvider.cs | 28 +-- .../Files/DotNet/DotNetMethodProviderImpl.cs | 2 +- .../DotNetMultiFileResourceHeaderDataImpl.cs | 8 +- .../DotNet/DotNetMultiFileResourcesImpl.cs | 6 +- .../DotNet/DotNetResourceProviderImpl.cs | 2 +- .../Files/DotNet/DotNetStructureProvider.cs | 16 +- .../Hex/Files/DotNet/DotNetTableSizes.cs | 4 +- .../Hex/Files/DotNet/FatMethodBodyImpl.cs | 4 +- .../MultiResourceStructureProviderFactory.cs | 2 +- dnSpy/dnSpy/Hex/Files/DotNet/PdbHeapImpl.cs | 6 +- .../dnSpy/Hex/Files/DotNet/StringsHeapImpl.cs | 6 +- .../dnSpy/Hex/Files/DotNet/TablesHeapImpl.cs | 10 +- dnSpy/dnSpy/Hex/Files/DotNet/USHeapImpl.cs | 8 +- dnSpy/dnSpy/Hex/Files/HexBufferFileImpl.cs | 20 +- .../dnSpy/Hex/Files/HexFieldFormatterImpl.cs | 4 +- .../Files/HexFileStructureInfoServiceImpl.cs | 10 +- dnSpy/dnSpy/Hex/Files/PE/PeHeadersReader.cs | 6 +- .../PE/PeHexFileStructureInfoProvider.cs | 4 +- .../dnSpy/Hex/Files/PE/PeStructureProvider.cs | 2 +- .../HexAndAdornmentSequencerImpl.cs | 2 +- .../Hex/Formatting/HexFormattedLineImpl.cs | 14 +- .../Formatting/HexFormattedLineSourceImpl.cs | 2 +- .../Formatting/HexHtmlBuilderServiceImpl.cs | 4 +- dnSpy/dnSpy/Hex/Formatting/HexLinePart.cs | 10 +- .../Hex/Formatting/HexLinePartsCollection.cs | 4 +- .../Hex/Formatting/HexLinePartsTextSource.cs | 6 +- .../HexLineTransformProviderService.cs | 2 +- .../dnSpy/Hex/Formatting/PhysicalLineCache.cs | 2 +- dnSpy/dnSpy/Hex/HexBufferImpl.cs | 4 +- dnSpy/dnSpy/Hex/HexBufferLineFormatterImpl.cs | 8 +- dnSpy/dnSpy/Hex/HexCachedBufferStreamImpl.cs | 2 +- .../Hex/HexGroups/HexViewOptionsGroupImpl.cs | 4 +- .../HexViewOptionsGroupServiceImpl.cs | 6 +- dnSpy/dnSpy/Hex/HexGroups/OptionsStorage.cs | 2 +- .../DnSpy/QuickInfoCommandTargetFilter.cs | 2 +- .../HexIntellisenseControllerService.cs | 2 +- .../HexIntellisensePresenterFactoryService.cs | 2 +- ...nseSessionStackImpl.CommandTargetFilter.cs | 4 +- .../HexIntellisenseSessionStackImpl.cs | 22 +- .../Hex/Intellisense/HexQuickInfoPresenter.cs | 8 +- .../Intellisense/HexQuickInfoSessionImpl.cs | 4 +- .../Hex/Intellisense/HexToolTipService.cs | 18 +- .../Hex/Operations/ByteHexSearchService.cs | 4 +- .../Hex/Operations/HexEditorOperationsImpl.cs | 28 +-- .../Hex/Operations/HexSearchServiceImpl.cs | 2 +- .../Hex/Operations/StringHexSearchService.cs | 4 +- .../Settings/GeneralAppSettingsPageBase.cs | 2 +- dnSpy/dnSpy/Hex/Tagging/HexTaggerFactory.cs | 6 +- dnSpy/dnSpy/Hex/Tagging/TagAggregator.cs | 10 +- .../Images/DefaultImageSourceInfoProvider.cs | 12 +- dnSpy/dnSpy/Images/DotNetImageService.cs | 10 +- dnSpy/dnSpy/Images/DsImageConverter.cs | 2 +- dnSpy/dnSpy/Images/ImageService.cs | 10 +- .../Intellisense/CompletionCollectionVM.cs | 14 +- .../Intellisense/CompletionPresenter.cs | 30 +-- .../Intellisense/CompletionSession.cs | 8 +- .../CompletionSessionCommandTargetFilter.cs | 2 +- .../Language/Intellisense/CompletionVM.cs | 2 +- .../CurrentLineSpaceReservationService.cs | 4 +- .../IntellisensePresenterFactoryService.cs | 4 +- ...lisenseSessionStack.CommandTargetFilter.cs | 6 +- .../Intellisense/IntellisenseSessionStack.cs | 22 +- .../Intellisense/QuickInfoPresenter.cs | 10 +- .../Language/Intellisense/QuickInfoSession.cs | 4 +- .../SignatureHelpCurrentParameterTagger.cs | 2 +- .../Intellisense/SignatureHelpPresenter.cs | 10 +- .../Intellisense/SignatureHelpSession.cs | 8 +- dnSpy/dnSpy/Language/Intellisense/WpfUtils.cs | 4 +- dnSpy/dnSpy/MainApp/App.xaml.cs | 32 +-- .../MainApp/AppCommandLineArgsHandler.cs | 2 +- dnSpy/dnSpy/MainApp/AppWindow.cs | 8 +- dnSpy/dnSpy/MainApp/DsLoaderService.cs | 4 +- dnSpy/dnSpy/MainApp/MainWindowControl.cs | 48 ++-- dnSpy/dnSpy/MainApp/MessageBoxService.cs | 2 +- .../MainApp/ResourceManagerTokenCacheImpl.cs | 4 +- dnSpy/dnSpy/MainApp/SavedWindowState.cs | 4 +- .../MainApp/Settings/FontAppSettingsPage.cs | 2 +- .../Settings/GeneralAppSettingsPage.cs | 4 +- .../Settings/WindowsExplorerIntegration.cs | 2 +- dnSpy/dnSpy/MainApp/ToolBarCommands.cs | 4 +- dnSpy/dnSpy/Menus/ContextMenuProvider.cs | 2 +- dnSpy/dnSpy/Menus/MenuItemContext.cs | 6 +- dnSpy/dnSpy/Menus/MenuService.cs | 40 ++-- dnSpy/dnSpy/Metadata/ModuleIdProvider.cs | 4 +- dnSpy/dnSpy/Output/NotPresentOutputWriter.cs | 2 +- dnSpy/dnSpy/Output/OutputContent.cs | 2 +- dnSpy/dnSpy/Output/OutputService.cs | 18 +- dnSpy/dnSpy/Scripting/ServiceLocator.cs | 10 +- .../dnSpy/Search/AppCommandLineArgsHandler.cs | 6 +- dnSpy/dnSpy/Search/Commands.cs | 2 +- dnSpy/dnSpy/Search/DocumentSearcher.cs | 4 +- dnSpy/dnSpy/Search/FilterSearcher.cs | 10 +- dnSpy/dnSpy/Search/FrameworkFileUtils.cs | 2 +- dnSpy/dnSpy/Search/SearchControlVM.cs | 14 +- dnSpy/dnSpy/Search/SearchResult.cs | 4 +- dnSpy/dnSpy/Search/SearchService.cs | 2 +- .../TextAppearanceCategory.cs | 4 +- .../Settings/Dialog/AppSettingsPageVM.cs | 10 +- .../Settings/Dialog/AppSettingsService.cs | 4 +- .../SettingsAppCommandLineArgsHandler.cs | 2 +- .../Settings/Dialog/ShowAppSettingsDialog.cs | 36 +-- .../Fonts/ThemeFontSettingsSerializer.cs | 10 +- dnSpy/dnSpy/Settings/SectionAttributes.cs | 6 +- .../dnSpy/Settings/SettingsSectionProvider.cs | 10 +- dnSpy/dnSpy/Settings/SettingsService.cs | 2 +- dnSpy/dnSpy/Settings/XmlSettingsWriter.cs | 2 +- dnSpy/dnSpy/Tabs/TabElementZoomer.cs | 20 +- dnSpy/dnSpy/Tabs/TabGroup.cs | 14 +- dnSpy/dnSpy/Tabs/TabGroupService.cs | 4 +- dnSpy/dnSpy/Tabs/TabUtils.cs | 2 +- .../dnSpy/Text/Adornments/ToolTipProvider.cs | 2 +- dnSpy/dnSpy/Text/AvalonEdit/CharRope.cs | 2 +- dnSpy/dnSpy/Text/AvalonEdit/DocumentLine.cs | 10 +- .../dnSpy/Text/AvalonEdit/DocumentLineTree.cs | 72 +++--- dnSpy/dnSpy/Text/AvalonEdit/LineManager.cs | 2 +- dnSpy/dnSpy/Text/AvalonEdit/LineNode.cs | 4 +- dnSpy/dnSpy/Text/AvalonEdit/Rope.cs | 12 +- dnSpy/dnSpy/Text/AvalonEdit/RopeNode.cs | 24 +- dnSpy/dnSpy/Text/AvalonEdit/TextDocument.cs | 6 +- dnSpy/dnSpy/Text/CachedColorsListTagger.cs | 4 +- .../CategoryClassificationFormatMap.cs | 10 +- .../Classification/ClassificationFontUtils.cs | 12 +- .../ClassificationTypeRegistryService.cs | 6 +- .../ClassifierAggregatorBase.cs | 4 +- .../ClassifierTaggerProvider.cs | 2 +- .../TextClassifierAggregatorService.cs | 2 +- .../ThemeClassificationTypeService.cs | 2 +- .../ViewClassificationFormatMap.cs | 4 +- .../Classification/ViewEditorFormatMap.cs | 4 +- .../dnSpy/Text/ContentTypeRegistryService.cs | 10 +- .../ContentTypeRegistryServiceExtensions.cs | 4 +- dnSpy/dnSpy/Text/Editor/AdornmentLayer.cs | 16 +- .../Text/Editor/BlockStructureService.cs | 10 +- .../Text/Editor/CommonGuidObjectsProvider.cs | 4 +- .../Text/Editor/CurrentLineHighlighter.cs | 6 +- .../Text/Editor/CustomLineNumberMargin.cs | 8 +- .../Editor/DefaultTextViewCommandTarget.cs | 2 +- .../Editor/DefaultTextViewMouseProcessor.cs | 8 +- dnSpy/dnSpy/Text/Editor/DsScrollBar.cs | 2 +- dnSpy/dnSpy/Text/Editor/EditorOptions.cs | 14 +- dnSpy/dnSpy/Text/Editor/GlyphMargin.cs | 22 +- .../Text/Editor/GlyphTextMarkerService.cs | 2 +- .../GlyphTextMarkerServiceMouseProcessor.cs | 16 +- ...GlyphTextViewMarkerClassificationTagger.cs | 2 +- .../Editor/GlyphTextViewMarkerGlyphTagger.cs | 2 +- ...lyphTextViewMarkerGlyphTextMarkerTagger.cs | 2 +- .../Text/Editor/GlyphTextViewMarkerService.cs | 58 ++--- dnSpy/dnSpy/Text/Editor/GoToCommand.cs | 8 +- .../Text/Editor/IntraTextAdornmentService.cs | 20 +- .../Text/Editor/KeyProcessorCollection.cs | 2 +- dnSpy/dnSpy/Text/Editor/LineCompressor.cs | 4 +- .../dnSpy/Text/Editor/LineNumberMarginBase.cs | 2 +- .../dnSpy/Text/Editor/LineSeparatorService.cs | 20 +- .../Text/Editor/MarginContextMenuService.cs | 8 +- dnSpy/dnSpy/Text/Editor/MarkerHelper.cs | 12 +- dnSpy/dnSpy/Text/Editor/MouseLocation.cs | 2 +- .../Text/Editor/MouseProcessorCollection.cs | 4 +- .../Text/Editor/PopupSpaceReservationAgent.cs | 6 +- .../Text/Editor/ReplCommandTargetFilter.cs | 2 +- dnSpy/dnSpy/Text/Editor/ReplCommands.cs | 2 +- dnSpy/dnSpy/Text/Editor/ReplEditor.cs | 34 +-- .../Editor/ResourceDictionaryUtilities.cs | 2 +- .../dnSpy/Text/Editor/Search/SearchService.cs | 28 +-- .../Text/Editor/SmartIndentationService.cs | 2 +- .../Text/Editor/SpaceReservationStack.cs | 4 +- dnSpy/dnSpy/Text/Editor/TextCaret.cs | 8 +- dnSpy/dnSpy/Text/Editor/TextCaretLayer.cs | 2 +- .../Text/Editor/TextEditorFactoryService.cs | 8 +- dnSpy/dnSpy/Text/Editor/TextMarkerService.cs | 8 +- dnSpy/dnSpy/Text/Editor/TextSelectionLayer.cs | 2 +- .../TextViewMouseProcessorCollection.cs | 4 +- dnSpy/dnSpy/Text/Editor/UriTagger.cs | 4 +- .../Text/Editor/WpfTextView.LayoutHelper.cs | 8 +- .../Editor/WpfTextView.MouseHoverHelper.cs | 4 +- dnSpy/dnSpy/Text/Editor/WpfTextView.cs | 36 +-- .../Text/Editor/WpfTextViewContainerMargin.cs | 2 +- .../Text/Editor/WpfTextViewLineCollection.cs | 2 +- .../WpfTextViewMarginProviderCollection.cs | 2 +- dnSpy/dnSpy/Text/Editor/ZoomControlMargin.cs | 12 +- .../Text/Formatting/HtmlBuilderService.cs | 2 +- dnSpy/dnSpy/Text/Formatting/LinePart.cs | 10 +- .../Text/Formatting/LinePartsCollection.cs | 4 +- .../Text/Formatting/LinePartsTextSource.cs | 6 +- .../LineTransformProviderService.cs | 2 +- .../Text/Formatting/PhysicalLineCache.cs | 2 +- .../Formatting/TextAndAdornmentSequencer.cs | 2 +- .../dnSpy/Text/Formatting/WpfTextViewLine.cs | 10 +- dnSpy/dnSpy/Text/Groups/OptionsStorage.cs | 2 +- .../dnSpy/Text/Groups/TextViewOptionsGroup.cs | 6 +- .../Groups/TextViewOptionsGroupService.cs | 6 +- .../dnSpy/Text/Operations/EditorOperations.cs | 16 +- .../Text/Operations/ReplEditorOperations.cs | 4 +- .../Text/Operations/TextSearchNavigator.cs | 8 +- .../Text/Operations/TextSearchService.cs | 8 +- .../TextStructureNavigatorSelectorService.cs | 2 +- .../dnSpy/Text/Operations/TextUndoHistory.cs | 6 +- dnSpy/dnSpy/Text/ProviderSelector.cs | 2 +- dnSpy/dnSpy/Text/Tagging/TagAggregatorBase.cs | 4 +- dnSpy/dnSpy/Text/Tagging/TaggerFactory.cs | 6 +- .../Xml/XamlAttributeValueClassifier.cs | 26 +-- dnSpy/dnSpy/Text/Tagging/Xml/XmlTaggerBase.cs | 22 +- dnSpy/dnSpy/Text/TextBuffer.cs | 8 +- dnSpy/dnSpy/Text/TextBufferFactoryService.cs | 6 +- dnSpy/dnSpy/Text/WPF/BrushComparer.cs | 2 +- .../dnSpy/Themes/AppCommandLineArgsHandler.cs | 2 +- dnSpy/dnSpy/Themes/ColorInfo.cs | 24 +- dnSpy/dnSpy/Themes/Theme.cs | 58 ++--- dnSpy/dnSpy/Themes/ThemeService.cs | 4 +- dnSpy/dnSpy/ToolBars/ToolBarService.cs | 16 +- dnSpy/dnSpy/ToolWindows/TabContentImpl.cs | 20 +- dnSpy/dnSpy/ToolWindows/ToolWindowGroup.cs | 8 +- .../ToolWindows/ToolWindowGroupService.cs | 4 +- dnSpy/dnSpy/ToolWindows/ToolWindowService.cs | 8 +- dnSpy/dnSpy/TreeView/TreeViewImpl.cs | 14 +- 1087 files changed, 4598 insertions(+), 4598 deletions(-) diff --git a/Build/ConvertToNetstandardReferences/ConvertToNetstandardReferences.cs b/Build/ConvertToNetstandardReferences/ConvertToNetstandardReferences.cs index 683f756a4b..f2bdcf063a 100644 --- a/Build/ConvertToNetstandardReferences/ConvertToNetstandardReferences.cs +++ b/Build/ConvertToNetstandardReferences/ConvertToNetstandardReferences.cs @@ -50,7 +50,7 @@ bool ShouldPatchAssembly(string simpleName) { } static bool IsPublic(TypeDef type) { - while (!(type is null)) { + while (type is not null) { if (!type.IsPublic && !type.IsNestedPublic) return false; type = type.DeclaringType; @@ -59,7 +59,7 @@ static bool IsPublic(TypeDef type) { } static bool IsPublic(ExportedType type) { - while (!(type is null)) { + while (type is not null) { if (!type.IsPublic && !type.IsNestedPublic) return false; type = type.DeclaringType; diff --git a/DnSpyCommon.props b/DnSpyCommon.props index 9bb1e450dd..c4ac11c7e9 100644 --- a/DnSpyCommon.props +++ b/DnSpyCommon.props @@ -13,7 +13,7 @@ false true strict;nullablePublicOnly - 8.0 + latest latest en false diff --git a/Extensions/Examples/Example1.Extension/CodeCtxMenus.cs b/Extensions/Examples/Example1.Extension/CodeCtxMenus.cs index bb8671f323..45a1c6f425 100644 --- a/Extensions/Examples/Example1.Extension/CodeCtxMenus.cs +++ b/Extensions/Examples/Example1.Extension/CodeCtxMenus.cs @@ -71,7 +71,7 @@ sealed class TextEditorCommand2 : MenuItemBase { sealed class TextEditorCommand3 : MenuItemBase { public override void Execute(IMenuItemContext context) { var md = GetTokenObj(context); - if (!(md is null)) { + if (md is not null) { try { Clipboard.SetText($"{md.MDToken.Raw:X8}"); } @@ -101,14 +101,14 @@ public override void Execute(IMenuItemContext context) { // Only show this in the document viewer public override bool IsVisible(IMenuItemContext context) => context.CreatorObject.Guid == new Guid(MenuConstants.GUIDOBJ_DOCUMENTVIEWERCONTROL_GUID); - public override bool IsEnabled(IMenuItemContext context) => !(GetTokenObj(context) is null); + public override bool IsEnabled(IMenuItemContext context) => GetTokenObj(context) is not null; } [ExportMenuItem(Group = Constants.GROUP_TEXTEDITOR, Order = 30)] sealed class TextEditorCommand4 : MenuItemBase { public override void Execute(IMenuItemContext context) { var documentViewer = GetDocumentViewer(context); - if (!(documentViewer is null)) { + if (documentViewer is not null) { try { var lineColumn = GetLineColumn(documentViewer.Caret.Position.VirtualBufferPosition); Clipboard.SetText($"Line,col: {lineColumn.Line + 1},{lineColumn.Column + 1}"); @@ -150,6 +150,6 @@ public LineColumn(int line, int column) { // Only show this in the document viewer public override bool IsVisible(IMenuItemContext context) => context.CreatorObject.Guid == new Guid(MenuConstants.GUIDOBJ_DOCUMENTVIEWERCONTROL_GUID); - public override bool IsEnabled(IMenuItemContext context) => !(GetDocumentViewer(context) is null); + public override bool IsEnabled(IMenuItemContext context) => GetDocumentViewer(context) is not null; } } diff --git a/Extensions/Examples/Example1.Extension/TreeViewCtxMenus.cs b/Extensions/Examples/Example1.Extension/TreeViewCtxMenus.cs index 3bad57682a..bbb787d170 100644 --- a/Extensions/Examples/Example1.Extension/TreeViewCtxMenus.cs +++ b/Extensions/Examples/Example1.Extension/TreeViewCtxMenus.cs @@ -84,7 +84,7 @@ sealed class TVCommand4 : TVCtxMenuCommand { sealed class TVCommand5 : TVCtxMenuCommand { public override void Execute(TVContext context) { var node = GetTokenNode(context); - if (!(node is null)) { + if (node is not null) { try { Clipboard.SetText($"{node.Reference!.MDToken.Raw:X8}"); } @@ -105,14 +105,14 @@ public override void Execute(TVContext context) { return $"Copy token {node.Reference!.MDToken.Raw:X8}"; } - public override bool IsVisible(TVContext context) => !(GetTokenNode(context) is null); + public override bool IsVisible(TVContext context) => GetTokenNode(context) is not null; } [ExportMenuItem(Header = "Copy Second Instruction", Group = Constants.GROUP_TREEVIEW, Order = 50)] sealed class TVCommand6 : TVCtxMenuCommand { public override void Execute(TVContext context) { var instr = GetSecondInstruction(context); - if (!(instr is null)) { + if (instr is not null) { try { Clipboard.SetText($"Second instruction: {instr}"); } @@ -132,6 +132,6 @@ public override void Execute(TVContext context) { return body.Instructions[1]; } - public override bool IsEnabled(TVContext context) => !(GetSecondInstruction(context) is null); + public override bool IsEnabled(TVContext context) => GetSecondInstruction(context) is not null; } } diff --git a/Extensions/Examples/Example2.Extension/AssemblyChildNodeTabContent.cs b/Extensions/Examples/Example2.Extension/AssemblyChildNodeTabContent.cs index e8bb4dfd67..c72c7bf63c 100644 --- a/Extensions/Examples/Example2.Extension/AssemblyChildNodeTabContent.cs +++ b/Extensions/Examples/Example2.Extension/AssemblyChildNodeTabContent.cs @@ -28,7 +28,7 @@ sealed class AssemblyChildNodeTabContentFactory : IDocumentTabContentFactory { // Serialize() doesn't add anything extra to 'section', but if it did, you'd have to // get that info here and return null if the serialized data wasn't found. var node = context.Nodes.Length == 1 ? context.Nodes[0] as AssemblyChildNode : null; - if (!(node is null)) + if (node is not null) return new AssemblyChildNodeTabContent(node); } return null; diff --git a/Extensions/Examples/Example2.Extension/NewDsDocument.cs b/Extensions/Examples/Example2.Extension/NewDsDocument.cs index bca8eb679b..ecb5ab73f6 100644 --- a/Extensions/Examples/Example2.Extension/NewDsDocument.cs +++ b/Extensions/Examples/Example2.Extension/NewDsDocument.cs @@ -28,7 +28,7 @@ sealed class MyDsDocument : DsDocument { // Used by MyDsDocumentNode.Decompile() to show the file in the text editor public string Text { get { - if (!(text is null)) + if (text is not null) return text; try { return text = File.ReadAllText(Filename); diff --git a/Extensions/Examples/Example2.Extension/OutputTextPane.cs b/Extensions/Examples/Example2.Extension/OutputTextPane.cs index ff92b71b77..1488fd29c1 100644 --- a/Extensions/Examples/Example2.Extension/OutputTextPane.cs +++ b/Extensions/Examples/Example2.Extension/OutputTextPane.cs @@ -22,7 +22,7 @@ public static IOutputTextPane Instance { return _instance; } set { - if (!(_instance is null)) + if (_instance is not null) throw new InvalidOperationException("Can't initialize the logger twice"); _instance = value ?? throw new ArgumentNullException(nameof(value)); } diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/AssemblyInfoTransform.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/AssemblyInfoTransform.cs index 58839a14a0..3be97f1ca8 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/AssemblyInfoTransform.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/AssemblyInfoTransform.cs @@ -28,7 +28,7 @@ sealed class AssemblyInfoTransform : IAstTransform { public void Run(AstNode compilationUnit) { foreach (var attrSect in compilationUnit.Descendants.OfType()) { var attr = attrSect.Descendants.OfType().FirstOrDefault(); - Debug2.Assert(!(attr is null)); + Debug2.Assert(attr is not null); if (attr is null) continue; bool remove = false; diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/CSharpDecompiler.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/CSharpDecompiler.cs index bd0c255fbc..55b949f43e 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/CSharpDecompiler.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/CSharpDecompiler.cs @@ -44,7 +44,7 @@ public DecompilerProvider() } public DecompilerProvider(DecompilerSettingsService decompilerSettingsService) { - Debug2.Assert(!(decompilerSettingsService is null)); + Debug2.Assert(decompilerSettingsService is not null); this.decompilerSettingsService = decompilerSettingsService ?? throw new ArgumentNullException(nameof(decompilerSettingsService)); } @@ -243,7 +243,7 @@ public override void Decompile(TypeDef type, IDecompilerOutput output, Decompila void RunTransformsAndGenerateCode(ref BuilderState state, IDecompilerOutput output, DecompilationContext ctx, IAstTransform? additionalTransform = null) { var astBuilder = state.AstBuilder; astBuilder.RunTransformations(transformAbortCondition); - if (!(additionalTransform is null)) { + if (additionalTransform is not null) { additionalTransform.Run(astBuilder.SyntaxTree); } AddXmlDocumentation(ref state, langSettings.Settings, astBuilder); @@ -256,7 +256,7 @@ internal static void AddXmlDocumentation(ref BuilderState state, DecompilerSetti var hasXmlDocFileTmp = state.State.HasXmlDocFile(module); bool hasXmlDocFile; if (hasXmlDocFileTmp is null) { - hasXmlDocFile = !(XmlDocLoader.LoadDocumentation(module) is null); + hasXmlDocFile = XmlDocLoader.LoadDocumentation(module) is not null; state.State.SetHasXmlDocFile(module, hasXmlDocFile); } else @@ -335,11 +335,11 @@ protected override void TypeToString(IDecompilerOutput output, ITypeDefOrRef? ty static readonly UTF8String isReadOnlyAttributeString = new UTF8String("IsReadOnlyAttribute"); bool WriteRefIfByRef(IDecompilerOutput output, TypeSig typeSig, ParamDef? pd) { if (typeSig.RemovePinnedAndModifiers() is ByRefSig) { - if (!(pd is null) && (!pd.IsIn && pd.IsOut)) { + if (pd is not null && (!pd.IsIn && pd.IsOut)) { output.Write("out", BoxedTextColor.Keyword); output.Write(" ", BoxedTextColor.Text); } - else if (!(pd is null) && pd.IsDefined(systemRuntimeCompilerServicesString, isReadOnlyAttributeString)) { + else if (pd is not null && pd.IsDefined(systemRuntimeCompilerServicesString, isReadOnlyAttributeString)) { output.Write("in", BoxedTextColor.Keyword); output.Write(" ", BoxedTextColor.Text); } @@ -375,7 +375,7 @@ protected override void FormatPropertyName(IDecompilerOutput output, PropertyDef } if (isIndexer.Value) { var accessor = property.GetMethod ?? property.SetMethod; - if (!(accessor is null) && accessor.HasOverrides) { + if (accessor is not null && accessor.HasOverrides) { var methDecl = accessor.Overrides.First().MethodDeclaration; var declaringType = methDecl is null ? null : methDecl.DeclaringType; TypeToString(output, declaringType, includeNamespace: true); diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/DecompilePartialTransform.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/DecompilePartialTransform.cs index 56c2046809..ca9e5508d6 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/DecompilePartialTransform.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/DecompilePartialTransform.cs @@ -43,13 +43,13 @@ public DecompilePartialTransform(TypeDef type, HashSet definitions, public void Run(AstNode compilationUnit) { foreach (var en in compilationUnit.Descendants.OfType()) { var def = en.Annotation(); - Debug2.Assert(!(def is null)); + Debug2.Assert(def is not null); if (def is null) continue; if (def == type) { var tdecl = en as TypeDeclaration; - Debug2.Assert(!(tdecl is null)); - if (!(tdecl is null)) { + Debug2.Assert(tdecl is not null); + if (tdecl is not null) { if (addPartialKeyword) { if (tdecl.ClassType != ClassType.Enum) tdecl.Modifiers |= Modifiers.Partial; @@ -63,7 +63,7 @@ public void Run(AstNode compilationUnit) { } foreach (var iface in tdecl.BaseTypes) { var tdr = iface.Annotation(); - if (!(tdr is null) && ifacesToRemove.Contains(tdr)) + if (tdr is not null && ifacesToRemove.Contains(tdr)) iface.Remove(); } } diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/DecompileTypeMethodsTransform.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/DecompileTypeMethodsTransform.cs index dca66ea226..d7d7a718f4 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/DecompileTypeMethodsTransform.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/CSharp/DecompileTypeMethodsTransform.cs @@ -40,7 +40,7 @@ public DecompileTypeMethodsTransform(HashSet types, HashSet foreach (var method in methods) { // If it's part of a property or event, include the property or event since there are no partial props/events var prop = method.DeclaringType.Properties.FirstOrDefault(a => a.GetMethods.Contains(method) || a.SetMethods.Contains(method)); - if (!(prop is null)) { + if (prop is not null) { defsToShow.Add(prop); foreach (var m in prop.GetMethods) defsToShow.Add(m); @@ -51,13 +51,13 @@ public DecompileTypeMethodsTransform(HashSet types, HashSet } else { var evt = method.DeclaringType.Events.FirstOrDefault(a => a.AddMethod == method || a.RemoveMethod == method); - if (!(evt is null)) { + if (evt is not null) { defsToShow.Add(evt); - if (!(evt.AddMethod is null)) + if (evt.AddMethod is not null) defsToShow.Add(evt.AddMethod); - if (!(evt.RemoveMethod is null)) + if (evt.RemoveMethod is not null) defsToShow.Add(evt.RemoveMethod); - if (!(evt.InvokeMethod is null)) + if (evt.InvokeMethod is not null) defsToShow.Add(evt.InvokeMethod); foreach (var m in evt.OtherMethods) defsToShow.Add(m); @@ -73,7 +73,7 @@ public DecompileTypeMethodsTransform(HashSet types, HashSet } } foreach (var def in defsToShow) { - for (var declType = def.DeclaringType; !(declType is null); declType = declType.DeclaringType) + for (var declType = def.DeclaringType; declType is not null; declType = declType.DeclaringType) partialTypes.Add(declType); } foreach (var type in types) { @@ -88,14 +88,14 @@ public DecompileTypeMethodsTransform(HashSet types, HashSet public void Run(AstNode compilationUnit) { foreach (var en in compilationUnit.Descendants.OfType()) { var def = en.Annotation(); - Debug2.Assert(!(def is null)); + Debug2.Assert(def is not null); if (def is null) continue; if (partialTypes.Contains(def)) { var tdecl = en as TypeDeclaration; - Debug2.Assert(!(tdecl is null)); - if (!(tdecl is null)) { + Debug2.Assert(tdecl is not null); + if (tdecl is not null) { if (tdecl.ClassType != ClassType.Enum) tdecl.Modifiers |= Modifiers.Partial; if (!showDefinitions) { diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/IL/ILDecompiler.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/IL/ILDecompiler.cs index 8e3c5aab59..8a28c63ed6 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/IL/ILDecompiler.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/IL/ILDecompiler.cs @@ -40,7 +40,7 @@ public DecompilerProvider() } public DecompilerProvider(DecompilerSettingsService decompilerSettingsService) { - Debug2.Assert(!(decompilerSettingsService is null)); + Debug2.Assert(decompilerSettingsService is not null); this.decompilerSettingsService = decompilerSettingsService ?? throw new ArgumentNullException(nameof(decompilerSettingsService)); } @@ -89,7 +89,7 @@ ReflectionDisassembler CreateReflectionDisassembler(IDecompilerOutput output, De var sb = new StringBuilder(); if (langSettings.Settings.ShowXmlDocumentation) disOpts.GetXmlDocComments = a => GetXmlDocComments(a, sb); - disOpts.CreateInstructionBytesReader = m => InstructionBytesReader.Create(m, !(ctx.IsBodyModified is null) && ctx.IsBodyModified(m)); + disOpts.CreateInstructionBytesReader = m => InstructionBytesReader.Create(m, ctx.IsBodyModified is not null && ctx.IsBodyModified(m)); disOpts.ShowTokenAndRvaComments = langSettings.Settings.ShowTokenAndRvaComments; disOpts.ShowILBytes = langSettings.Settings.ShowILBytes; disOpts.SortMembers = langSettings.Settings.SortMembers; @@ -111,7 +111,7 @@ static IEnumerable GetXmlDocComments(IMemberRef mr, StringBuilder sb) { foreach (var info in new XmlDocLine(doc)) { sb.Clear(); - if (!(info is null)) { + if (info is not null) { sb.Append(' '); info.Value.WriteTo(sb); } @@ -132,11 +132,11 @@ public override void Decompile(FieldDef field, IDecompilerOutput output, Decompi public override void Decompile(PropertyDef property, IDecompilerOutput output, DecompilationContext ctx) { ReflectionDisassembler rd = CreateReflectionDisassembler(output, ctx, property); rd.DisassembleProperty(property, addLineSep: true); - if (!(property.GetMethod is null)) { + if (property.GetMethod is not null) { output.WriteLine(); rd.DisassembleMethod(property.GetMethod, true); } - if (!(property.SetMethod is null)) { + if (property.SetMethod is not null) { output.WriteLine(); rd.DisassembleMethod(property.SetMethod, true); } @@ -149,11 +149,11 @@ public override void Decompile(PropertyDef property, IDecompilerOutput output, D public override void Decompile(EventDef ev, IDecompilerOutput output, DecompilationContext ctx) { ReflectionDisassembler rd = CreateReflectionDisassembler(output, ctx, ev); rd.DisassembleEvent(ev, addLineSep: true); - if (!(ev.AddMethod is null)) { + if (ev.AddMethod is not null) { output.WriteLine(); rd.DisassembleMethod(ev.AddMethod, true); } - if (!(ev.RemoveMethod is null)) { + if (ev.RemoveMethod is not null) { output.WriteLine(); rd.DisassembleMethod(ev.RemoveMethod, true); } diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/ILAst/ILAstDecompiler.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/ILAst/ILAstDecompiler.cs index 506ba385d8..66e505c774 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/ILAst/ILAstDecompiler.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/ILAst/ILAstDecompiler.cs @@ -39,7 +39,7 @@ public DecompilerProvider() } public DecompilerProvider(DecompilerSettingsService decompilerSettingsService) { - Debug2.Assert(!(decompilerSettingsService is null)); + Debug2.Assert(decompilerSettingsService is not null); this.decompilerSettingsService = decompilerSettingsService ?? throw new ArgumentNullException(nameof(decompilerSettingsService)); } @@ -104,7 +104,7 @@ public override void Decompile(MethodDef method, IDecompilerOutput output, Decom MethodDef? inlinedMethod = null; AsyncMethodDebugInfo? asyncInfo = null; string? compilerName = null; - if (!(abortBeforeStep is null)) { + if (abortBeforeStep is not null) { var optimizer = new ILAstOptimizer(); optimizer.Optimize(context, ilMethod, out stateMachineKind, out inlinedMethod, out asyncInfo, abortBeforeStep.Value); compilerName = optimizer.CompilerName; @@ -122,11 +122,11 @@ public override void Decompile(MethodDef method, IDecompilerOutput output, Decom } var allVariables = ilMethod.GetSelfAndChildrenRecursive().Select(e => e.Operand as ILVariable) - .Where(v => !(v is null) && !v.IsParameter).Distinct(); + .Where(v => v is not null && !v.IsParameter).Distinct(); foreach (var v in allVariables) { - Debug2.Assert(!(v is null)); + Debug2.Assert(v is not null); output.Write(IdentifierEscaper.Escape(v.Name), v.GetTextReferenceObject(), DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, v.IsParameter ? BoxedTextColor.Parameter : BoxedTextColor.Local); - if (!(v.Type is null)) { + if (v.Type is not null) { output.Write(" ", BoxedTextColor.Text); output.Write(":", BoxedTextColor.Punctuation); output.Write(" ", BoxedTextColor.Text); @@ -149,7 +149,7 @@ public override void Decompile(MethodDef method, IDecompilerOutput output, Decom } var localVariables = new HashSet(GetVariables(ilMethod)); - var builder = new MethodDebugInfoBuilder(settingsVersion, stateMachineKind, inlinedMethod ?? method, !(inlinedMethod is null) ? method : null, CreateSourceLocals(localVariables), CreateSourceParameters(localVariables), asyncInfo); + var builder = new MethodDebugInfoBuilder(settingsVersion, stateMachineKind, inlinedMethod ?? method, inlinedMethod is not null ? method : null, CreateSourceLocals(localVariables), CreateSourceParameters(localVariables), asyncInfo); builder.CompilerName = compilerName; foreach (ILNode node in ilMethod.Body) { node.WriteTo(output, builder); @@ -163,14 +163,14 @@ public override void Decompile(MethodDef method, IDecompilerOutput output, Decom IEnumerable GetVariables(ILBlock ilMethod) { foreach (var n in ilMethod.GetSelfAndChildrenRecursive(new List())) { var expr = n as ILExpression; - if (!(expr is null)) { + if (expr is not null) { var v = expr.Operand as ILVariable; - if (!(v is null)) + if (v is not null) yield return v; continue; } var cb = n as ILTryCatchBlock.CatchBlockBase; - if (!(cb is null) && !(cb.ExceptionVariable is null)) + if (cb is not null && cb.ExceptionVariable is not null) yield return cb.ExceptionVariable; } } @@ -229,17 +229,17 @@ void EndKeywordBlock(IDecompilerOutput output, BraceInfo info, CodeBracesRangeFl public override void Decompile(EventDef ev, IDecompilerOutput output, DecompilationContext ctx) { var eventInfo = StartKeywordBlock(output, ".event", ev); - if (!(ev.AddMethod is null)) { + if (ev.AddMethod is not null) { var info = StartKeywordBlock(output, ".add", ev.AddMethod); EndKeywordBlock(output, info, CodeBracesRangeFlags.AccessorBraces); } - if (!(ev.InvokeMethod is null)) { + if (ev.InvokeMethod is not null) { var info = StartKeywordBlock(output, ".invoke", ev.InvokeMethod); EndKeywordBlock(output, info, CodeBracesRangeFlags.AccessorBraces); } - if (!(ev.RemoveMethod is null)) { + if (ev.RemoveMethod is not null) { var info = StartKeywordBlock(output, ".remove", ev.RemoveMethod); EndKeywordBlock(output, info, CodeBracesRangeFlags.AccessorBraces); } @@ -252,7 +252,7 @@ public override void Decompile(FieldDef field, IDecompilerOutput output, Decompi output.Write(" ", BoxedTextColor.Text); output.Write(IdentifierEscaper.Escape(field.Name), field, DecompilerReferenceFlags.Definition, MetadataTextColorProvider.GetColor(field)); var c = field.Constant; - if (!(c is null)) { + if (c is not null) { output.Write(" ", BoxedTextColor.Text); output.Write("=", BoxedTextColor.Operator); output.Write(" ", BoxedTextColor.Text); @@ -321,7 +321,7 @@ public override void Decompile(PropertyDef property, IDecompilerOutput output, D public override void Decompile(TypeDef type, IDecompilerOutput output, DecompilationContext ctx) { this.WriteCommentLine(output, $"Type: {type.FullName}"); - if (!(type.BaseType is null)) { + if (type.BaseType is not null) { WriteCommentBegin(output, true); output.Write("Base type: ", BoxedTextColor.Comment); output.Write(IdentifierEscaper.Escape(type.BaseType.FullName), type.BaseType, DecompilerReferenceFlags.None, BoxedTextColor.Comment); diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/Settings/CSharpVBDecompilerSettings.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/Settings/CSharpVBDecompilerSettings.cs index dfddc25a08..b474cedb10 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/Settings/CSharpVBDecompilerSettings.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/Settings/CSharpVBDecompilerSettings.cs @@ -273,7 +273,7 @@ void SetMemberOrder(string s) { public override bool Equals(object? obj) { var other = obj as CSharpVBDecompilerSettings; - return !(other is null) && decompilerSettings.Equals(other.decompilerSettings); + return other is not null && decompilerSettings.Equals(other.decompilerSettings); } public override int GetHashCode() => decompilerSettings.GetHashCode(); diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/Settings/ILSettings.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/Settings/ILSettings.cs index 9bf5a46082..1ba430d335 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/Settings/ILSettings.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/Settings/ILSettings.cs @@ -146,7 +146,7 @@ public ILSettings CopyTo(ILSettings other) { public override bool Equals(object? obj) { var other = obj as ILSettings; - return !(other is null) && + return other is not null && ShowILComments == other.ShowILComments && ShowXmlDocumentation == other.ShowXmlDocumentation && ShowTokenAndRvaComments == other.ShowTokenAndRvaComments && diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/ILSpyEnvironmentProvider.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/ILSpyEnvironmentProvider.cs index 8c954b7cf2..54b037f347 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/ILSpyEnvironmentProvider.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/ILSpyEnvironmentProvider.cs @@ -47,7 +47,7 @@ public string GetTypeNameForAttribute(ICSharpCode.NRefactory.CSharp.Attribute at return null; IEntity current = null; -if (!(entity is null)) { +if (entity is not null) { var typeInfo = entity.Annotation(); current = loader.ReadTypeReference(typeInfo).Resolve(context).GetDefinition(); } @@ -128,7 +128,7 @@ public TypeCode ResolveExpression(ICSharpCode.NRefactory.CSharp.Expression expre } } - public bool HasEvent(ICSharpCode.NRefactory.VB.Ast.Expression expression) => !(expression.Annotation() is null); + public bool HasEvent(ICSharpCode.NRefactory.VB.Ast.Expression expression) => expression.Annotation() is not null; public bool IsMethodGroup(ICSharpCode.NRefactory.CSharp.Expression expression) { var annotation = expression.Annotation(); @@ -145,10 +145,10 @@ public ICSharpCode.NRefactory.CSharp.ParameterDeclaration[] GetParametersForProp sb.Clear(); var getMethod = propInfo.GetMethod; - if (!(getMethod is null)) + if (getMethod is not null) return getMethod.Parameters.Where(p => p.IsNormalMethodParameter).Select(p => new ICSharpCode.NRefactory.CSharp.ParameterDeclaration(AstBuilder.ConvertType(p.Type, sb), p.Name, GetModifiers(p))).ToArray(); var setMethod = propInfo.SetMethod; - if (!(setMethod is null)) { + if (setMethod is not null) { var ps = setMethod.Parameters.Where(p => p.IsNormalMethodParameter).ToArray(); if (ps.Length > 1) return ps.Take(ps.Length - 1).Select(p => new ICSharpCode.NRefactory.CSharp.ParameterDeclaration(AstBuilder.ConvertType(p.Type, sb), p.Name, GetModifiers(p))).ToArray(); @@ -159,7 +159,7 @@ public ICSharpCode.NRefactory.CSharp.ParameterDeclaration[] GetParametersForProp ICSharpCode.NRefactory.CSharp.ParameterModifier GetModifiers(Parameter p) { var pd = p.ParamDef; - if (!(pd is null)) { + if (pd is not null) { if (pd.IsOut && pd.IsIn) return ICSharpCode.NRefactory.CSharp.ParameterModifier.Ref; if (pd.IsOut) diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/VBDecompiler.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/VBDecompiler.cs index 63227b5fbc..dda8e7a8b4 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/VBDecompiler.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/VBDecompiler.cs @@ -43,7 +43,7 @@ public DecompilerProvider() } public DecompilerProvider(DecompilerSettingsService decompilerSettingsService) { - Debug2.Assert(!(decompilerSettingsService is null)); + Debug2.Assert(decompilerSettingsService is not null); this.decompilerSettingsService = decompilerSettingsService ?? throw new ArgumentNullException(nameof(decompilerSettingsService)); } @@ -195,7 +195,7 @@ VBFormattingOptions CreateVBFormattingOptions(DecompilerSettings settings) => void RunTransformsAndGenerateCode(ref BuilderState state, IDecompilerOutput output, DecompilationContext ctx, IAstTransform? additionalTransform = null) { var astBuilder = state.AstBuilder; astBuilder.RunTransformations(transformAbortCondition); - if (!(additionalTransform is null)) { + if (additionalTransform is not null) { additionalTransform.Run(astBuilder.SyntaxTree); } var settings = GetDecompilerSettings(); @@ -249,7 +249,7 @@ void TypeToString(IDecompilerOutput output, ConvertTypeOptions options, ITypeDef var converter = new CSharpToVBConverterVisitor(type.Module, envProvider); var astType = AstBuilder.ConvertType(type, new StringBuilder(), typeAttributes, options); - if (!(type.TryGetByRefSig() is null)) { + if (type.TryGetByRefSig() is not null) { output.Write("ByRef", BoxedTextColor.Keyword); output.Write(" ", BoxedTextColor.Text); if (astType is ICSharpCode.NRefactory.CSharp.ComposedType && ((ICSharpCode.NRefactory.CSharp.ComposedType)astType).PointerRank > 0) diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/VBTextOutputFormatter.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/VBTextOutputFormatter.cs index cdc5dbf8fb..bb0d4d3355 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/VBTextOutputFormatter.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/VisualBasic/VBTextOutputFormatter.cs @@ -48,13 +48,13 @@ public void StartNode(AstNode node) { nodeStack.Push(node); MethodDebugInfoBuilder mapping = node.Annotation(); - if (!(mapping is null)) { + if (mapping is not null) { parentMethodDebugInfoBuilder.Push(currentMethodDebugInfoBuilder); currentMethodDebugInfoBuilder = mapping; } // For ctor/cctor field initializers var mms = node.Annotation>>>(); - if (!(mms is null)) { + if (mms is not null) { Debug2.Assert(multiMappings is null); multiMappings = mms; } @@ -64,8 +64,8 @@ public void EndNode(AstNode node) { if (nodeStack.Pop() != node) throw new InvalidOperationException(); - if (!(node.Annotation() is null)) { - Debug2.Assert(!(currentMethodDebugInfoBuilder is null)); + if (node.Annotation() is not null) { + Debug2.Assert(currentMethodDebugInfoBuilder is not null); if (context.CalculateILSpans) { foreach (var ns in context.UsingNamespaces) currentMethodDebugInfoBuilder.Scope.Imports.Add(ImportInfo.CreateNamespace(ns)); @@ -74,7 +74,7 @@ public void EndNode(AstNode node) { currentMethodDebugInfoBuilder = parentMethodDebugInfoBuilder.Pop(); } var mms = node.Annotation>>>(); - if (!(mms is null)) { + if (mms is not null) { Debug.Assert(mms == multiMappings); if (mms == multiMappings) { foreach (var mm in mms) @@ -86,25 +86,25 @@ public void EndNode(AstNode node) { public void WriteIdentifier(string identifier, object data, object extraData) { var definition = GetCurrentDefinition(); - if (!(definition is null)) { + if (definition is not null) { output.Write(IdentifierEscaper.Escape(identifier), definition, DecompilerReferenceFlags.Definition, data); return; } var memberRef = GetCurrentMemberReference() ?? (object?)(extraData as NamespaceReference); - if (!(memberRef is null)) { + if (memberRef is not null) { output.Write(IdentifierEscaper.Escape(identifier), memberRef, DecompilerReferenceFlags.None, data); return; } definition = GetCurrentLocalDefinition(); - if (!(definition is null)) { + if (definition is not null) { output.Write(IdentifierEscaper.Escape(identifier), definition, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, data); return; } memberRef = GetCurrentLocalReference(); - if (!(memberRef is null)) { + if (memberRef is not null) { output.Write(IdentifierEscaper.Escape(identifier), memberRef, DecompilerReferenceFlags.Local, data); return; } @@ -114,7 +114,7 @@ public void WriteIdentifier(string identifier, object data, object extraData) { IMemberRef? GetCurrentMemberReference() { AstNode node = nodeStack.Peek(); - if (!(node.Annotation() is null)) + if (node.Annotation() is not null) return null; if (node.Role == AstNode.Roles.Type && node.Parent is ObjectCreationExpression) node = node.Parent; @@ -134,12 +134,12 @@ public void WriteIdentifier(string identifier, object data, object extraData) { ILVariable variable = node.Annotation(); if (variable is null && node.Parent is IdentifierExpression) variable = node.Parent.Annotation(); - if (!(variable is null)) + if (variable is not null) return variable.GetTextReferenceObject(); var lbl = (node.Parent?.Parent as GoToStatement)?.Label ?? (node.Parent?.Parent as LabelDeclarationStatement)?.Label; - if (!(lbl is null)) { - var method = nodeStack.Select(nd => nd.Annotation()).FirstOrDefault(mr => !(mr is null) && mr.IsMethod); - if (!(method is null)) + if (lbl is not null) { + var method = nodeStack.Select(nd => nd.Annotation()).FirstOrDefault(mr => mr is not null && mr.IsMethod); + if (method is not null) return method.ToString() + lbl; } return null; @@ -150,30 +150,30 @@ public void WriteIdentifier(string identifier, object data, object extraData) { if (node is Identifier && node.Parent is CatchBlock) node = node.Parent; var parameterDef = node.Annotation(); - if (!(parameterDef is null)) + if (parameterDef is not null) return parameterDef; if (node is ParameterDeclaration) { node = ((ParameterDeclaration)node).Name; parameterDef = node.Annotation(); - if (!(parameterDef is null)) + if (parameterDef is not null) return parameterDef; } if (node is VariableIdentifier) { var variable = ((VariableIdentifier)node).Name.Annotation(); - if (!(variable is null)) + if (variable is not null) return variable.GetTextReferenceObject(); node = node.Parent ?? node; } if (node is VariableDeclaratorWithTypeAndInitializer || node is VariableInitializer || node is CatchBlock || node is ForEachStatement) { var variable = node.Annotation(); - if (!(variable is null)) + if (variable is not null) return variable.GetTextReferenceObject(); } if (node is LabelDeclarationStatement label) { - var method = nodeStack.Select(nd => nd.Annotation()).FirstOrDefault(mr => !(mr is null) && mr.IsMethod); - if (!(method is null)) + var method = nodeStack.Select(nd => nd.Annotation()).FirstOrDefault(mr => mr is not null && mr.IsMethod); + if (method is not null) return method.ToString() + label.Label; } @@ -205,18 +205,18 @@ public void WriteIdentifier(string identifier, object data, object extraData) { public void WriteKeyword(string keyword) { var memberRef = GetCurrentMemberReference(); var node = nodeStack.Peek(); - if (!(memberRef is null) && (node is PrimitiveType || node is InstanceExpression)) + if (memberRef is not null && (node is PrimitiveType || node is InstanceExpression)) output.Write(keyword, memberRef, DecompilerReferenceFlags.None, BoxedTextColor.Keyword); - else if (!(memberRef is null) && (node is ConstructorDeclaration && keyword == "New")) + else if (memberRef is not null && (node is ConstructorDeclaration && keyword == "New")) output.Write(keyword, memberRef, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, BoxedTextColor.Keyword); - else if (!(memberRef is null) && (node is Accessor && (keyword == "Get" || keyword == "Set" || keyword == "AddHandler" || keyword == "RemoveHandler" || keyword == "RaiseEvent"))) { + else if (memberRef is not null && (node is Accessor && (keyword == "Get" || keyword == "Set" || keyword == "AddHandler" || keyword == "RemoveHandler" || keyword == "RaiseEvent"))) { if (canPrintAccessor) output.Write(keyword, memberRef, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, BoxedTextColor.Keyword); else output.Write(keyword, BoxedTextColor.Keyword); canPrintAccessor = !canPrintAccessor; } - else if (!(memberRef is null) && node is OperatorDeclaration && keyword == "Operator") + else if (memberRef is not null && node is OperatorDeclaration && keyword == "Operator") output.Write(keyword, memberRef, DecompilerReferenceFlags.Definition, BoxedTextColor.Keyword); else output.Write(keyword, BoxedTextColor.Keyword); @@ -227,7 +227,7 @@ public void WriteToken(string token, object data, object? reference) { var memberRef = GetCurrentMemberReference(); var node = nodeStack.Peek(); - bool addRef = !(memberRef is null) && + bool addRef = memberRef is not null && (node is BinaryOperatorExpression || node is UnaryOperatorExpression || node is AssignmentExpression); @@ -235,13 +235,13 @@ node is UnaryOperatorExpression || // Add a ref to the method if it's a delegate call if (!addRef && node is InvocationExpression && memberRef is IMethod) { var md = Resolve(memberRef as IMethod); - if (!(md is null) && !(md.DeclaringType is null) && md.DeclaringType.IsDelegate) + if (md is not null && md.DeclaringType is not null && md.DeclaringType.IsDelegate) addRef = true; } if (addRef) output.Write(token, memberRef, DecompilerReferenceFlags.None, data); - else if (!(reference is null)) + else if (reference is not null) output.Write(token, reference, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Hidden | DecompilerReferenceFlags.NoFollow, data); else output.Write(token, data); @@ -329,11 +329,11 @@ public void DebugExpression(AstNode node) { public void DebugEnd(AstNode node) { var state = debugStack.Pop(); - if (!(currentMethodDebugInfoBuilder is null)) { + if (currentMethodDebugInfoBuilder is not null) { foreach (var ilSpan in ILSpan.OrderAndCompact(GetILSpans(state))) currentMethodDebugInfoBuilder.Add(new SourceStatement(ilSpan, new TextSpan(state.StartLocation, output.NextPosition - state.StartLocation))); } - else if (!(multiMappings is null)) { + else if (multiMappings is not null) { foreach (var mm in multiMappings) { foreach (var ilSpan in ILSpan.OrderAndCompact(mm.Item2)) mm.Item1.Add(new SourceStatement(ilSpan, new TextSpan(state.StartLocation, output.NextPosition - state.StartLocation))); @@ -356,8 +356,8 @@ static IEnumerable GetILSpans(DebugState state) { } public void AddHighlightedKeywordReference(object reference, int start, int end) { - Debug2.Assert(!(reference is null)); - if (!(reference is null)) + Debug2.Assert(reference is not null); + if (reference is not null) output.AddSpanReference(reference, start, end, PredefinedSpanReferenceIds.HighlightRelatedKeywords); } diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/XmlDoc/AddXmlDocTransform.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/XmlDoc/AddXmlDocTransform.cs index 7173c8084a..9a30b183ca 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/XmlDoc/AddXmlDocTransform.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/XmlDoc/AddXmlDocTransform.cs @@ -34,9 +34,9 @@ struct AddXmlDocTransform { public void Run(AstNode node) { if (node is EntityDeclaration) { IMemberRef mr = node.Annotation(); - if (!(mr is null) && !(mr.Module is null)) { + if (mr is not null && mr.Module is not null) { var xmldoc = XmlDocLoader.LoadDocumentation(mr.Module); - if (!(xmldoc is null)) { + if (xmldoc is not null) { var doc = xmldoc.GetDocumentation(XmlDocKeyProvider.GetKey(mr, stringBuilder)); if (!string2.IsNullOrEmpty(doc)) { InsertXmlDocumentation(node, doc); @@ -53,7 +53,7 @@ public void Run(AstNode node) { void InsertXmlDocumentation(AstNode node, string doc) { foreach (var info in new XmlDocLine(doc)) { stringBuilder.Clear(); - if (!(info is null)) { + if (info is not null) { stringBuilder.Append(' '); info.Value.WriteTo(stringBuilder); } diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/XmlDoc/XmlDocLine.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/XmlDoc/XmlDocLine.cs index 92396f1dd5..638b017dda 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/XmlDoc/XmlDocLine.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy.Core/XmlDoc/XmlDocLine.cs @@ -105,7 +105,7 @@ public bool MoveNext() { } void Trim(out int trimmedIndex, out int trimmedEnd) { - Debug2.Assert(!(indent is null)); + Debug2.Assert(indent is not null); int index = iter.Current.Index; int end = index + iter.Current.Length; diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy/Settings/CSharpDecompilerSettingsPage.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy/Settings/CSharpDecompilerSettingsPage.cs index b6ad7223a4..3d648e371b 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy/Settings/CSharpDecompilerSettingsPage.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy/Settings/CSharpDecompilerSettingsPage.cs @@ -67,7 +67,7 @@ public DecompilationObjectVM DecompilationObject4 { } void SetDecompilationObject(int index, DecompilationObjectVM newValue) { - Debug2.Assert(!(newValue is null)); + Debug2.Assert(newValue is not null); if (newValue is null) throw new ArgumentNullException(nameof(newValue)); if (decompilationObjectVMs[index] == newValue) diff --git a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy/Settings/DecompilerAppSettingsModifiedListener.cs b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy/Settings/DecompilerAppSettingsModifiedListener.cs index 6040707787..aa2a648729 100644 --- a/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy/Settings/DecompilerAppSettingsModifiedListener.cs +++ b/Extensions/ILSpy.Decompiler/dnSpy.Decompiler.ILSpy/Settings/DecompilerAppSettingsModifiedListener.cs @@ -58,7 +58,7 @@ public void OnSettingsModified(IAppRefreshSettings appRefreshSettings) { get { foreach (var tab in documentTabService.VisibleFirstTabs) { var decompiler = (tab.Content as IDecompilerTabContent)?.Decompiler; - if (!(decompiler is null)) + if (decompiler is not null) yield return (tab, decompiler); } } diff --git a/Extensions/dnSpy.Analyzer/AnalyzerService.cs b/Extensions/dnSpy.Analyzer/AnalyzerService.cs index 4dee71b017..ea108b2e2f 100644 --- a/Extensions/dnSpy.Analyzer/AnalyzerService.cs +++ b/Extensions/dnSpy.Analyzer/AnalyzerService.cs @@ -143,7 +143,7 @@ void DocumentTabService_FileModified(object? sender, DocumentModifiedEventArgs e void ActivateNode() { var nodes = TreeView.TopLevelSelection; var node = nodes.Length == 0 ? null : nodes[0] as TreeNodeData; - if (!(node is null)) + if (node is not null) node.Activate(); } @@ -194,7 +194,7 @@ void AnalyzerSettings_PropertyChanged(object? sender, PropertyChangedEventArgs e void ITreeViewListener.OnEvent(ITreeView treeView, TreeViewListenerEventArgs e) { if (e.Event == TreeViewListenerEvent.NodeCreated) { - Debug2.Assert(!(context is null)); + Debug2.Assert(context is not null); var node = (ITreeNode)e.Argument; if (node.Data is AnalyzerTreeNodeData d) d.Context = context; @@ -213,7 +213,7 @@ void ClearAll() { public void Add(AnalyzerTreeNodeData node) { if (node is EntityNode an) { var found = TreeView.Root.DataChildren.OfType().FirstOrDefault(n => n.Member == an.Member); - if (!(found is null)) { + if (found is not null) { found.TreeNode.IsExpanded = true; TreeView.SelectItems(new TreeNodeData[] { found }); TreeView.Focus(); @@ -240,13 +240,13 @@ public void FollowNode(TreeNodeData node, bool newTab, bool? useCodeRef) { var entityNode = node as EntityNode; var srcRef = entityNode?.SourceRef; - bool code = useCodeRef ?? !(srcRef is null); + bool code = useCodeRef ?? srcRef is not null; if (code) { if (srcRef is null) return; - if (!(srcRef.Value.ILOffset is null)) { + if (srcRef.Value.ILOffset is not null) { documentTabService.FollowReference(srcRef.Value.Method, newTab, true, a => { - if (!a.HasMovedCaret && a.Success && !(srcRef is null)) + if (!a.HasMovedCaret && a.Success && srcRef is not null) a.HasMovedCaret = GoTo(a.Tab, srcRef.Value.Method, srcRef.Value.ILOffset, srcRef.Value.Reference); }); } @@ -268,8 +268,8 @@ public bool CanFollowNode(TreeNodeData node, bool useCodeRef) { var srcRef = entityNode?.SourceRef; if (useCodeRef) - return !(srcRef is null); - return !(@ref is null); + return srcRef is not null; + return @ref is not null; } bool GoTo(IDocumentTab tab, MethodDef method, uint? ilOffset, object? @ref) { @@ -354,7 +354,7 @@ static bool RefEquals(object? a, object? b) { if (new SigComparer(flags).Equals(prop, b as PropertyDef)) return true; var bm = b as IMethod; - return !(bm is null) && + return bm is not null && (new SigComparer(flags).Equals(prop.GetMethod, bm) || new SigComparer(flags).Equals(prop.SetMethod, bm)); } @@ -363,7 +363,7 @@ static bool RefEquals(object? a, object? b) { if (new SigComparer(flags).Equals(evt, b as EventDef)) return true; var bm = b as IMethod; - return !(bm is null) && + return bm is not null && (new SigComparer(flags).Equals(evt.AddMethod, bm) || new SigComparer(flags).Equals(evt.InvokeMethod, bm) || new SigComparer(flags).Equals(evt.RemoveMethod, bm)); diff --git a/Extensions/dnSpy.Analyzer/Commands.cs b/Extensions/dnSpy.Analyzer/Commands.cs index bd120da838..2e78ee98ff 100644 --- a/Extensions/dnSpy.Analyzer/Commands.cs +++ b/Extensions/dnSpy.Analyzer/Commands.cs @@ -49,7 +49,7 @@ public override void Execute(IMenuItemContext context) { analyzerService.Value.FollowNode(@ref, newTab, useCodeRef); } - public override bool IsVisible(IMenuItemContext context) => !(GetReference(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetReference(context) is not null; TreeNodeData? GetReference(IMenuItemContext context) { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_ANALYZER_TREEVIEW_GUID)) @@ -59,7 +59,7 @@ public override void Execute(IMenuItemContext context) { if (nodes is null || nodes.Length != 1) return null; - if (nodes[0] is IMDTokenNode tokenNode && !(tokenNode.Reference is null)) { + if (nodes[0] is IMDTokenNode tokenNode && tokenNode.Reference is not null) { if (!analyzerService.Value.CanFollowNode(nodes[0], useCodeRef)) return null; return nodes[0]; diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/AttributeAppliedToNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/AttributeAppliedToNode.cs index 55260841fc..6023c202ff 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/AttributeAppliedToNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/AttributeAppliedToNode.cs @@ -39,7 +39,7 @@ sealed class AttributeAppliedToNode : SearchNode { public static bool CanShow(TypeDef type) => type.IsClass && IsCustomAttribute(type); static bool IsCustomAttribute(TypeDef type) { - while (!(type is null)) { + while (type is not null) { var bt = type.BaseType.ResolveTypeDef(); if (bt is null) return false; @@ -55,7 +55,7 @@ public AttributeAppliedToNode(TypeDef analyzedType) { analyzedTypes = new List { analyzedType }; includeAllModules = CustomAttributesUtils.IsPseudoCustomAttributeType(analyzedType); var ca = analyzedType.CustomAttributes.Find("System.AttributeUsageAttribute"); - if (!(ca is null) && ca.ConstructorArguments.Count == 1 && ca.ConstructorArguments[0].Value is int) + if (ca is not null && ca.ConstructorArguments.Count == 1 && ca.ConstructorArguments[0].Value is int) usage = (AttributeTargets)ca.ConstructorArguments[0].Value; else usage = AttributeTargets.All; @@ -104,7 +104,7 @@ IEnumerable FindReferencesInModule(IEnumerable foreach (var module in modules) { if ((usage & AttributeTargets.Assembly) != 0) { AssemblyDef asm = module.Assembly; - if (!(asm is null) && checkedAsms.Add(asm)) { + if (asm is not null && checkedAsms.Add(asm)) { foreach (var attribute in asm.GetCustomAttributes()) { if (new SigComparer().Equals(attribute.AttributeType?.GetScopeType(), trScopeType)) { yield return new AssemblyNode(asm) { Context = Context }; @@ -267,10 +267,10 @@ IEnumerable FindReferencesWithinInType(TypeDef type, IType var modules = Context.DocumentService.GetDocuments().Where(a => SearchNode.CanIncludeModule(mod, a.ModuleDef)); foreach (var module in modules) { - Debug2.Assert(!(module.ModuleDef is null)); + Debug2.Assert(module.ModuleDef is not null); ct.ThrowIfCancellationRequested(); var typeref = GetScopeTypeRefInModule(module.ModuleDef); - if (!(typeref is null)) + if (typeref is not null) yield return (module.ModuleDef, typeref); } } @@ -288,11 +288,11 @@ IEnumerable FindReferencesWithinInType(TypeDef type, IType var friendAssemblies = GetFriendAssemblies(Context.DocumentService, mod, out var modules); if (friendAssemblies.Count > 0) { foreach (var module in modules) { - Debug2.Assert(!(module.ModuleDef is null)); + Debug2.Assert(module.ModuleDef is not null); ct.ThrowIfCancellationRequested(); if (module.AssemblyDef is null || friendAssemblies.Contains(module.AssemblyDef.Name)) { var typeref = GetScopeTypeRefInModule(module.ModuleDef); - if (!(typeref is null)) + if (typeref is not null) yield return (module.ModuleDef, typeref); } } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/Commands.cs b/Extensions/dnSpy.Analyzer/TreeNodes/Commands.cs index 88d4f09380..0b7dce0a3f 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/Commands.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/Commands.cs @@ -133,7 +133,7 @@ sealed class FilesCommand : MenuItemBase { if (nodes is null) yield break; - if (checkRoot && nodes.All(a => !(a.TreeNode.Parent is null) && a.TreeNode.Parent.Parent is null)) + if (checkRoot && nodes.All(a => a.TreeNode.Parent is not null && a.TreeNode.Parent.Parent is null)) yield break; foreach (var node in nodes) { @@ -188,7 +188,7 @@ internal static IEnumerable GetMemberRefs(IMenuItemContext context, yield break; var @ref = context.Find(); - if (!(@ref is null)) { + if (@ref is not null) { if (@ref.Reference is IMemberRef mr) yield return mr; } @@ -251,13 +251,13 @@ public static void Analyze(IDsToolWindowService toolWindowService, Lazy DeleteNodes(), (s, e) => e.CanExecute = CanDeleteNodes, ModifierKeys.None, Key.Delete); } - bool CanDeleteNodes => !(GetNodes() is null); + bool CanDeleteNodes => GetNodes() is not null; void DeleteNodes() => DeleteNodes(GetNodes()); TreeNodeData[]? GetNodes() => GetNodes(analyzerService.Value.TreeView.TopLevelSelection); internal static TreeNodeData[]? GetNodes(TreeNodeData[] nodes) { if (nodes is null) return null; - if (nodes.Length == 0 || !nodes.All(a => !(a.TreeNode.Parent is null) && a.TreeNode.Parent.Parent is null)) + if (nodes.Length == 0 || !nodes.All(a => a.TreeNode.Parent is not null && a.TreeNode.Parent.Parent is null)) return null; return nodes; } internal static void DeleteNodes(TreeNodeData[]? nodes) { - if (!(nodes is null)) { + if (nodes is not null) { foreach (var node in nodes) { AnalyzerTreeNodeData.CancelSelfAndChildren(node); node.TreeNode.Parent!.Children.Remove(node.TreeNode); @@ -313,7 +313,7 @@ internal static void DeleteNodes(TreeNodeData[]? nodes) { [ExportMenuItem(Header = "res:RemoveCommand", Icon = DsImagesAttribute.Cancel, InputGestureText = "res:ShortCutKeyDelete", Group = MenuConstants.GROUP_CTX_ANALYZER_OTHER, Order = 10)] sealed class RemoveAnalyzeCtxMenuCommand : MenuItemBase { - public override bool IsVisible(IMenuItemContext context) => !(GetNodes(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetNodes(context) is not null; static TreeNodeData[]? GetNodes(IMenuItemContext context) { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_ANALYZER_TREEVIEW_GUID)) diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/EventAccessorNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/EventAccessorNode.cs index c204a50c5f..b580111fcf 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/EventAccessorNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/EventAccessorNode.cs @@ -28,7 +28,7 @@ public EventAccessorNode(MethodDef analyzedMethod, string? name) : base(analyzedMethod) => this.name = name; protected override void Write(ITextColorWriter output, IDecompiler decompiler) { - if (!(name is null)) + if (name is not null) output.Write(BoxedTextColor.Keyword, name); else base.Write(output, decompiler); diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/EventFiredByNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/EventFiredByNode.cs index f16a721bd9..4c44373c5b 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/EventFiredByNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/EventFiredByNode.cs @@ -42,7 +42,7 @@ public EventFiredByNode(EventDef analyzedEvent) { eventBackingField = GetBackingField(analyzedEvent); var eventType = analyzedEvent.EventType.ResolveTypeDef(); - if (!(eventType is null)) + if (eventType is not null) eventFiringMethod = eventType.Methods.First(md => md.Name == "Invoke"); } @@ -79,14 +79,14 @@ IEnumerable FindReferencesInType(TypeDef type) { } } if (readBackingField && (code == Code.Callvirt || code == Code.Call)) { - if (instr.Operand is IMethod mr && !(eventFiringMethod is null) && mr.Name == eventFiringMethod.Name && CheckEquals(mr.ResolveMethodDef(), eventFiringMethod)) { + if (instr.Operand is IMethod mr && eventFiringMethod is not null && mr.Name == eventFiringMethod.Name && CheckEquals(mr.ResolveMethodDef(), eventFiringMethod)) { foundInstr = instr; break; } } } - if (!(foundInstr is null)) { + if (foundInstr is not null) { if (GetOriginalCodeLocation(method) is MethodDef codeLocation && !HasAlreadyBeenFound(codeLocation)) { var node = new MethodNode(codeLocation) { Context = Context }; if (codeLocation == method) @@ -117,6 +117,6 @@ IEnumerable FindReferencesInType(TypeDef type) { } - public static bool CanShow(EventDef ev) => !(GetBackingField(ev) is null); + public static bool CanShow(EventDef ev) => GetBackingField(ev) is not null; } } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/EventNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/EventNode.cs index a483d8bbe4..f366a0fdfc 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/EventNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/EventNode.cs @@ -54,13 +54,13 @@ protected override void Write(ITextColorWriter output, IDecompiler decompiler) { } public override IEnumerable CreateChildren() { - if (!(analyzedEvent.AddMethod is null)) + if (analyzedEvent.AddMethod is not null) yield return new EventAccessorNode(analyzedEvent.AddMethod, "add"); - if (!(analyzedEvent.RemoveMethod is null)) + if (analyzedEvent.RemoveMethod is not null) yield return new EventAccessorNode(analyzedEvent.RemoveMethod, "remove"); - if (!(analyzedEvent.InvokeMethod is null)) + if (analyzedEvent.InvokeMethod is not null) yield return new EventAccessorNode(analyzedEvent.InvokeMethod, "raise"); foreach (var accessor in analyzedEvent.OtherMethods) diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/EventOverriddenNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/EventOverriddenNode.cs index e41f03fb7b..add3e73544 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/EventOverriddenNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/EventOverriddenNode.cs @@ -68,18 +68,18 @@ protected override IEnumerable FetchChildren(CancellationT } public static bool CanShow(EventDef @event) => - !((GetAccessor(@event.AddMethod) ?? GetAccessor(@event.RemoveMethod) ?? GetAccessor(@event.InvokeMethod)) is null); + (GetAccessor(@event.AddMethod) ?? GetAccessor(@event.RemoveMethod) ?? GetAccessor(@event.InvokeMethod)) is not null; static MethodDef? GetAccessor(MethodDef? accessor) { - if (!(accessor is null) && - !(accessor.DeclaringType.BaseType is null) && + if (accessor is not null && + accessor.DeclaringType.BaseType is not null && (accessor.IsVirtual || accessor.IsAbstract) && accessor.IsReuseSlot) return accessor; return null; } static MethodDef? GetVirtualAccessor(MethodDef? accessor) { - if (!(accessor is null) && (accessor.IsVirtual || accessor.IsAbstract)) + if (accessor is not null && (accessor.IsVirtual || accessor.IsAbstract)) return accessor; return null; } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/EventOverridesNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/EventOverridesNode.cs index b80fa18b82..a43fa92b9b 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/EventOverridesNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/EventOverridesNode.cs @@ -55,7 +55,7 @@ IEnumerable FindReferencesInType(TypeDef type) { public static bool CanShow(EventDef @event) { var accessor = @event.AddMethod ?? @event.RemoveMethod ?? @event.InvokeMethod; - return !(accessor is null) && accessor.IsVirtual && !accessor.IsFinal && !accessor.DeclaringType.IsInterface; + return accessor is not null && accessor.IsVirtual && !accessor.IsFinal && !accessor.DeclaringType.IsInterface; } } } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/FieldAccessNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/FieldAccessNode.cs index f54c555894..67c92b416d 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/FieldAccessNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/FieldAccessNode.cs @@ -85,7 +85,7 @@ IEnumerable FindReferencesInType(TypeDef type) { } } - if (!(foundInstr is null)) { + if (foundInstr is not null) { if (GetOriginalCodeLocation(method) is MethodDef codeLocation && !HasAlreadyBeenFound(codeLocation)) { var node = new MethodNode(codeLocation) { Context = Context }; if (codeLocation == method) diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/Helpers.cs b/Extensions/dnSpy.Analyzer/TreeNodes/Helpers.cs index 7af9bffcc7..2a00b5f14b 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/Helpers.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/Helpers.cs @@ -46,7 +46,7 @@ static MethodDef GetOriginalCodeLocation(MethodDef method) { /// Used to detect the 'parent method' for a lambda/iterator/async state machine. /// static MethodDef? GetOriginalCodeLocation(TypeDef type) { - if (!(type is null) && !(type.DeclaringType is null) && IsCompilerGenerated(type)) { + if (type is not null && type.DeclaringType is not null && IsCompilerGenerated(type)) { if (type.IsValueType) { // Value types might not have any constructor; but they must be stored in a local var // because 'initobj' (or 'call .ctor') expects a managed ref. @@ -107,12 +107,12 @@ internal static bool CheckEquals(IMemberRef? mr1, IMemberRef? mr2) => } static TypeDef? ResolveWithinSameModule(ITypeDefOrRef type) { - if (!(type is null) && type.Scope == type.Module) + if (type is not null && type.Scope == type.Module) return type.ResolveTypeDef(); return null; } static bool IsCompilerGenerated(this IHasCustomAttribute hca) => - !(hca is null) && hca.CustomAttributes.IsDefined("System.Runtime.CompilerServices.CompilerGeneratedAttribute"); + hca is not null && hca.CustomAttributes.IsDefined("System.Runtime.CompilerServices.CompilerGeneratedAttribute"); } } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/InterfaceEventImplementedByNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/InterfaceEventImplementedByNode.cs index 742dbd3409..8ac48440e3 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/InterfaceEventImplementedByNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/InterfaceEventImplementedByNode.cs @@ -39,11 +39,11 @@ enum AccessorKind { public InterfaceEventImplementedByNode(EventDef analyzedEvent) { this.analyzedEvent = analyzedEvent ?? throw new ArgumentNullException(nameof(analyzedEvent)); - if (!(this.analyzedEvent.AddMethod is null)) { + if (this.analyzedEvent.AddMethod is not null) { analyzedMethod = this.analyzedEvent.AddMethod; accessorKind = AccessorKind.Adder; } - else if (!(this.analyzedEvent.RemoveMethod is null)) { + else if (this.analyzedEvent.RemoveMethod is not null) { analyzedMethod = this.analyzedEvent.RemoveMethod; accessorKind = AccessorKind.Remover; } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/InterfaceMethodImplementedByNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/InterfaceMethodImplementedByNode.cs index 1dafb04959..f255c157e8 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/InterfaceMethodImplementedByNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/InterfaceMethodImplementedByNode.cs @@ -65,7 +65,7 @@ IEnumerable FindReferencesInType(TypeDef type) { } } - if (!(comIface is null) && ComUtils.GetMethod(comIface, vtblIndex) is MethodDef comIfaceMethod) { + if (comIface is not null && ComUtils.GetMethod(comIface, vtblIndex) is MethodDef comIfaceMethod) { foreach (var method in type.Methods) { // Don't include abstract methods, they don't implement anything if (!method.IsVirtual || method.IsAbstract) @@ -77,7 +77,7 @@ IEnumerable FindReferencesInType(TypeDef type) { } } - if (!(implementedInterfaceRef is null)) { + if (implementedInterfaceRef is not null) { foreach (var method in type.Methods) { // Don't include abstract methods, they don't implement anything if (!method.IsVirtual || method.IsAbstract) diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/InterfacePropertyImplementedByNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/InterfacePropertyImplementedByNode.cs index a8ec8e873b..094896287a 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/InterfacePropertyImplementedByNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/InterfacePropertyImplementedByNode.cs @@ -33,7 +33,7 @@ sealed class InterfacePropertyImplementedByNode : SearchNode { public InterfacePropertyImplementedByNode(PropertyDef analyzedProperty) { this.analyzedProperty = analyzedProperty ?? throw new ArgumentNullException(nameof(analyzedProperty)); - if (!(this.analyzedProperty.GetMethod is null)) { + if (this.analyzedProperty.GetMethod is not null) { analyzedMethod = this.analyzedProperty.GetMethod; isGetter = true; } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/MethodOverriddenNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/MethodOverriddenNode.cs index e8dc9e0723..c833dbfc4c 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/MethodOverriddenNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/MethodOverriddenNode.cs @@ -66,7 +66,7 @@ protected override IEnumerable FetchChildren(CancellationT } public static bool CanShow(MethodDef method) => - !(method.DeclaringType.BaseType is null) && + method.DeclaringType.BaseType is not null && (method.IsVirtual || method.IsAbstract) && method.IsReuseSlot; } } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/MethodUsedByNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/MethodUsedByNode.cs index 036b3799bb..03a16ba401 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/MethodUsedByNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/MethodUsedByNode.cs @@ -81,18 +81,18 @@ protected override IEnumerable FetchChildren(CancellationT if (isSetter) property = analyzedMethod.DeclaringType.Properties.FirstOrDefault(a => a.SetMethod == analyzedMethod); - var includeAllModules = (!(property is null) && CustomAttributesUtils.IsPseudoCustomAttributeType(analyzedMethod.DeclaringType)) || !(implMapName is null); + var includeAllModules = (property is not null && CustomAttributesUtils.IsPseudoCustomAttributeType(analyzedMethod.DeclaringType)) || implMapName is not null; var options = ScopedWhereUsedAnalyzerOptions.None; if (includeAllModules) options |= ScopedWhereUsedAnalyzerOptions.IncludeAllModules; - if (!(implMapName is null)) + if (implMapName is not null) options |= ScopedWhereUsedAnalyzerOptions.ForcePublic; var analyzer = new ScopedWhereUsedAnalyzer(Context.DocumentService, analyzedMethod, FindReferencesInType, options); foreach (var child in analyzer.PerformAnalysis(ct)) { yield return child; } - if (!(property is null)) { + if (property is not null) { var hash = new HashSet(); foreach (var module in analyzer.AllModules) { if (module.Assembly is AssemblyDef asm && hash.Add(asm)) { @@ -113,7 +113,7 @@ IEnumerable FindReferencesInType(TypeDef type) { if (!method.HasBody) continue; Instruction? foundInstr = null; - if (!(implMapName is null)) { + if (implMapName is not null) { foreach (var instr in method.Body.Instructions) { if (instr.Operand is IMethod mr && !mr.IsField && mr.ResolveMethodDef() is MethodDef md && @@ -137,7 +137,7 @@ IEnumerable FindReferencesInType(TypeDef type) { } } - if (!(foundInstr is null)) { + if (foundInstr is not null) { if (GetOriginalCodeLocation(method) is MethodDef codeLocation && !HasAlreadyBeenFound(codeLocation)) { var node = new MethodNode(codeLocation) { Context = Context }; if (codeLocation == method) @@ -147,7 +147,7 @@ IEnumerable FindReferencesInType(TypeDef type) { } } - if (!(property is null)) { + if (property is not null) { foreach (var node in FieldAccessNode.CheckCustomAttributeNamedArgumentWrite(Context, type, property)) { if (node is MethodNode methodNode && methodNode.Member is MethodDef method && HasAlreadyBeenFound(method)) continue; diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/MethodUsesNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/MethodUsesNode.cs index a5a16b5779..840061f300 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/MethodUsesNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/MethodUsesNode.cs @@ -60,7 +60,7 @@ IEnumerable> GetUsedMethods() { foreach (Instruction instr in analyzedMethod.Body.Instructions) { if (instr.Operand is IMethod mr && !mr.IsField) { MethodDef def = mr.ResolveMethodDef(); - if (!(def is null)) + if (def is not null) yield return new DefRef(def, new SourceRef(analyzedMethod, instr.Offset, instr.Operand as IMDTokenProvider)); } } @@ -70,7 +70,7 @@ IEnumerable> GetUsedFields() { foreach (Instruction instr in analyzedMethod.Body.Instructions) { if (instr.Operand is IField fr && !fr.IsMethod) { FieldDef def = fr.ResolveFieldDef(); - if (!(def is null)) + if (def is not null) yield return new DefRef(def, new SourceRef(analyzedMethod, instr.Offset, instr.Operand as IMDTokenProvider)); } } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/PropertyAccessorNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/PropertyAccessorNode.cs index bb8aa15fb4..5f7146669d 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/PropertyAccessorNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/PropertyAccessorNode.cs @@ -28,7 +28,7 @@ public PropertyAccessorNode(MethodDef analyzedMethod, string? name, bool isSette : base(analyzedMethod, isSetter: isSetter) => this.name = name; protected override void Write(ITextColorWriter output, IDecompiler decompiler) { - if (!(name is null)) + if (name is not null) output.Write(BoxedTextColor.Keyword, name); else base.Write(output, decompiler); diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/PropertyNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/PropertyNode.cs index f1ff8bae20..380d693210 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/PropertyNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/PropertyNode.cs @@ -56,10 +56,10 @@ protected override void Write(ITextColorWriter output, IDecompiler decompiler) { } public override IEnumerable CreateChildren() { - if (!(analyzedProperty.GetMethod is null)) + if (analyzedProperty.GetMethod is not null) yield return new PropertyAccessorNode(analyzedProperty.GetMethod, "get", isSetter: false); - if (!(analyzedProperty.SetMethod is null)) + if (analyzedProperty.SetMethod is not null) yield return new PropertyAccessorNode(analyzedProperty.SetMethod, "set", isSetter: true); foreach (var accessor in analyzedProperty.OtherMethods) diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/PropertyOverriddenNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/PropertyOverriddenNode.cs index 28c7efd518..ff1d227ddb 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/PropertyOverriddenNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/PropertyOverriddenNode.cs @@ -68,18 +68,18 @@ protected override IEnumerable FetchChildren(CancellationT } public static bool CanShow(PropertyDef property) => - !((GetAccessor(property.GetMethod) ?? GetAccessor(property.SetMethod)) is null); + (GetAccessor(property.GetMethod) ?? GetAccessor(property.SetMethod)) is not null; static MethodDef? GetAccessor(MethodDef? accessor) { - if (!(accessor is null) && - !(accessor.DeclaringType.BaseType is null) && + if (accessor is not null && + accessor.DeclaringType.BaseType is not null && (accessor.IsVirtual || accessor.IsAbstract) && accessor.IsReuseSlot) return accessor; return null; } static MethodDef? GetVirtualAccessor(MethodDef? accessor) { - if (!(accessor is null) && (accessor.IsVirtual || accessor.IsAbstract)) + if (accessor is not null && (accessor.IsVirtual || accessor.IsAbstract)) return accessor; return null; } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/PropertyOverridesNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/PropertyOverridesNode.cs index f6ad1791b5..f2593ebbd7 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/PropertyOverridesNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/PropertyOverridesNode.cs @@ -56,7 +56,7 @@ IEnumerable FindReferencesInType(TypeDef type) { public static bool CanShow(PropertyDef property) { var accessor = property.GetMethod ?? property.SetMethod; - return !(accessor is null) && accessor.IsVirtual && !accessor.IsFinal && !accessor.DeclaringType.IsInterface; + return accessor is not null && accessor.IsVirtual && !accessor.IsFinal && !accessor.DeclaringType.IsInterface; } } } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/ScopedWhereUsedAnalyzer.cs b/Extensions/dnSpy.Analyzer/TreeNodes/ScopedWhereUsedAnalyzer.cs index 8961b841fb..99ec90b5b6 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/ScopedWhereUsedAnalyzer.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/ScopedWhereUsedAnalyzer.cs @@ -297,7 +297,7 @@ IEnumerable GetReferencingModules(ModuleDef mod, CancellationToken ct var modules = documentService.GetDocuments().Where(a => SearchNode.CanIncludeModule(mod, a.ModuleDef)); foreach (var module in modules) { - Debug2.Assert(!(module.ModuleDef is null)); + Debug2.Assert(module.ModuleDef is not null); ct.ThrowIfCancellationRequested(); if (ModuleReferencesScopeType(module.ModuleDef)) yield return module.ModuleDef; @@ -316,7 +316,7 @@ IEnumerable GetModuleAndAnyFriends(ModuleDef mod, CancellationToken c var friendAssemblies = SearchNode.GetFriendAssemblies(documentService, mod, out var modules); if (friendAssemblies.Count > 0) { foreach (var module in modules) { - Debug2.Assert(!(module.ModuleDef is null)); + Debug2.Assert(module.ModuleDef is not null); ct.ThrowIfCancellationRequested(); if ((module.AssemblyDef is null || friendAssemblies.Contains(module.AssemblyDef.Name)) && ModuleReferencesScopeType(module.ModuleDef)) yield return module.ModuleDef; diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/SearchNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/SearchNode.cs index 46fe40e782..279b7a0ec5 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/SearchNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/SearchNode.cs @@ -48,14 +48,14 @@ public override IEnumerable CreateChildren() { internal IEnumerable FetchChildrenInternal(CancellationToken token) => FetchChildren(token); public override void OnIsVisibleChanged() { - if (!TreeNode.IsVisible && !(asyncFetchChildrenHelper is null) && !asyncFetchChildrenHelper.CompletedSuccessfully) { + if (!TreeNode.IsVisible && asyncFetchChildrenHelper is not null && !asyncFetchChildrenHelper.CompletedSuccessfully) { CancelAndClearChildren(); TreeNode.LazyLoading = true; } } public override void OnIsExpandedChanged(bool isExpanded) { - if (!isExpanded && !(asyncFetchChildrenHelper is null) && !asyncFetchChildrenHelper.CompletedSuccessfully) { + if (!isExpanded && asyncFetchChildrenHelper is not null && !asyncFetchChildrenHelper.CompletedSuccessfully) { CancelAndClearChildren(); TreeNode.LazyLoading = true; } @@ -95,14 +95,14 @@ internal static bool CanIncludeModule(ModuleDef targetModule, ModuleDef? module) return false; if (targetModule == module) return false; - if (!(targetModule.Assembly is null) && targetModule.Assembly == module.Assembly) + if (targetModule.Assembly is not null && targetModule.Assembly == module.Assembly) return false; return true; } internal static HashSet GetFriendAssemblies(IDsDocumentService documentService, ModuleDef mod, out IDsDocument[] modules) { var asm = mod.Assembly; - Debug2.Assert(!(asm is null)); + Debug2.Assert(asm is not null); var friendAssemblies = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var attribute in asm.CustomAttributes.FindAll("System.Runtime.CompilerServices.InternalsVisibleToAttribute")) { if (attribute.ConstructorArguments.Count == 0) @@ -115,7 +115,7 @@ internal static HashSet GetFriendAssemblies(IDsDocumentService documentS } modules = documentService.GetDocuments().Where(a => CanIncludeModule(mod, a.ModuleDef)).ToArray(); foreach (var module in modules) { - Debug2.Assert(!(module.ModuleDef is null)); + Debug2.Assert(module.ModuleDef is not null); var asm2 = module.AssemblyDef; if (asm2 is null) continue; @@ -135,7 +135,7 @@ internal static void AddTypeEquivalentTypes(IDsDocumentService documentService, Debug.Assert(analyzedTypes.Count == 1 && analyzedTypes[0] == analyzedType); if (!TIAHelper.IsTypeDefEquivalent(analyzedType)) return; - foreach (var document in documentService.GetDocuments().Where(a => !(a.ModuleDef is null))) { + foreach (var document in documentService.GetDocuments().Where(a => a.ModuleDef is not null)) { foreach (var type in GetTypeEquivalentTypes(document.AssemblyDef, document.ModuleDef, analyzedType)) { if (type != analyzedType) analyzedTypes.Add(type); @@ -157,12 +157,12 @@ static IEnumerable GetTypeEquivalentTypes(AssemblyDef? assembly, Module } static IEnumerable GetModules(AssemblyDef? assembly, ModuleDef? module) { - if (!(assembly is null)) { + if (assembly is not null) { foreach (var mod in assembly.Modules) yield return mod; } else { - if (!(module is null)) + if (module is not null) yield return module; } } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/TypeExposedByNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/TypeExposedByNode.cs index 7331a9c23b..57059184e2 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/TypeExposedByNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/TypeExposedByNode.cs @@ -186,7 +186,7 @@ bool TypeIsExposedBy(MethodDef method) { return false; var methDecl = method.Overrides[0].MethodDeclaration; var typeDef = methDecl?.DeclaringType?.ResolveTypeDef(); - if (!(typeDef is null) && !typeDef.IsInterface) + if (typeDef is not null && !typeDef.IsInterface) return false; } @@ -216,15 +216,15 @@ bool TypeIsExposedBy(MethodBaseSig? methodSig, int recursionCounter) { } static bool IsPrivate(PropertyDef property) { - bool isGetterPublic = (!(property.GetMethod is null) && !property.GetMethod.IsPrivate); - bool isSetterPublic = (!(property.SetMethod is null) && !property.SetMethod.IsPrivate); + bool isGetterPublic = (property.GetMethod is not null && !property.GetMethod.IsPrivate); + bool isSetterPublic = (property.SetMethod is not null && !property.SetMethod.IsPrivate); return !(isGetterPublic || isSetterPublic); } static bool IsPrivate(EventDef eventDef) { - bool isAdderPublic = (!(eventDef.AddMethod is null) && !eventDef.AddMethod.IsPrivate); - bool isRemoverPublic = (!(eventDef.RemoveMethod is null) && !eventDef.RemoveMethod.IsPrivate); - bool isInvokerPublic = (!(eventDef.InvokeMethod is null) && !eventDef.InvokeMethod.IsPrivate); + bool isAdderPublic = (eventDef.AddMethod is not null && !eventDef.AddMethod.IsPrivate); + bool isRemoverPublic = (eventDef.RemoveMethod is not null && !eventDef.RemoveMethod.IsPrivate); + bool isInvokerPublic = (eventDef.InvokeMethod is not null && !eventDef.InvokeMethod.IsPrivate); return !(isAdderPublic || isRemoverPublic || isInvokerPublic); } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/TypeExtensionMethodsNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/TypeExtensionMethodsNode.cs index aabf7ff71d..0778945009 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/TypeExtensionMethodsNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/TypeExtensionMethodsNode.cs @@ -73,7 +73,7 @@ static int GetParametersSkip(IList parameters) { return 0; } - bool HasExtensionAttribute(IHasCustomAttribute p) => !(p.CustomAttributes.Find("System.Runtime.CompilerServices.ExtensionAttribute") is null); + bool HasExtensionAttribute(IHasCustomAttribute p) => p.CustomAttributes.Find("System.Runtime.CompilerServices.ExtensionAttribute") is not null; // show on all types except static classes public static bool CanShow(TypeDef type) => !(type.IsAbstract && type.IsSealed); diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/TypeInstantiationsNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/TypeInstantiationsNode.cs index 27a6cbe9f2..f43fb2b8ae 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/TypeInstantiationsNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/TypeInstantiationsNode.cs @@ -64,7 +64,7 @@ IEnumerable FindReferencesInType(TypeDef type) { } } - if (!(foundInstr is null)) + if (foundInstr is not null) yield return new MethodNode(method) { Context = Context, SourceRef = new SourceRef(method, foundInstr.Offset, foundInstr.Operand as IMDTokenProvider) }; } } diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/TypeUsedByNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/TypeUsedByNode.cs index 881b696920..4bb5b0ce61 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/TypeUsedByNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/TypeUsedByNode.cs @@ -90,7 +90,7 @@ IEnumerable FindTypeUsage(TypeDef? type) { if (new SigComparer().Equals(type, analyzedType)) yield break; if (isComType && ComUtils.ComEquals(type, ref comGuid)) { - Debug2.Assert(!(allTypes is null)); + Debug2.Assert(allTypes is not null); lock (allTypes) allTypes.Add(type); yield break; @@ -121,11 +121,11 @@ IEnumerable FindTypeUsage(TypeDef? type) { EntityNode HandleSpecialMethodNode(MethodDef method, SourceRef? sourceRef) { var property = method.DeclaringType.Properties.FirstOrDefault(p => (object?)p.GetMethod == method || (object?)p.SetMethod == method); - if (!(property is null)) + if (property is not null) return new PropertyNode(property) { Context = Context, SourceRef = sourceRef }; var @event = method.DeclaringType.Events.FirstOrDefault(p => (object?)p.AddMethod == method || (object?)p.RemoveMethod == method || (object?)p.InvokeMethod == method); - if (!(@event is null)) + if (@event is not null) return new EventNode(@event) { Context = Context, SourceRef = sourceRef }; return new MethodNode(method) { Context = Context, SourceRef = sourceRef }; @@ -284,7 +284,7 @@ bool TypeMatches(IType? tref, int level) { return false; if (isComType && tref.Resolve() is TypeDef td && ComUtils.ComEquals(td, ref comGuid)) return true; - if (!(tref is null)) { + if (tref is not null) { if (new SigComparer().Equals(analyzedType, tref.GetScopeType())) return true; if (tref is TypeSig ts) { @@ -301,7 +301,7 @@ bool TypeMatches(IType? tref, int level) { if (TypeMatches(p, level + 1)) return true; } - if (!(msig.ParamsAfterSentinel is null)) { + if (msig.ParamsAfterSentinel is not null) { foreach (var p in msig.ParamsAfterSentinel) { if (TypeMatches(p, level + 1)) return true; @@ -349,7 +349,7 @@ bool TypeMatches(IType? tref, int level) { return false; } - public static bool CanShow(TypeDef? type) => !(type is null); + public static bool CanShow(TypeDef? type) => type is not null; } sealed class AnalyzerEntityTreeNodeComparer : IEqualityComparer { diff --git a/Extensions/dnSpy.Analyzer/TreeNodes/VirtualMethodUsedByNode.cs b/Extensions/dnSpy.Analyzer/TreeNodes/VirtualMethodUsedByNode.cs index 1107e92a86..e3ff623747 100644 --- a/Extensions/dnSpy.Analyzer/TreeNodes/VirtualMethodUsedByNode.cs +++ b/Extensions/dnSpy.Analyzer/TreeNodes/VirtualMethodUsedByNode.cs @@ -52,7 +52,7 @@ protected override IEnumerable FetchChildren(CancellationT if (isSetter) property = analyzedMethod.DeclaringType.Properties.FirstOrDefault(a => a.SetMethod == analyzedMethod); - var includeAllModules = !(property is null) && CustomAttributesUtils.IsPseudoCustomAttributeType(analyzedMethod.DeclaringType); + var includeAllModules = property is not null && CustomAttributesUtils.IsPseudoCustomAttributeType(analyzedMethod.DeclaringType); ComUtils.GetMemberInfo(analyzedMethod, out isComType, out comGuid, out vtblIndex); includeAllModules |= isComType; var options = ScopedWhereUsedAnalyzerOptions.None; @@ -65,7 +65,7 @@ protected override IEnumerable FetchChildren(CancellationT yield return child; } - if (!(property is null)) { + if (property is not null) { var hash = new HashSet(); foreach (var module in analyzer.AllModules) { if (module.Assembly is AssemblyDef asm && hash.Add(module.Assembly)) { @@ -109,7 +109,7 @@ IEnumerable FindReferencesInType(TypeDef type) { if (isComType) { md ??= mr.ResolveMethodDef(); - if (!(md is null)) { + if (md is not null) { ComUtils.GetMemberInfo(md, out bool otherIsComType, out var otherComGuid, out int otherVtblIndex); if (otherIsComType && comGuid == otherComGuid && vtblIndex == otherVtblIndex) { foundInstr = instr; @@ -140,7 +140,7 @@ IEnumerable FindReferencesInType(TypeDef type) { } } - if (!(foundInstr is null)) { + if (foundInstr is not null) { if (GetOriginalCodeLocation(method) is MethodDef codeLocation && !HasAlreadyBeenFound(codeLocation)) { var node = new MethodNode(codeLocation) { Context = Context }; if (codeLocation == method) @@ -150,7 +150,7 @@ IEnumerable FindReferencesInType(TypeDef type) { } } - if (!(property is null)) { + if (property is not null) { foreach (var node in FieldAccessNode.CheckCustomAttributeNamedArgumentWrite(Context, type, property)) { if (node is MethodNode methodNode && methodNode.Member is MethodDef method && HasAlreadyBeenFound(method)) continue; diff --git a/Extensions/dnSpy.Analyzer/TreeTraversal.cs b/Extensions/dnSpy.Analyzer/TreeTraversal.cs index b9d1ef238c..ea8bf0748a 100644 --- a/Extensions/dnSpy.Analyzer/TreeTraversal.cs +++ b/Extensions/dnSpy.Analyzer/TreeTraversal.cs @@ -47,7 +47,7 @@ public static IEnumerable PreOrder(IEnumerable input, Func children = recursion(element); - if (!(children is null)) { + if (children is not null) { stack.Push(children.GetEnumerator()); } } @@ -83,7 +83,7 @@ public static IEnumerable PostOrder(IEnumerable input, Func children = recursion(element); - if (!(children is null)) { + if (children is not null) { stack.Push(children.GetEnumerator()); } else { diff --git a/Extensions/dnSpy.AsmEditor/Assembly/AssemblyCommands.cs b/Extensions/dnSpy.AsmEditor/Assembly/AssemblyCommands.cs index 5ed73d3701..811e37ada0 100644 --- a/Extensions/dnSpy.AsmEditor/Assembly/AssemblyCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Assembly/AssemblyCommands.cs @@ -52,7 +52,7 @@ sealed class CommandLoader : IAutoLoaded { sealed class DisableMemoryMappedIOCommand : MenuItemBase { public override bool IsVisible(IMenuItemContext context) => context.CreatorObject.Guid == new Guid(MenuConstants.GUIDOBJ_DOCUMENTS_TREEVIEW_GUID) && - (context.Find() ?? Array.Empty()).Any(a => !(GetDocument(a) is null)); + (context.Find() ?? Array.Empty()).Any(a => GetDocument(a) is not null); static IDsDocument? GetDocument(TreeNodeData node) { var fileNode = node as DsDocumentNode; @@ -72,7 +72,7 @@ public override void Execute(IMenuItemContext context) { var asms = new List(); foreach (var node in (context.Find() ?? Array.Empty())) { var file = GetDocument(node); - if (!(file is null)) + if (file is not null) asms.Add(file); } foreach (var asm in asms) @@ -276,7 +276,7 @@ internal sealed class EditMenuCommand : EditMenuHandler { } static bool CanExecute(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && nodes.Length == 1 && nodes[0] is AssemblyDocumentNode; @@ -327,7 +327,7 @@ public AssemblyRefInfo(AssemblyRef asmRef) { public void Execute() { newOptions.CopyTo(asmNode.Document.AssemblyDef!); - if (!(assemblyRefInfos is null)) { + if (assemblyRefInfos is not null) { var pkt = newOptions.PublicKey.Token; foreach (var info in assemblyRefInfos) { info.AssemblyRef.Name = newOptions.Name; @@ -343,7 +343,7 @@ public void Execute() { public void Undo() { origOptions.CopyTo(asmNode.Document.AssemblyDef!); - if (!(assemblyRefInfos is null)) { + if (assemblyRefInfos is not null) { foreach (var info in assemblyRefInfos) { info.AssemblyRef.Name = info.OrigName; info.AssemblyRef.PublicKeyOrToken = info.OrigPublicKeyOrToken; @@ -392,7 +392,7 @@ sealed class EditMenuCommand : EditMenuHandler { } static bool CanExecute(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && (nodes.Length == 0 || nodes[0] is DsDocumentNode); static void Execute(Lazy undoCommandService, IAppService appService, DocumentTreeNodeData[] nodes) { diff --git a/Extensions/dnSpy.AsmEditor/Commands/CloseAllMissingFilesCommand.cs b/Extensions/dnSpy.AsmEditor/Commands/CloseAllMissingFilesCommand.cs index e5b58e40af..95f519e4db 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/CloseAllMissingFilesCommand.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/CloseAllMissingFilesCommand.cs @@ -47,10 +47,10 @@ sealed class CloseAllMissingFilesCommand : MenuItemBase { return nodes.Length == 0 ? null : nodes; } - public override bool IsEnabled(IMenuItemContext context) => !(GetNodes() is null); + public override bool IsEnabled(IMenuItemContext context) => GetNodes() is not null; public override void Execute(IMenuItemContext context) { var nodes = GetNodes(); - if (!(nodes is null)) + if (nodes is not null) RemoveAssemblyCommand.Execute(undoCommandService, documentSaver, appService, nodes); } } diff --git a/Extensions/dnSpy.AsmEditor/Commands/CloseOldInMemoryModulesCommand.cs b/Extensions/dnSpy.AsmEditor/Commands/CloseOldInMemoryModulesCommand.cs index 7782bce943..a789345c8e 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/CloseOldInMemoryModulesCommand.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/CloseOldInMemoryModulesCommand.cs @@ -54,10 +54,10 @@ sealed class CloseOldInMemoryModulesCommand : MenuItemBase { return nodes.Count == 0 ? null : nodes.ToArray(); } - public override bool IsEnabled(IMenuItemContext context) => !(GetNodes() is null); + public override bool IsEnabled(IMenuItemContext context) => GetNodes() is not null; public override void Execute(IMenuItemContext context) { var nodes = GetNodes(); - if (!(nodes is null)) + if (nodes is not null) RemoveAssemblyCommand.Execute(undoCommandService, documentSaver, appService, nodes); } } diff --git a/Extensions/dnSpy.AsmEditor/Commands/CodeContextMenuHandlerCommandProxy.cs b/Extensions/dnSpy.AsmEditor/Commands/CodeContextMenuHandlerCommandProxy.cs index 62b014abe6..ae8a9d7237 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/CodeContextMenuHandlerCommandProxy.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/CodeContextMenuHandlerCommandProxy.cs @@ -56,13 +56,13 @@ event EventHandler? ICommand.CanExecuteChanged { bool ICommand.CanExecute(object? parameter) { var ctx = CreateContext(); - return !(ctx is null) && command.IsVisible(ctx) && command.IsEnabled(ctx); + return ctx is not null && command.IsVisible(ctx) && command.IsEnabled(ctx); } void ICommand.Execute(object? parameter) { var ctx = CreateContext(); - Debug2.Assert(!(ctx is null)); - if (!(ctx is null)) + Debug2.Assert(ctx is not null); + if (ctx is not null) command.Execute(ctx); } } diff --git a/Extensions/dnSpy.AsmEditor/Commands/CommandUtils.cs b/Extensions/dnSpy.AsmEditor/Commands/CommandUtils.cs index e91d7e6ec2..1f995081e4 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/CommandUtils.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/CommandUtils.cs @@ -38,11 +38,11 @@ public static void AddRemoveCommand(this IWpfCommandService wpfCommandService, C } public static void AddSettingsCommand(this IWpfCommandService wpfCommandService, IDocumentTabService documentTabService, EditMenuHandler? treeViewCmd, CodeContextMenuHandler? textEditorCmd) { - if (!(treeViewCmd is null)) { + if (treeViewCmd is not null) { var cmds = wpfCommandService.GetCommands(ControlConstants.GUID_DOCUMENT_TREEVIEW); cmds.Add(SettingsRoutedCommand, new EditMenuHandlerCommandProxy(treeViewCmd)); } - if (!(textEditorCmd is null)) { + if (textEditorCmd is not null) { var cmds = wpfCommandService.GetCommands(ControlConstants.GUID_DOCUMENTVIEWER_UICONTEXT); cmds.Add(SettingsRoutedCommand, new CodeContextMenuHandlerCommandProxy(textEditorCmd, documentTabService), ModifierKeys.Alt, Key.Enter); } diff --git a/Extensions/dnSpy.AsmEditor/Commands/DeletableNodes.cs b/Extensions/dnSpy.AsmEditor/Commands/DeletableNodes.cs index 27127f85c3..c0b18b44ec 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/DeletableNodes.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/DeletableNodes.cs @@ -47,7 +47,7 @@ public DeletableNodes(IEnumerable nodes) { /// public void Delete() { Debug2.Assert(parents is null); - if (!(parents is null)) + if (parents is not null) throw new ArgumentException("Nodes have already been deleted"); parents = new DocumentTreeNodeData[nodes.Length]; @@ -65,7 +65,7 @@ public void Delete() { /// The model (dnlib) elements must be restored before this method is called, not after. /// public void Restore() { - Debug2.Assert(!(parents is null)); + Debug2.Assert(parents is not null); if (parents is null) throw new ArgumentException("Nodes have already been restored"); diff --git a/Extensions/dnSpy.AsmEditor/Commands/DeletedTypeUpdater.cs b/Extensions/dnSpy.AsmEditor/Commands/DeletedTypeUpdater.cs index 12bc332fac..d82d56d074 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/DeletedTypeUpdater.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/DeletedTypeUpdater.cs @@ -50,7 +50,7 @@ public DeletedTypeUpdater(ModuleDocumentNode modNode, TypeDef originalType) { public void Add() { if (!parentNode.TreeNode.Children.Remove(ownerNode.TreeNode)) throw new InvalidOperationException(); - if (!(ownerType is null)) { + if (ownerType is not null) { typeIndex = ownerType.NestedTypes.IndexOf(type); ownerType.NestedTypes.RemoveAt(typeIndex); } @@ -61,7 +61,7 @@ public void Add() { } public void Remove() { - if (!(ownerType is null)) + if (ownerType is not null) ownerType.NestedTypes.Insert(typeIndex, type); else ownerModule.Types.Insert(typeIndex, type); diff --git a/Extensions/dnSpy.AsmEditor/Commands/DocumentsContextMenuHandler.cs b/Extensions/dnSpy.AsmEditor/Commands/DocumentsContextMenuHandler.cs index 481c4cc6dc..63a31762de 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/DocumentsContextMenuHandler.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/DocumentsContextMenuHandler.cs @@ -33,7 +33,7 @@ abstract class DocumentsContextMenuHandler : MenuItemBase { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTS_TREEVIEW_GUID)) return null; var ary = context.Find(); - Debug2.Assert(!(ary is null)); + Debug2.Assert(ary is not null); return new AsmEditorContext(ary is null ? Array.Empty() : ary.OfType().ToArray()); } } diff --git a/Extensions/dnSpy.AsmEditor/Commands/EditMenuHandlerCommandProxy.cs b/Extensions/dnSpy.AsmEditor/Commands/EditMenuHandlerCommandProxy.cs index e34e06a4cc..a98c18d644 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/EditMenuHandlerCommandProxy.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/EditMenuHandlerCommandProxy.cs @@ -36,13 +36,13 @@ event EventHandler? ICommand.CanExecuteChanged { bool ICommand.CanExecute(object? parameter) { var ctx = CreateContext(); - return !(ctx is null) && command.IsVisible(ctx) && command.IsEnabled(ctx); + return ctx is not null && command.IsVisible(ctx) && command.IsEnabled(ctx); } void ICommand.Execute(object? parameter) { var ctx = CreateContext(); - Debug2.Assert(!(ctx is null)); - if (!(ctx is null)) + Debug2.Assert(ctx is not null); + if (ctx is not null) command.Execute(ctx); } } diff --git a/Extensions/dnSpy.AsmEditor/Commands/EventNodeCreator.cs b/Extensions/dnSpy.AsmEditor/Commands/EventNodeCreator.cs index b7ff79b7e2..2193a4a1d2 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/EventNodeCreator.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/EventNodeCreator.cs @@ -38,11 +38,11 @@ public EventNodeCreator(ModuleDocumentNode modNode, TypeNode ownerNode, EventDef } IEnumerable GetMethods() { - if (!(eventNode.EventDef.AddMethod is null)) + if (eventNode.EventDef.AddMethod is not null) yield return eventNode.EventDef.AddMethod; - if (!(eventNode.EventDef.RemoveMethod is null)) + if (eventNode.EventDef.RemoveMethod is not null) yield return eventNode.EventDef.RemoveMethod; - if (!(eventNode.EventDef.InvokeMethod is null)) + if (eventNode.EventDef.InvokeMethod is not null) yield return eventNode.EventDef.InvokeMethod; foreach (var m in eventNode.EventDef.OtherMethods) yield return m; diff --git a/Extensions/dnSpy.AsmEditor/Commands/IndexObservableCollection.cs b/Extensions/dnSpy.AsmEditor/Commands/IndexObservableCollection.cs index 6754edbf95..44b4621234 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/IndexObservableCollection.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/IndexObservableCollection.cs @@ -35,7 +35,7 @@ class IndexObservableCollection : ObservableCollection where T : class, II public ICommand RemoveAllItemsCommand => new RelayCommand(a => RemoveAllItems((T[])a!), a => RemoveAllItemsCanExecute((T[])a!)); public bool DisableAutoUpdateProps { get; set; } public Action? UpdateIndexesDelegate { get; set; } - public bool CanCreateNewItems => !(createNewItem is null); + public bool CanCreateNewItems => createNewItem is not null; public bool CanRemoveItems => true; public bool CanMoveItems => true; @@ -91,7 +91,7 @@ protected override void RemoveItem(int index) { } public void UpdateIndexes(int index) { - if (!(UpdateIndexesDelegate is null)) + if (UpdateIndexesDelegate is not null) UpdateIndexesDelegate(index); else DefaultUpdateIndexes(index); diff --git a/Extensions/dnSpy.AsmEditor/Commands/InstructionCommands.cs b/Extensions/dnSpy.AsmEditor/Commands/InstructionCommands.cs index 370b3b2f7c..5c4d9f7c38 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/InstructionCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/InstructionCommands.cs @@ -80,12 +80,12 @@ public override void Execute(IMenuItemContext context) { } public static bool CanExecute(IDocumentViewer? documentViewer) => - !(documentViewer is null) && FindInstructions(documentViewer).Any(); + documentViewer is not null && FindInstructions(documentViewer).Any(); public static void Execute(IDocumentViewer? documentViewer, Lazy methodAnnotations) { if (!CanExecute(documentViewer)) return; - Debug2.Assert(!(documentViewer is null)); + Debug2.Assert(documentViewer is not null); var copier = new InstructionILBytesCopier(); var text = copier.Copy(FindInstructions(documentViewer), methodAnnotations); diff --git a/Extensions/dnSpy.AsmEditor/Commands/ListBoxHelperBase.cs b/Extensions/dnSpy.AsmEditor/Commands/ListBoxHelperBase.cs index f64fbf3af4..75b20782d0 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/ListBoxHelperBase.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/ListBoxHelperBase.cs @@ -212,7 +212,7 @@ protected void AddCopyHandlers() { } public void OnDataContextChanged(object dataContext) { - if (!(coll is null)) + if (coll is not null) throw new InvalidOperationException("DataContext changed more than once"); // Can't add M, N etc as shortcuts so must use a key down handler @@ -281,9 +281,9 @@ static void ShowContextMenu(ContextMenuEventArgs e, ListBox listBox, IList 1 ? handler.HeaderPlural ?? handler.Header : handler.Header); var tmpHandler = handler; menuItem.Click += (s, e2) => tmpHandler.Command.Execute(parameter); - if (!(handler.Icon is null)) + if (handler.Icon is not null) Add16x16Image(menuItem, handler.Icon.Value, menuItem.IsEnabled); - if (!(handler.InputGestureText is null)) + if (handler.InputGestureText is not null) menuItem.InputGestureText = ResourceHelper.GetString(handler, handler.InputGestureText); if (addSep) { @@ -362,8 +362,8 @@ void PasteItems(int relIndex) { } void PasteItems() => PasteItems(0); - bool PasteItemsCanExecute() => !(GetClipboardData() is null); + bool PasteItemsCanExecute() => GetClipboardData() is not null; void PasteAfterItems() => PasteItems(1); - bool PasteAfterItemsCanExecute() => listBox.SelectedIndex >= 0 && !(GetClipboardData() is null); + bool PasteAfterItemsCanExecute() => listBox.SelectedIndex >= 0 && GetClipboardData() is not null; } } diff --git a/Extensions/dnSpy.AsmEditor/Commands/NestedTypeNodeCreator.cs b/Extensions/dnSpy.AsmEditor/Commands/NestedTypeNodeCreator.cs index 0308f3ca6b..793b7a2174 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/NestedTypeNodeCreator.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/NestedTypeNodeCreator.cs @@ -34,7 +34,7 @@ sealed class NestedTypeNodeCreator { public IEnumerable OriginalNodes { get { yield return ownerTypeNode; - if (!(nestedTypeNode is null)) + if (nestedTypeNode is not null) yield return nestedTypeNode; } } @@ -44,7 +44,7 @@ public NestedTypeNodeCreator(ModuleDocumentNode modNode, TypeNode ownerTypeNode, throw new ArgumentNullException(nameof(modNode)); if (nestedType is null) throw new ArgumentNullException(nameof(nestedType)); - if (!(nestedType.Module is null)) + if (nestedType.Module is not null) throw new ArgumentException(); this.ownerTypeNode = ownerTypeNode; nestedTypeNode = modNode.Context.DocumentTreeView.CreateNested(nestedType); diff --git a/Extensions/dnSpy.AsmEditor/Commands/RefFinder.cs b/Extensions/dnSpy.AsmEditor/Commands/RefFinder.cs index f712d38133..3eca73bfa1 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/RefFinder.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/RefFinder.cs @@ -95,7 +95,7 @@ static bool Equals(IMemberRefParent @class, TypeDef type) { var tdrSig = typeSig as TypeDefOrRefSig; if (tdrSig is null && typeSig is GenericInstSig gis) tdrSig = gis.GenericType; - if (!(tdrSig is null)) { + if (tdrSig is not null) { if (tdrSig.TypeDefOrRef is TypeDef td2) return TypeEqualityComparerInstance.Equals(td2, type); if (tdrSig.TypeDefOrRef is TypeRef tr2) diff --git a/Extensions/dnSpy.AsmEditor/Commands/RootDocumentNodeCreator.cs b/Extensions/dnSpy.AsmEditor/Commands/RootDocumentNodeCreator.cs index 23848867ba..2a3fcce2d3 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/RootDocumentNodeCreator.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/RootDocumentNodeCreator.cs @@ -48,7 +48,7 @@ public RootDocumentNodeCreator(IDocumentTreeView documentTreeView, DsDocumentNod public void Add() { Debug2.Assert(documentNode.TreeNode.Parent is null); - if (!(documentNode.TreeNode.Parent is null)) + if (documentNode.TreeNode.Parent is not null) throw new InvalidOperationException(); Debug.Assert(!restoreIndex || origIndex >= 0); @@ -56,7 +56,7 @@ public void Add() { bool b = documentNode.Document.ModuleDef is null || (documentTreeView.FindNode( - !(documentNode.Document.AssemblyDef is null) ? + documentNode.Document.AssemblyDef is not null ? (object)documentNode.Document.AssemblyDef : documentNode.Document.ModuleDef) == documentNode); Debug.Assert(b); @@ -65,7 +65,7 @@ public void Add() { } public void Remove() { - Debug2.Assert(!(documentNode.TreeNode.Parent is null)); + Debug2.Assert(documentNode.TreeNode.Parent is not null); if (documentNode.TreeNode.Parent is null) throw new InvalidOperationException(); diff --git a/Extensions/dnSpy.AsmEditor/Commands/TypeNodeCreator.cs b/Extensions/dnSpy.AsmEditor/Commands/TypeNodeCreator.cs index 5c6caf1f4f..6386f65930 100644 --- a/Extensions/dnSpy.AsmEditor/Commands/TypeNodeCreator.cs +++ b/Extensions/dnSpy.AsmEditor/Commands/TypeNodeCreator.cs @@ -56,7 +56,7 @@ public TypeNodeCreator(ModuleDocumentNode modNode, List types) { if (tns != ns) throw new ArgumentException(); // Can't be a nested type, and can't be part of a module yet - if (!(t.DeclaringType is null) || !(t.Module is null)) + if (t.DeclaringType is not null || t.Module is not null) throw new ArgumentException(); } ownerList = modNode.Document.ModuleDef!.Types; diff --git a/Extensions/dnSpy.AsmEditor/Compiler/AddClassCommands.cs b/Extensions/dnSpy.AsmEditor/Compiler/AddClassCommands.cs index 20cc22c3e3..45a3793f45 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/AddClassCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/AddClassCommands.cs @@ -98,7 +98,7 @@ sealed class CodeCommand : NodesCodeContextMenuHandler { } static bool CanExecute(EditCodeVMCreator editCodeVMCreator, DocumentTreeNodeData[] nodes) => - editCodeVMCreator.CanCreate(CompilationKind.AddClass) && nodes.Length == 1 && !(GetModuleNode(nodes[0]) is null); + editCodeVMCreator.CanCreate(CompilationKind.AddClass) && nodes.Length == 1 && GetModuleNode(nodes[0]) is not null; static ModuleDocumentNode? GetModuleNode(DocumentTreeNodeData node) { if (node is AssemblyDocumentNode asmNode) { @@ -114,11 +114,11 @@ static void Execute(EditCodeVMCreator editCodeVMCreator, Lazy methodAnnotations, Lazy IsVisible(editCodeVMCreator, BodyCommandUtils.GetStatements(context, FindByTextPositionOptions.OuterMostStatement)); static bool IsVisible(EditCodeVMCreator editCodeVMCreator, IList? list) => editCodeVMCreator.CanCreate(CompilationKind.EditMethod) && - !(list is null) && + list is not null && list.Count != 0 && - !(list[0].Method.Body is null) && + list[0].Method.Body is not null && list[0].Method.Body.Instructions.Count > 0; public override void Execute(IMenuItemContext context) => Execute(BodyCommandUtils.GetStatements(context, FindByTextPositionOptions.OuterMostStatement)); diff --git a/Extensions/dnSpy.AsmEditor/Compiler/EditAssemblyCommands.cs b/Extensions/dnSpy.AsmEditor/Compiler/EditAssemblyCommands.cs index 9e32d3e2a9..7b86ead5a7 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/EditAssemblyCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/EditAssemblyCommands.cs @@ -106,17 +106,17 @@ static void Execute(EditCodeVMCreator editCodeVMCreator, Lazy IsVisible(editCodeVMCreator, BodyCommandUtils.GetStatements(context, FindByTextPositionOptions.OuterMostStatement)); static bool IsVisible(EditCodeVMCreator editCodeVMCreator, IList? list) => editCodeVMCreator.CanCreate(CompilationKind.EditClass) && - !(list is null) && + list is not null && list.Count != 0 && - !(list[0].Method.Body is null) && + list[0].Method.Body is not null && list[0].Method.Body.Instructions.Count > 0; public override void Execute(IMenuItemContext context) => Execute(BodyCommandUtils.GetStatements(context, FindByTextPositionOptions.OuterMostStatement)); diff --git a/Extensions/dnSpy.AsmEditor/Compiler/EditClassVM.cs b/Extensions/dnSpy.AsmEditor/Compiler/EditClassVM.cs index dcbda43aab..a4611eb712 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/EditClassVM.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/EditClassVM.cs @@ -42,7 +42,7 @@ public EditClassVM(EditCodeVMOptions options, IMemberDef defToEdit, IList(StringComparer.OrdinalIgnoreCase); - if (!(typeToEdit is null)) { + if (typeToEdit is not null) { Debug.Assert(typeToEdit.Module == sourceModule); - while (!(typeToEdit.DeclaringType is null)) + while (typeToEdit.DeclaringType is not null) typeToEdit = typeToEdit.DeclaringType; } tempAssembly = new AssemblyNameInfo { @@ -339,7 +339,7 @@ async Task StartDecompileAsync() { for (int i = 0; i < Documents.Count; i++) { var doc = Documents[i]; var caretSpan = simpleDocuments[i].CaretSpan; - if (!(caretSpan is null) && caretSpan.Value.End <= doc.TextView.TextSnapshot.Length) + if (caretSpan is not null && caretSpan.Value.End <= doc.TextView.TextSnapshot.Length) doc.Initialize(new SnapshotPoint(doc.TextView.TextSnapshot, caretSpan.Value.Start)); else doc.Initialize(new SnapshotPoint(doc.TextView.TextSnapshot, 0)); @@ -446,7 +446,7 @@ async Task StartCompileAsync() { new CompilerDiagnostic(CompilerDiagnosticSeverity.Error, "The task was canceled", "DSWTF!", null, null, null), }; } - else if (!(caughtException is null)) { + else if (caughtException is not null) { compilerDiagnostics = new CompilerDiagnostic[] { ToCompilerDiagnostic(caughtException) }; } else if (result?.Success == true) { @@ -479,7 +479,7 @@ async Task StartCompileAsync() { compileCodeState = null; CanCompile = true; - if (!(importer is null)) { + if (importer is not null) { Result = importer; CodeCompiled?.Invoke(this, EventArgs.Empty); } @@ -495,7 +495,7 @@ static CompilerDiagnostic ToCompilerDiagnostic(Exception ex) => Task CompileAsync() { Debug2.Assert(compileCodeState is null); - if (!(compileCodeState is null)) + if (compileCodeState is not null) throw new InvalidOperationException(); var state = new CompileCodeState(); compileCodeState = state; @@ -589,12 +589,12 @@ internal void MoveTo(CompilerDiagnosticVM diag) { return; var doc = Documents.FirstOrDefault(a => a.Name == diag.FullPath); - Debug2.Assert(!(doc is null)); + Debug2.Assert(doc is not null); if (doc is null) return; SelectedDocument = doc; - if (!(diag.LineLocationSpan is null)) { + if (diag.LineLocationSpan is not null) { UIUtilities.Focus(doc.TextView.VisualElement, () => { // The caret isn't always moved unless we wait a little doc.TextView.VisualElement.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { diff --git a/Extensions/dnSpy.AsmEditor/Compiler/EditCodeVMCreator.cs b/Extensions/dnSpy.AsmEditor/Compiler/EditCodeVMCreator.cs index 113327fa05..4d6cc94dfc 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/EditCodeVMCreator.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/EditCodeVMCreator.cs @@ -51,7 +51,7 @@ sealed class EditCodeVMCreator { this.languageCompilerProviders = languageCompilerProviders.OrderBy(a => a.Order).ToArray(); } - public bool CanCreate(CompilationKind kind) => !(GetLanguageCompilerProvider(kind) is null); + public bool CanCreate(CompilationKind kind) => GetLanguageCompilerProvider(kind) is not null; (IDecompiler decompiler, ILanguageCompilerProvider languageCompilerProvider)? GetLanguageCompilerProvider(CompilationKind kind) { var language = TryGetUsedLanguage(kind); diff --git a/Extensions/dnSpy.AsmEditor/Compiler/EditMethodCodeVM.cs b/Extensions/dnSpy.AsmEditor/Compiler/EditMethodCodeVM.cs index db51cd21c4..93bcee380e 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/EditMethodCodeVM.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/EditMethodCodeVM.cs @@ -53,7 +53,7 @@ protected override Task DecompileAsync(DecompileCodeState state.CancellationToken.ThrowIfCancellationRequested(); var type = methodToEdit.DeclaringType; - while (!(type.DeclaringType is null)) + while (type.DeclaringType is not null) type = type.DeclaringType; DecompileTypeMethods options; diff --git a/Extensions/dnSpy.AsmEditor/Compiler/ExistingTypeNodeUpdater.cs b/Extensions/dnSpy.AsmEditor/Compiler/ExistingTypeNodeUpdater.cs index 26a8d117fd..4efda6ce9a 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/ExistingTypeNodeUpdater.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/ExistingTypeNodeUpdater.cs @@ -88,11 +88,11 @@ static HashSet GetSpecialMethods(MergedImportedType type) { } foreach (var e in type.NewEvents) { - if (!(e.AddMethod is null)) + if (e.AddMethod is not null) specialMethods.Add(e.AddMethod); - if (!(e.RemoveMethod is null)) + if (e.RemoveMethod is not null) specialMethods.Add(e.RemoveMethod); - if (!(e.InvokeMethod is null)) + if (e.InvokeMethod is not null) specialMethods.Add(e.InvokeMethod); foreach (var m in e.OtherMethods) specialMethods.Add(m); diff --git a/Extensions/dnSpy.AsmEditor/Compiler/ImportSigComparer.cs b/Extensions/dnSpy.AsmEditor/Compiler/ImportSigComparer.cs index 88fa95ed2a..b61a145ad1 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/ImportSigComparer.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/ImportSigComparer.cs @@ -205,7 +205,7 @@ bool Equals(IAssembly aAsm, IAssembly bAsm, TypeRef b) { // Could be an exported type. Resolve it and check again. var td = b.Resolve(sourceModule); - return !(td is null) && Equals(aAsm, td.Module.Assembly); + return td is not null && Equals(aAsm, td.Module.Assembly); } bool Equals(IAssembly aAsm, IAssembly bAsm, ExportedType b) { @@ -213,7 +213,7 @@ bool Equals(IAssembly aAsm, IAssembly bAsm, ExportedType b) { return true; var td = b.Resolve(); - return !(td is null) && Equals(aAsm, td.Module.Assembly); + return td is not null && Equals(aAsm, td.Module.Assembly); } bool Equals(IAssembly? aAsm, TypeRef a, IAssembly? bAsm, TypeRef b) { @@ -224,7 +224,7 @@ bool Equals(IAssembly? aAsm, TypeRef a, IAssembly? bAsm, TypeRef b) { var tda = a.Resolve(sourceModule); var tdb = b.Resolve(sourceModule); - return !(tda is null) && !(tdb is null) && Equals(tda.Module.Assembly, tdb.Module.Assembly); + return tda is not null && tdb is not null && Equals(tda.Module.Assembly, tdb.Module.Assembly); } bool Equals(IAssembly? aAsm, ExportedType a, IAssembly? bAsm, ExportedType b) { @@ -233,7 +233,7 @@ bool Equals(IAssembly? aAsm, ExportedType a, IAssembly? bAsm, ExportedType b) { var tda = a.Resolve(); var tdb = b.Resolve(); - return !(tda is null) && !(tdb is null) && Equals(tda.Module.Assembly, tdb.Module.Assembly); + return tda is not null && tdb is not null && Equals(tda.Module.Assembly, tdb.Module.Assembly); } bool Equals(IAssembly? aAsm, TypeRef a, IAssembly? bAsm, ExportedType b) { @@ -244,7 +244,7 @@ bool Equals(IAssembly? aAsm, TypeRef a, IAssembly? bAsm, ExportedType b) { var tda = a.Resolve(sourceModule); var tdb = b.Resolve(); - return !(tda is null) && !(tdb is null) && Equals(tda.Module.Assembly, tdb.Module.Assembly); + return tda is not null && tdb is not null && Equals(tda.Module.Assembly, tdb.Module.Assembly); } bool Equals(TypeDef a, IModule bMod, TypeRef b) { @@ -264,7 +264,7 @@ bool Equals(TypeDef a, FileDef bFile, ExportedType b) { return true; var td = b.Resolve(); - return !(td is null) && Equals(a.Module, td.Module) && Equals(a.DefinitionAssembly, td.DefinitionAssembly); + return td is not null && Equals(a.Module, td.Module) && Equals(a.DefinitionAssembly, td.DefinitionAssembly); } bool TypeDefScopeEquals(TypeDef? a, TypeDef? b) { @@ -281,7 +281,7 @@ bool Equals(TypeRef a, IModule? ma, TypeRef b, IModule? mb) { var tda = a.Resolve(sourceModule); var tdb = b.Resolve(sourceModule); - return !(tda is null) && !(tdb is null) && + return tda is not null && tdb is not null && Equals(tda.Module, tdb.Module) && Equals(tda.DefinitionAssembly, tdb.DefinitionAssembly); } @@ -293,7 +293,7 @@ bool Equals(TypeRef a, IModule? ma, ExportedType b, FileDef? fb) { var tda = a.Resolve(sourceModule); var tdb = b.Resolve(); - return !(tda is null) && !(tdb is null) && + return tda is not null && tdb is not null && Equals(tda.Module, tdb.Module) && Equals(tda.DefinitionAssembly, tdb.DefinitionAssembly); } @@ -312,15 +312,15 @@ public bool Equals(IMemberRef? a, IMemberRef? b) { PropertyDef? pa, pb; EventDef? ea, eb; - if (!((ta = a as IType) is null) && !((tb = b as IType) is null)) + if ((ta = a as IType) is not null && (tb = b as IType) is not null) result = Equals(ta, tb); - else if (!((fa = a as IField) is null) && !((fb = b as IField) is null) && fa.IsField && fb.IsField) + else if ((fa = a as IField) is not null && (fb = b as IField) is not null && fa.IsField && fb.IsField) result = Equals(fa, fb); - else if (!((ma = a as IMethod) is null) && !((mb = b as IMethod) is null)) + else if ((ma = a as IMethod) is not null && (mb = b as IMethod) is not null) result = Equals(ma, mb); - else if (!((pa = a as PropertyDef) is null) && !((pb = b as PropertyDef) is null)) + else if ((pa = a as PropertyDef) is not null && (pb = b as PropertyDef) is not null) result = Equals(pa, pb); - else if (!((ea = a as EventDef) is null) && !((eb = b as EventDef) is null)) + else if ((ea = a as EventDef) is not null && (eb = b as EventDef) is not null) result = Equals(ea, eb); else result = false; @@ -342,15 +342,15 @@ public int GetHashCode(IMemberRef? a) { PropertyDef? pa; EventDef? ea; - if (!((ta = a as IType) is null)) + if ((ta = a as IType) is not null) result = GetHashCode(ta); - else if (!((fa = a as IField) is null)) + else if ((fa = a as IField) is not null) result = GetHashCode(fa); - else if (!((ma = a as IMethod) is null)) + else if ((ma = a as IMethod) is not null) result = GetHashCode(ma); - else if (!((pa = a as PropertyDef) is null)) + else if ((pa = a as PropertyDef) is not null) result = GetHashCode(pa); - else if (!((ea = a as EventDef) is null)) + else if ((ea = a as EventDef) is not null) result = GetHashCode(ea); else result = 0; // Should never be reached @@ -378,55 +378,55 @@ public bool Equals(IType? a, IType? b) { TypeSig? sa, sb; ExportedType? eta, etb; - if (!((tda = a as TypeDef) is null) & !((tdb = b as TypeDef) is null)) + if ((tda = a as TypeDef) is not null & (tdb = b as TypeDef) is not null) result = Equals(tda, tdb); - else if (!((tra = a as TypeRef) is null) & !((trb = b as TypeRef) is null)) + else if ((tra = a as TypeRef) is not null & (trb = b as TypeRef) is not null) result = Equals(tra, trb); - else if (!((tsa = a as TypeSpec) is null) & !((tsb = b as TypeSpec) is null)) + else if ((tsa = a as TypeSpec) is not null & (tsb = b as TypeSpec) is not null) result = Equals(tsa, tsb); - else if (!((sa = a as TypeSig) is null) & !((sb = b as TypeSig) is null)) + else if ((sa = a as TypeSig) is not null & (sb = b as TypeSig) is not null) result = Equals(sa, sb); - else if (!((eta = a as ExportedType) is null) & !((etb = b as ExportedType) is null)) + else if ((eta = a as ExportedType) is not null & (etb = b as ExportedType) is not null) result = Equals(eta, etb); - else if (!(tda is null) && !(trb is null)) + else if (tda is not null && trb is not null) result = Equals(tda, trb); // TypeDef vs TypeRef - else if (!(tra is null) && !(tdb is null)) + else if (tra is not null && tdb is not null) result = Equals(tdb, tra); // TypeDef vs TypeRef - else if (!(tda is null) && !(tsb is null)) + else if (tda is not null && tsb is not null) result = Equals(tda, tsb); // TypeDef vs TypeSpec - else if (!(tsa is null) && !(tdb is null)) + else if (tsa is not null && tdb is not null) result = Equals(tdb, tsa); // TypeDef vs TypeSpec - else if (!(tda is null) && !(sb is null)) + else if (tda is not null && sb is not null) result = Equals(tda, sb); // TypeDef vs TypeSig - else if (!(sa is null) && !(tdb is null)) + else if (sa is not null && tdb is not null) result = Equals(tdb, sa); // TypeDef vs TypeSig - else if (!(tda is null) && !(etb is null)) + else if (tda is not null && etb is not null) result = Equals(tda, etb); // TypeDef vs ExportedType - else if (!(eta is null) && !(tdb is null)) + else if (eta is not null && tdb is not null) result = Equals(tdb, eta); // TypeDef vs ExportedType - else if (!(tra is null) && !(tsb is null)) + else if (tra is not null && tsb is not null) result = Equals(tra, tsb); // TypeRef vs TypeSpec - else if (!(tsa is null) && !(trb is null)) + else if (tsa is not null && trb is not null) result = Equals(trb, tsa); // TypeRef vs TypeSpec - else if (!(tra is null) && !(sb is null)) + else if (tra is not null && sb is not null) result = Equals(tra, sb); // TypeRef vs TypeSig - else if (!(sa is null) && !(trb is null)) + else if (sa is not null && trb is not null) result = Equals(trb, sa); // TypeRef vs TypeSig - else if (!(tra is null) && !(etb is null)) + else if (tra is not null && etb is not null) result = Equals(tra, etb); // TypeRef vs ExportedType - else if (!(eta is null) && !(trb is null)) + else if (eta is not null && trb is not null) result = Equals(trb, eta); // TypeRef vs ExportedType - else if (!(tsa is null) && !(sb is null)) + else if (tsa is not null && sb is not null) result = Equals(tsa, sb); // TypeSpec vs TypeSig - else if (!(sa is null) && !(tsb is null)) + else if (sa is not null && tsb is not null) result = Equals(tsb, sa); // TypeSpec vs TypeSig - else if (!(tsa is null) && !(etb is null)) + else if (tsa is not null && etb is not null) result = Equals(tsa, etb); // TypeSpec vs ExportedType - else if (!(eta is null) && !(tsb is null)) + else if (eta is not null && tsb is not null) result = Equals(tsb, eta); // TypeSpec vs ExportedType - else if (!(sa is null) && !(etb is null)) + else if (sa is not null && etb is not null) result = Equals(sa, etb); // TypeSig vs ExportedType - else if (!(eta is null) && !(sb is null)) + else if (eta is not null && sb is not null) result = Equals(sb, eta); // TypeSig vs ExportedType else result = false; // Should never be reached @@ -448,15 +448,15 @@ public int GetHashCode(IType? a) { TypeSig? sig; ExportedType? et; - if (!((td = a as TypeDef) is null)) + if ((td = a as TypeDef) is not null) hash = GetHashCode(td); - else if (!((tr = a as TypeRef) is null)) + else if ((tr = a as TypeRef) is not null) hash = GetHashCode(tr); - else if (!((ts = a as TypeSpec) is null)) + else if ((ts = a as TypeSpec) is not null) hash = GetHashCode(ts); - else if (!((sig = a as TypeSig) is null)) + else if ((sig = a as TypeSig) is not null) hash = GetHashCode(sig); - else if (!((et = a as ExportedType) is null)) + else if ((et = a as ExportedType) is not null) hash = GetHashCode(et); else hash = 0; // Should never be reached @@ -484,19 +484,19 @@ public bool Equals(TypeDef? a, TypeRef? b) { if (!Equals_TypeNames(a.Name, b.Name) || !Equals_TypeNamespaces(a.Namespace, b.Namespace)) result = false; - else if (!((dtb = scope as TypeRef) is null)) // nested type + else if ((dtb = scope as TypeRef) is not null) // nested type result = Equals(a.DeclaringType, dtb); // Compare enclosing types - else if (!(a.DeclaringType is null)) { + else if (a.DeclaringType is not null) { // a is nested, b isn't result = false; } else if (DontCompareTypeScope) result = true; - else if (!((bMod = scope as IModule) is null)) // 'b' is defined in the same assembly as 'a' + else if ((bMod = scope as IModule) is not null) // 'b' is defined in the same assembly as 'a' result = Equals(a, bMod, b); - else if (!((bAsm = scope as AssemblyRef) is null)) { + else if ((bAsm = scope as AssemblyRef) is not null) { var aMod = a.Module; - result = !(aMod is null) && Equals(aMod.Assembly, bAsm, b); + result = aMod is not null && Equals(aMod.Assembly, bAsm, b); } else { result = false; @@ -528,20 +528,20 @@ public bool Equals(TypeDef? a, ExportedType? b) { if (!Equals_TypeNames(a.Name, b.TypeName) || !Equals_TypeNamespaces(a.Namespace, b.TypeNamespace)) result = false; - else if (!((dtb = scope as ExportedType) is null)) { // nested type + else if ((dtb = scope as ExportedType) is not null) { // nested type result = Equals(a.DeclaringType, dtb); // Compare enclosing types } - else if (!(a.DeclaringType is null)) { + else if (a.DeclaringType is not null) { result = false; // a is nested, b isn't } else if (DontCompareTypeScope) result = true; else { - if (!((bFile = scope as FileDef) is null)) + if ((bFile = scope as FileDef) is not null) result = Equals(a, bFile, b); - else if (!((bAsm = scope as AssemblyRef) is null)) { + else if ((bAsm = scope as AssemblyRef) is not null) { var aMod = a.Module; - result = !(aMod is null) && Equals(aMod.Assembly, bAsm, b); + result = aMod is not null && Equals(aMod.Assembly, bAsm, b); } else result = false; @@ -764,7 +764,7 @@ public int GetHashCode(TypeDef? a) { int hash; hash = GetHashCode_TypeName(a.Name); - if (!(a.DeclaringType is null)) + if (a.DeclaringType is not null) hash += HASHCODE_MAGIC_NESTED_TYPE; else hash += GetHashCode_TypeNamespace(a.Namespace); @@ -812,27 +812,27 @@ bool EqualsResolutionScope(TypeRef? a, TypeRef? b) { ModuleDef? modDef; // if one of them is a TypeRef, the other one must be too - if (!((ea = ra as TypeRef) is null) | !((eb = rb as TypeRef) is null)) + if ((ea = ra as TypeRef) is not null | (eb = rb as TypeRef) is not null) result = Equals(ea, eb); else if (DontCompareTypeScope) result = true; // only compare if both are modules - else if (!((ma = ra as IModule) is null) & !((mb = rb as IModule) is null)) + else if ((ma = ra as IModule) is not null & (mb = rb as IModule) is not null) result = Equals(a, ma, b, mb); // only compare if both are assemblies - else if (!((aa = ra as AssemblyRef) is null) & !((ab = rb as AssemblyRef) is null)) + else if ((aa = ra as AssemblyRef) is not null & (ab = rb as AssemblyRef) is not null) result = Equals(aa, a, ab, b); - else if (!(aa is null) && rb is ModuleRef) { + else if (aa is not null && rb is ModuleRef) { var bMod = b.Module; - result = !(bMod is null) && Equals(bMod.Assembly, b, aa, a); + result = bMod is not null && Equals(bMod.Assembly, b, aa, a); } - else if (!(ab is null) && ra is ModuleRef) { + else if (ab is not null && ra is ModuleRef) { var aMod = a.Module; - result = !(aMod is null) && Equals(aMod.Assembly, a, ab, b); + result = aMod is not null && Equals(aMod.Assembly, a, ab, b); } - else if (!(aa is null) && !((modDef = rb as ModuleDef) is null)) + else if (aa is not null && (modDef = rb as ModuleDef) is not null) result = Equals(modDef.Assembly, aa, a); - else if (!(ab is null) && !((modDef = ra as ModuleDef) is null)) + else if (ab is not null && (modDef = ra as ModuleDef) is not null) result = Equals(modDef.Assembly, ab, b); else result = false; @@ -861,19 +861,19 @@ bool EqualsImplementation(ExportedType? a, ExportedType? b) { AssemblyRef? aa, ab; // if one of them is an ExportedType, the other one must be too - if (!((ea = ia as ExportedType) is null) | !((eb = ib as ExportedType) is null)) + if ((ea = ia as ExportedType) is not null | (eb = ib as ExportedType) is not null) result = Equals(ea, eb); else if (DontCompareTypeScope) result = true; // only compare if both are files - else if (!((fa = ia as FileDef) is null) & !((fb = ib as FileDef) is null)) + else if ((fa = ia as FileDef) is not null & (fb = ib as FileDef) is not null) result = Equals(fa, fb); // only compare if both are assemblies - else if (!((aa = ia as AssemblyRef) is null) & !((ab = ib as AssemblyRef) is null)) + else if ((aa = ia as AssemblyRef) is not null & (ab = ib as AssemblyRef) is not null) result = Equals(aa, a, ab, b); - else if (!(fa is null) && !(ab is null)) + else if (fa is not null && ab is not null) result = Equals(a.DefinitionAssembly, ab, b); - else if (!(fb is null) && !(aa is null)) + else if (fb is not null && aa is not null) result = Equals(b.DefinitionAssembly, aa, a); else result = false; @@ -904,17 +904,17 @@ bool EqualsScope(TypeRef? a, ExportedType? b) { AssemblyRef? aa, ab; // If one is a nested type, the other one must be too - if (!((ea = ra as TypeRef) is null) | !((eb = ib as ExportedType) is null)) + if ((ea = ra as TypeRef) is not null | (eb = ib as ExportedType) is not null) result = Equals(ea, eb); else if (DontCompareTypeScope) result = true; - else if (!((ma = ra as IModule) is null) & !((fb = ib as FileDef) is null)) + else if ((ma = ra as IModule) is not null & (fb = ib as FileDef) is not null) result = Equals(a, ma, b, fb); - else if (!((aa = ra as AssemblyRef) is null) & !((ab = ib as AssemblyRef) is null)) + else if ((aa = ra as AssemblyRef) is not null & (ab = ib as AssemblyRef) is not null) result = Equals(aa, a, ab, b); - else if (!(ma is null) && !(ab is null)) + else if (ma is not null && ab is not null) result = Equals(a.DefinitionAssembly, ab, b); - else if (!(fb is null) && !(aa is null)) + else if (fb is not null && aa is not null) result = Equals(b.DefinitionAssembly, aa, a); else result = false; @@ -953,11 +953,11 @@ internal bool Equals(IModule? a, IModule? b) { return UTF8String.CaseInsensitiveEquals(a.Name, b.Name) || (IsTargetOrSourceModule(a) && IsTargetOrSourceModule(b)); } - static bool IsCorLib(ModuleDef? a) => !(a is null) && a.IsManifestModule && a.Assembly.IsCorLib(); + static bool IsCorLib(ModuleDef? a) => a is not null && a.IsManifestModule && a.Assembly.IsCorLib(); static bool IsCorLib(IModule? a) { var mod = a as ModuleDef; - return !(mod is null) && mod.IsManifestModule && mod.Assembly.IsCorLib(); + return mod is not null && mod.IsManifestModule && mod.Assembly.IsCorLib(); } static bool IsCorLib(IAssembly a) => a.IsCorLib(); @@ -1000,11 +1000,11 @@ bool Equals(IAssembly? a, IAssembly? b) { } bool IsTargetOrSourceAssembly(IAssembly? a) => IsTargetAssembly(a) || IsSourceAssembly(a); - bool IsTargetAssembly(IAssembly? a) => !(a is null) && __AssemblyEquals(a, importOptions.TargetModule.Assembly); - bool IsSourceAssembly(IAssembly? a) => !(a is null) && __AssemblyEquals(a, importOptions.SourceModule.Assembly); + bool IsTargetAssembly(IAssembly? a) => a is not null && __AssemblyEquals(a, importOptions.TargetModule.Assembly); + bool IsSourceAssembly(IAssembly? a) => a is not null && __AssemblyEquals(a, importOptions.SourceModule.Assembly); bool IsTargetOrSourceModule(IModule? a) => IsTargetModule(a) || IsSourceModule(a); - bool IsTargetModule(IModule? a) => !(a is null) && __ModuleEquals(a, importOptions.TargetModule); - bool IsSourceModule(IModule? a) => !(a is null) && __ModuleEquals(a, importOptions.SourceModule); + bool IsTargetModule(IModule? a) => a is not null && __ModuleEquals(a, importOptions.TargetModule); + bool IsSourceModule(IModule? a) => a is not null && __ModuleEquals(a, importOptions.SourceModule); bool __AssemblyEquals(IAssembly? a, AssemblyDef? b) { if ((object?)a == b) return true; @@ -1349,22 +1349,22 @@ bool Equals(CallingConventionSig? a, CallingConventionSig? b, bool compareHasThi case CallingConvention.Property: case CallingConvention.NativeVarArg: MethodBaseSig ma = (MethodBaseSig)a, mb = (MethodBaseSig)b; - result = !(ma is null) && !(mb is null) && Equals(ma, mb, compareHasThisFlag); + result = ma is not null && mb is not null && Equals(ma, mb, compareHasThisFlag); break; case CallingConvention.Field: FieldSig fa = (FieldSig)a, fb = (FieldSig)b; - result = !(fa is null) && !(fb is null) && Equals(fa, fb); + result = fa is not null && fb is not null && Equals(fa, fb); break; case CallingConvention.LocalSig: LocalSig la = (LocalSig)a, lb = (LocalSig)b; - result = !(la is null) && !(lb is null) && Equals(la, lb); + result = la is not null && lb is not null && Equals(la, lb); break; case CallingConvention.GenericInst: GenericInstMethodSig ga = (GenericInstMethodSig)a, gb = (GenericInstMethodSig)b; - result = !(ga is null) && !(gb is null) && Equals(ga, gb); + result = ga is not null && gb is not null && Equals(ga, gb); break; case CallingConvention.Unmanaged: @@ -1581,15 +1581,15 @@ public bool Equals(IMethod? a, IMethod? b) { MemberRef? mra, mrb; MethodSpec? msa, msb; - if (!((mda = a as MethodDef) is null) & !((mdb = b as MethodDef) is null)) + if ((mda = a as MethodDef) is not null & (mdb = b as MethodDef) is not null) result = Equals(mda, mdb); - else if (!((mra = a as MemberRef) is null) & !((mrb = b as MemberRef) is null)) + else if ((mra = a as MemberRef) is not null & (mrb = b as MemberRef) is not null) result = Equals(mra, mrb); - else if (!((msa = a as MethodSpec) is null) && !((msb = b as MethodSpec) is null)) + else if ((msa = a as MethodSpec) is not null && (msb = b as MethodSpec) is not null) result = Equals(msa, msb); - else if (!(mda is null) && !(mrb is null)) + else if (mda is not null && mrb is not null) result = Equals(mda, mrb); - else if (!(mra is null) && !(mdb is null)) + else if (mra is not null && mdb is not null) result = Equals(mdb, mra); else result = false; @@ -1609,11 +1609,11 @@ public int GetHashCode(IMethod? a) { MemberRef? mra; MethodSpec? msa; - if (!((mda = a as MethodDef) is null)) + if ((mda = a as MethodDef) is not null) hash = GetHashCode(mda); - else if (!((mra = a as MemberRef) is null)) + else if ((mra = a as MemberRef) is not null) hash = GetHashCode(mra); - else if (!((msa = a as MethodSpec) is null)) + else if ((msa = a as MethodSpec) is not null) hash = GetHashCode(msa); else hash = 0; @@ -1746,18 +1746,18 @@ bool Equals(IMemberRefParent? a, IMemberRefParent? b) { MethodDef? ma, mb; TypeDef? td; - if (!((ita = a as ITypeDefOrRef) is null) && !((itb = b as ITypeDefOrRef) is null)) + if ((ita = a as ITypeDefOrRef) is not null && (itb = b as ITypeDefOrRef) is not null) result = Equals((IType)ita, (IType)itb); - else if (!((moda = a as ModuleRef) is null) & !((modb = b as ModuleRef) is null)) { + else if ((moda = a as ModuleRef) is not null & (modb = b as ModuleRef) is not null) { ModuleDef omoda = moda!.Module, omodb = modb!.Module; result = Equals((IModule)moda, (IModule)modb) && Equals(omoda is null ? null : omoda.Assembly, omodb is null ? null : omodb.Assembly); } - else if (!((ma = a as MethodDef) is null) && !((mb = b as MethodDef) is null)) + else if ((ma = a as MethodDef) is not null && (mb = b as MethodDef) is not null) result = Equals(ma, mb); - else if (!(modb is null) && !((td = a as TypeDef) is null)) + else if (modb is not null && (td = a as TypeDef) is not null) result = EqualsGlobal(td, modb); - else if (!(moda is null) && !((td = b as TypeDef) is null)) + else if (moda is not null && (td = b as TypeDef) is not null) result = EqualsGlobal(td, moda); else result = false; @@ -1776,11 +1776,11 @@ int GetHashCode(IMemberRefParent? a) { ITypeDefOrRef? ita; MethodDef? ma; - if (!((ita = a as ITypeDefOrRef) is null)) + if ((ita = a as ITypeDefOrRef) is not null) hash = GetHashCode((IType)ita); else if (a is ModuleRef) hash = GetHashCodeGlobalType(); - else if (!((ma = a as MethodDef) is null)) { + else if ((ma = a as MethodDef) is not null) { // Only use the declaring type so we get the same hash code when hashing a MethodBase. hash = GetHashCode(ma.DeclaringType); } @@ -1803,13 +1803,13 @@ public bool Equals(IField? a, IField? b) { FieldDef? fa, fb; MemberRef? ma, mb; - if (!((fa = a as FieldDef) is null) & !((fb = b as FieldDef) is null)) + if ((fa = a as FieldDef) is not null & (fb = b as FieldDef) is not null) result = Equals(fa, fb); - else if (!((ma = a as MemberRef) is null) & !((mb = b as MemberRef) is null)) + else if ((ma = a as MemberRef) is not null & (mb = b as MemberRef) is not null) result = Equals(ma, mb); - else if (!(fa is null) && !(mb is null)) + else if (fa is not null && mb is not null) result = Equals(fa, mb); - else if (!(fb is null) && !(ma is null)) + else if (fb is not null && ma is not null) result = Equals(fb, ma); else result = false; @@ -1828,9 +1828,9 @@ public int GetHashCode(IField? a) { FieldDef? fa; MemberRef? ma; - if (!((fa = a as FieldDef) is null)) + if ((fa = a as FieldDef) is not null) hash = GetHashCode(fa); - else if (!((ma = a as MemberRef) is null)) + else if ((ma = a as MemberRef) is not null) hash = GetHashCode(ma); else hash = 0; diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/BlobMDHeap.cs b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/BlobMDHeap.cs index a453e991ed..cf8a5504b6 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/BlobMDHeap.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/BlobMDHeap.cs @@ -79,6 +79,6 @@ byte[] GetLengthBytes(uint value) { } public override bool MustRewriteHeap() => newData.Count > 0; - public override bool ExistsInMetadata => !(blobStream.StreamHeader is null); + public override bool ExistsInMetadata => blobStream.StreamHeader is not null; } } diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/GuidMDHeap.cs b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/GuidMDHeap.cs index b4709af2a3..350cd285c6 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/GuidMDHeap.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/GuidMDHeap.cs @@ -41,6 +41,6 @@ public GuidMDHeap(MetadataEditor mdEditor, GuidStream guidStream) { } public override bool MustRewriteHeap() => newData.Count > 0; - public override bool ExistsInMetadata => !(guidStream.StreamHeader is null); + public override bool ExistsInMetadata => guidStream.StreamHeader is not null; } } diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/ImageCor20HeaderSectionData.cs b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/ImageCor20HeaderSectionData.cs index 37026f2ae8..f5ef1e3fc4 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/ImageCor20HeaderSectionData.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/ImageCor20HeaderSectionData.cs @@ -70,7 +70,7 @@ public override void Finish(MDWriter mdWriter, MDWriterStream stream) { stream.Write(mdData.RVA); stream.Write(mdData.Size); - if (!(snData is null)) { + if (snData is not null) { stream.Position = cor20HeaderStrongnameDataDirPosition; Debug.Assert(snData.RVA != 0); Debug.Assert(snData.Size != 0); diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/MDWriter.cs b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/MDWriter.cs index c3f916f097..fc69fc50bd 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/MDWriter.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/MDWriter.cs @@ -95,7 +95,7 @@ public void Write() { if ((cor20.Flags & ComImageFlags.StrongNameSigned) != 0 && cor20.StrongNameSignature.Size != 0 && cor20.StrongNameSignature.VirtualAddress != 0) snData = new StrongNameSignatureSectionData(cor20.StrongNameSignature.Size); - if (!(snData is null)) + if (snData is not null) textSection.SectionData.Add(snData); var mdData = new DotNetMetadataSectionData(mdEditor); textSection.SectionData.Add(new ImageCor20HeaderSectionData(mdData, snData)); diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/StringsMDHeap.cs b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/StringsMDHeap.cs index 1671917c72..1d7efc8f8c 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/StringsMDHeap.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/StringsMDHeap.cs @@ -74,6 +74,6 @@ static void CheckValidName(byte[] bytes) { } public override bool MustRewriteHeap() => newData.Count > 0; - public override bool ExistsInMetadata => !(stringsStream.StreamHeader is null); + public override bool ExistsInMetadata => stringsStream.StreamHeader is not null; } } diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/TablesHeapWriter.cs b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/TablesHeapWriter.cs index 1cfdd3b360..51292af17a 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/TablesHeapWriter.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/TablesHeapWriter.cs @@ -105,7 +105,7 @@ public unsafe override void Write(MDWriter mdWriter, MDWriterStream stream, byte if (tablesToIgnore[i]) continue; var info = infos[i]; - if (!(info is null) && !info.IsEmpty) { + if (info is not null && !info.IsEmpty) { rowCounts[i] = info.Rows; stream.Write(info.Rows); } @@ -123,7 +123,7 @@ public unsafe override void Write(MDWriter mdWriter, MDWriterStream stream, byte if (tablesToIgnore[i]) continue; var info = infos[i]; - if (!(info is null) && !info.IsEmpty) + if (info is not null && !info.IsEmpty) totalSize += (long)info.Rows * tableInfos[i].RowSize; } @@ -211,7 +211,7 @@ static ulong GetValidMask(TablesMDHeap tablesHeap) { if (tablesToIgnore[i]) continue; var info = infos[i]; - if (!(info is null) && !info.IsEmpty) + if (info is not null && !info.IsEmpty) mask |= 1UL << i; } return mask; diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/TablesMDHeap.cs b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/TablesMDHeap.cs index 9ca231e08d..4c4b4cae54 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/TablesMDHeap.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/TablesMDHeap.cs @@ -295,6 +295,6 @@ public override bool MustRewriteHeap() { return false; } - public override bool ExistsInMetadata => !(tablesStream.StreamHeader is null); + public override bool ExistsInMetadata => tablesStream.StreamHeader is not null; } } diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/USMDHeap.cs b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/USMDHeap.cs index 1d8fc4a4d3..abb8065657 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/USMDHeap.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/USMDHeap.cs @@ -31,6 +31,6 @@ public USMDHeap(MetadataEditor mdEditor, USStream usStream) { } public override bool MustRewriteHeap() => false; - public override bool ExistsInMetadata => !(usStream.StreamHeader is null); + public override bool ExistsInMetadata => usStream.StreamHeader is not null; } } diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/UnknownMDHeap.cs b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/UnknownMDHeap.cs index b90c9a94b2..174ea2894e 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/UnknownMDHeap.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MDEditor/UnknownMDHeap.cs @@ -31,6 +31,6 @@ public UnknownMDHeap(MetadataEditor mdEditor, DotNetStream stream) { } public override bool MustRewriteHeap() => false; - public override bool ExistsInMetadata => !(stream.StreamHeader is null); + public override bool ExistsInMetadata => stream.StreamHeader is not null; } } diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MDEditorPatcher.cs b/Extensions/dnSpy.AsmEditor/Compiler/MDEditorPatcher.cs index 53f9925a92..d826eeea6f 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MDEditorPatcher.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MDEditorPatcher.cs @@ -66,7 +66,7 @@ uint GetOrCreateTempAssemblyRid() { } public void Patch(ModuleDef module) { - if (UpdateTypeReferences && !(nonNestedEditedType is null)) { + if (UpdateTypeReferences && nonNestedEditedType is not null) { if (nonNestedEditedType.Module == module) DeleteTypeDef(mdEditor, nonNestedEditedType); PatchTypeRefsToEditedType(nonNestedEditedType); @@ -101,7 +101,7 @@ void DeleteTypeDef(MetadataEditor mdEditor, TypeDef nonNestedTypeDef) { foreach (var kv in dict) { var deletedType = kv.Value; uint resolutionScope; - if (!(deletedType.Type.DeclaringType is null)) { + if (deletedType.Type.DeclaringType is not null) { var declType = dict[deletedType.Type.DeclaringType]; resolutionScope = CodedToken.ResolutionScope.Encode(new MDToken(Table.TypeRef, declType.TypeRefRid)); } @@ -486,7 +486,7 @@ uint PatchTypeSignature(Dictionary typeSigDict, uint sig) { return newSig; var data = MDSigPatcher.PatchTypeSignature(sigBuilder, remappedTypeTokens, moduleData, (uint)mdEditor.RealMetadata.BlobStream.StartOffset, sig); - if (!(data is null)) + if (data is not null) newSig = mdEditor.BlobHeap.Create(data); else newSig = sig; @@ -504,7 +504,7 @@ uint PatchCallingConventionSignature(Dictionary callConvSigDict, uin return newSig; var data = MDSigPatcher.PatchCallingConventionSignature(sigBuilder, remappedTypeTokens, moduleData, (uint)mdEditor.RealMetadata.BlobStream.StartOffset, sig); - if (!(data is null)) + if (data is not null) newSig = mdEditor.BlobHeap.Create(data); else newSig = sig; diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MDPatcherUtils.cs b/Extensions/dnSpy.AsmEditor/Compiler/MDPatcherUtils.cs index 5378f69926..f94c45fa91 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MDPatcherUtils.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MDPatcherUtils.cs @@ -68,7 +68,7 @@ public unsafe static uint ReadCompressedUInt32(ref byte* data, byte* end) { (*data++ << 8) | *data++); } - public static bool ExistsInMetadata(TypeDef? type) => !(type is null) && !(type is TypeDefUser); + public static bool ExistsInMetadata(TypeDef? type) => type is not null && !(type is TypeDefUser); public static bool ReferencesModule(ModuleDef sourceModule, ModuleDef? targetModule) { if (targetModule is null) @@ -78,7 +78,7 @@ public static bool ReferencesModule(ModuleDef sourceModule, ModuleDef? targetMod return true; var targetAssembly = targetModule.Assembly; - if (!(targetAssembly is null)) { + if (targetAssembly is not null) { // Don't compare version, there could be binding redirects var asmComparer = new AssemblyNameComparer(AssemblyNameComparerFlags.Name | AssemblyNameComparerFlags.PublicKeyToken | AssemblyNameComparerFlags.Culture | AssemblyNameComparerFlags.ContentType); foreach (var asmRef in sourceModule.GetAssemblyRefs()) { diff --git a/Extensions/dnSpy.AsmEditor/Compiler/MergeWithAssemblyCommand.cs b/Extensions/dnSpy.AsmEditor/Compiler/MergeWithAssemblyCommand.cs index 853dbd5dea..98d5e17eab 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/MergeWithAssemblyCommand.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/MergeWithAssemblyCommand.cs @@ -95,7 +95,7 @@ sealed class CodeCommand : NodesCodeContextMenuHandler { public override void Execute(CodeContext context) => MergeWithAssemblyCommand.Execute(pickFilename, addUpdatedNodesHelperProvider, undoCommandService, appService, context.Nodes); } - static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length == 1 && !(GetModuleNode(nodes[0]) is null); + static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length == 1 && GetModuleNode(nodes[0]) is not null; static ModuleDocumentNode? GetModuleNode(DocumentTreeNodeData node) { if (node is AssemblyDocumentNode asmNode) { @@ -111,11 +111,11 @@ static void Execute(IPickFilename pickFilename, Lazy extraAssemblyReferences) { IEnumerable GetAssemblies(ModuleDef module, IEnumerable extraAssemblyReferences) { var asm = module.Assembly; - if (!(asm is null)) { + if (asm is not null) { foreach (var a in GetAssemblies(asm)) yield return a; } @@ -79,7 +79,7 @@ IEnumerable GetAssemblyRefs(ModuleDef module, IEnumerable ext yield return a; foreach (var s in extraAssemblyReferences) { var info = new AssemblyNameInfo(s); - if (!(info.Version is null)) + if (info.Version is not null) yield return info; } } @@ -134,7 +134,7 @@ IEnumerable GetResolvedContractAssemblies(ModuleDef module) { checkedContractsAssemblies.Add(asmRef); var contractsAsm = module.Context.AssemblyResolver.Resolve(asmRef, module); - if (!(contractsAsm is null)) { + if (contractsAsm is not null) { yield return contractsAsm; foreach (var m in contractsAsm.Modules) { foreach (var ar in m.GetAssemblyRefs()) { @@ -150,7 +150,7 @@ IEnumerable GetResolvedContractAssemblies(ModuleDef module) { foreach (var asmRef in nonContractAsms) { cancellationToken.ThrowIfCancellationRequested(); var asm = module.Context.AssemblyResolver.Resolve(asmRef, module); - if (!(asm is null)) + if (asm is not null) yield return asm; } } diff --git a/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporter.MemberLookup.cs b/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporter.MemberLookup.cs index 7525e0920c..ad0a304c8e 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporter.MemberLookup.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporter.MemberLookup.cs @@ -92,7 +92,7 @@ public void Initialize(TypeDef targetType) { return null; foreach (var o in compiledMethod.Overrides) { var targetMethod = LookupOverride(o); - if (!(targetMethod is null)) + if (targetMethod is not null) return targetMethod.DeclaringType.Properties.First(a => a.GetMethod == targetMethod || a.SetMethod == targetMethod); } return null; @@ -109,7 +109,7 @@ public void Initialize(TypeDef targetType) { return null; foreach (var o in compiledMethod.Overrides) { var targetMethod = LookupOverride(o); - if (!(targetMethod is null)) + if (targetMethod is not null) return targetMethod.DeclaringType.Events.First(a => a.AddMethod == targetMethod || a.RemoveMethod == targetMethod || a.InvokeMethod == targetMethod); } return null; @@ -121,7 +121,7 @@ public void Initialize(TypeDef targetType) { return targetMethod; foreach (var o in compiledMethod.Overrides) { targetMethod = LookupOverride(o); - if (!(targetMethod is null)) + if (targetMethod is not null) return targetMethod; } return null; diff --git a/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporter.cs b/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporter.cs index d8e8a5f295..308bb88ab0 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporter.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporter.cs @@ -377,7 +377,7 @@ public void Import(byte[] rawGeneratedModule, DebugFileResult debugFile, ModuleI RemoveDuplicates(attributes, "System.Security.UnverifiableCodeAttribute"); NewModuleCustomAttributes = attributes.ToArray(); var asm = sourceModule.Assembly; - if (!(asm is null)) { + if (asm is not null) { NewAssemblyVersion = asm.Version; attributes.Clear(); ImportCustomAttributes(attributes, asm); @@ -387,7 +387,7 @@ public void Import(byte[] rawGeneratedModule, DebugFileResult debugFile, ModuleI if ((options & ModuleImporterOptions.ReplaceAssemblyDeclSecurities) != 0) { var asm = sourceModule.Assembly; - if (!(asm is null)) { + if (asm is not null) { var declSecs = new List(); ImportDeclSecurities(declSecs, asm); // The C# compiler always adds this security attribute: @@ -417,12 +417,12 @@ public void Import(byte[] rawGeneratedModule, DebugFileResult debugFile, ModuleI public void Import(byte[] rawGeneratedModule, DebugFileResult debugFile, TypeDef targetType) { if (targetType.Module != targetModule) throw new InvalidOperationException(); - if (!(targetType.DeclaringType is null)) + if (targetType.DeclaringType is not null) throw new ArgumentException("Type must not be nested"); SetSourceModule(LoadModule(rawGeneratedModule, debugFile)); var newType = FindSourceType(targetType); - if (!(newType.DeclaringType is null)) + if (newType.DeclaringType is not null) throw new ArgumentException("Type must not be nested"); RenamePropEventAccessors(newType, targetType); @@ -444,7 +444,7 @@ public void Import(byte[] rawGeneratedModule, DebugFileResult debugFile, TypeDef TypeDef FindSourceType(TypeDef targetType) { var newType = sourceModule.Find(targetType.Module.Import(targetType)); - if (!(newType is null)) + if (newType is not null) return newType; AddErrorThrow(IM0010, string.Format(dnSpy_AsmEditor_Resources.ERR_IM_CouldNotFindEditedType, targetType)); @@ -460,12 +460,12 @@ TypeDef FindSourceType(TypeDef targetType) { public void ImportNewMembers(byte[] rawGeneratedModule, DebugFileResult debugFile, TypeDef targetType) { if (targetType.Module != targetModule) throw new InvalidOperationException(); - if (!(targetType.DeclaringType is null)) + if (targetType.DeclaringType is not null) throw new ArgumentException("Type must not be nested"); SetSourceModule(LoadModule(rawGeneratedModule, debugFile)); var newType = FindSourceType(targetType); - if (!(newType.DeclaringType is null)) + if (newType.DeclaringType is not null) throw new ArgumentException("Type must not be nested"); RenamePropEventAccessors(newType, targetType); @@ -564,7 +564,7 @@ MergedImportedType MergeEditedTypes(TypeDef newType, TypeDef targetType) { InitializeNewStateMachineTypes(newType); - Debug2.Assert(!(importSigComparerOptions is null)); + Debug2.Assert(importSigComparerOptions is not null); var fieldDiff = new FieldMemberDiff(importSigComparerOptions, targetModule); fieldDiff.Initialize(newType, targetType, mergedImportedType); var methodDiff = new MethodMemberDiff(importSigComparerOptions, targetModule); @@ -642,7 +642,7 @@ MergedImportedType MergeEditedTypes(TypeDef newType, TypeDef targetType) { void InitializeNewStateMachineTypes(TypeDef compiledType) { foreach (var method in compiledType.Methods) { var smType = StateMachineHelpers.GetStateMachineType(method); - if (!(smType is null)) { + if (smType is not null) { Debug.Assert(!newStateMachineTypes.Contains(smType), "Two or more methods share the same state machine type"); newStateMachineTypes.Add(smType); } @@ -667,7 +667,7 @@ public void Import(byte[] rawGeneratedModule, DebugFileResult debugFile, MethodD var newMethod = FindSourceMethod(targetMethod); var newMethodNonNestedDeclType = newMethod.DeclaringType; - while (!(newMethodNonNestedDeclType.DeclaringType is null)) + while (newMethodNonNestedDeclType.DeclaringType is not null) newMethodNonNestedDeclType = newMethodNonNestedDeclType.DeclaringType; RenamePropEventAccessors(newMethod.DeclaringType, targetMethod.DeclaringType); @@ -764,7 +764,7 @@ MethodDef FindSourceMethod(MethodDef targetMethod) { const SigComparerOptions comparerFlags = SIG_COMPARER_OPTIONS | SigComparerOptions.DontCompareTypeScope; var newMethod = newType!.FindMethod(GetMethodName(targetMethod), targetMethod.MethodSig, comparerFlags, targetMethod.Module); - if (!(newMethod is null)) + if (newMethod is not null) return newMethod; if (targetMethod.Overrides.Count != 0) { @@ -856,17 +856,17 @@ void UpdateEditedMethods() { void AddEditedMethod(MethodDef newMethod, MethodDef targetMethod) { var newBaseType = newMethod.DeclaringType; var targetBaseType = targetMethod.DeclaringType; - while (!(newBaseType.DeclaringType is null)) { + while (newBaseType.DeclaringType is not null) { if (targetBaseType is null) throw new InvalidOperationException(); newBaseType = newBaseType.DeclaringType; targetBaseType = targetBaseType.DeclaringType; } - if (targetBaseType is null || !(targetBaseType.DeclaringType is null)) + if (targetBaseType is null || targetBaseType.DeclaringType is not null) throw new InvalidOperationException(); var newStateMachineType = StateMachineHelpers.GetStateMachineType(newMethod); - if (!(newStateMachineType is null)) + if (newStateMachineType is not null) newStateMachineTypes.Add(newStateMachineType); nonNestedMergedImportedTypes.Add(AddMergedType(newBaseType, targetBaseType)); editedMethodsToFix.Add(newMethod, targetMethod); @@ -950,7 +950,7 @@ MergedImportedType MergeTypesRename(TypeDef newType, TypeDef targetType) { void RenameMergedMembers(MergedImportedType mergedType) { if (mergedType.MergeKind != MergeKind.Rename) throw new InvalidOperationException(); - Debug2.Assert(!(importSigComparerOptions is null)); + Debug2.Assert(importSigComparerOptions is not null); var existingProps = new HashSet(new ImportPropertyEqualityComparer(new ImportSigComparer(importSigComparerOptions, SIG_COMPARER_OPTIONS | SigComparerOptions.DontCompareReturnType, targetModule))); var existingMethods = new HashSet(new ImportMethodEqualityComparer(new ImportSigComparer(importSigComparerOptions, SIG_COMPARER_OPTIONS | SigComparerOptions.DontCompareReturnType, targetModule))); var existingEventsFields = new HashSet(StringComparer.Ordinal); @@ -979,9 +979,9 @@ void RenameMergedMembers(MergedImportedType mergedType) { while (existingProps.Contains(newProp)) newProp.Name = origName + "_" + (counter++).ToString(); existingProps.Add(newProp); - if (!(newProp.GetMethod is null)) + if (newProp.GetMethod is not null) suggestedNames[newProp.GetMethod] = "get_" + newProp.Name; - if (!(newProp.SetMethod is null)) + if (newProp.SetMethod is not null) suggestedNames[newProp.SetMethod] = "set_" + newProp.Name; } @@ -998,11 +998,11 @@ void RenameMergedMembers(MergedImportedType mergedType) { while (existingEventsFields.Contains(newEvent.Name)) newEvent.Name = origName + "_" + (counter++).ToString(); existingEventsFields.Add(newEvent.Name); - if (!(newEvent.AddMethod is null)) + if (newEvent.AddMethod is not null) suggestedNames[newEvent.AddMethod] = "add_" + newEvent.Name; - if (!(newEvent.RemoveMethod is null)) + if (newEvent.RemoveMethod is not null) suggestedNames[newEvent.RemoveMethod] = "remove_" + newEvent.Name; - if (!(newEvent.InvokeMethod is null)) + if (newEvent.InvokeMethod is not null) suggestedNames[newEvent.InvokeMethod] = "raise_" + newEvent.Name; } @@ -1216,11 +1216,11 @@ void AddUsedMethods(ImportedType importedType) { usedMethods.Add(m); } foreach (var p in importedType.TargetType.Events) { - if (!(p.AddMethod is null)) + if (p.AddMethod is not null) usedMethods.Add(p.AddMethod); - if (!(p.InvokeMethod is null)) + if (p.InvokeMethod is not null) usedMethods.Add(p.InvokeMethod); - if (!(p.RemoveMethod is null)) + if (p.RemoveMethod is not null) usedMethods.Add(p.RemoveMethod); foreach (var m in p.OtherMethods) usedMethods.Add(m); @@ -1228,7 +1228,7 @@ void AddUsedMethods(ImportedType importedType) { } void InitializeTypesStep1(IEnumerable importedTypes) { - Debug2.Assert(!(importSigComparerOptions is null)); + Debug2.Assert(importSigComparerOptions is not null); var memberDict = new MemberLookup(new ImportSigComparer(importSigComparerOptions, SIG_COMPARER_BASE_OPTIONS, targetModule)); foreach (var importedType in importedTypes) { var compiledType = toExtraData[importedType].CompiledType; @@ -1254,7 +1254,7 @@ void InitializeTypesStep1(IEnumerable importedTypes) { foreach (var compiledField in compiledType.Fields) { FieldDef? targetField; - if (!((targetField = memberDict.FindField(compiledField)) is null)) { + if ((targetField = memberDict.FindField(compiledField)) is not null) { memberDict.Remove(targetField); isStub.Add(compiledField); isStub.Add(targetField); @@ -1266,7 +1266,7 @@ void InitializeTypesStep1(IEnumerable importedTypes) { } foreach (var compiledMethod in compiledType.Methods) { MethodDef? targetMethod; - if (!((targetMethod = memberDict.FindMethod(compiledMethod)) is null) || editedMethodsToFix.TryGetValue(compiledMethod, out targetMethod)) { + if ((targetMethod = memberDict.FindMethod(compiledMethod)) is not null || editedMethodsToFix.TryGetValue(compiledMethod, out targetMethod)) { memberDict.Remove(targetMethod); isStub.Add(compiledMethod); isStub.Add(targetMethod); @@ -1278,7 +1278,7 @@ void InitializeTypesStep1(IEnumerable importedTypes) { } foreach (var compiledProperty in compiledType.Properties) { PropertyDef? targetProperty; - if (!((targetProperty = memberDict.FindProperty(compiledProperty)) is null)) { + if ((targetProperty = memberDict.FindProperty(compiledProperty)) is not null) { memberDict.Remove(targetProperty); isStub.Add(compiledProperty); isStub.Add(targetProperty); @@ -1290,7 +1290,7 @@ void InitializeTypesStep1(IEnumerable importedTypes) { } foreach (var compiledEvent in compiledType.Events) { EventDef? targetEvent; - if (!((targetEvent = memberDict.FindEvent(compiledEvent)) is null)) { + if ((targetEvent = memberDict.FindEvent(compiledEvent)) is not null) { memberDict.Remove(targetEvent); isStub.Add(compiledEvent); isStub.Add(targetEvent); @@ -1360,7 +1360,7 @@ void Initialize(TypeDef compiledType, TypeDef targetType, TypeDefOptions options } void InitializeTypesStep2(IEnumerable importedTypes) { - Debug2.Assert(!(importSigComparerOptions is null)); + Debug2.Assert(importSigComparerOptions is not null); var memberDict = new MemberLookup(new ImportSigComparer(importSigComparerOptions, SIG_COMPARER_BASE_OPTIONS, targetModule)); foreach (var importedType in importedTypes) { var compiledType = toExtraData[importedType].CompiledType; @@ -1389,7 +1389,7 @@ void InitializeTypesStep2(IEnumerable importedTypes) { foreach (var compiledField in compiledType.Fields) { FieldDef? targetField; - if (!((targetField = memberDict.FindField(compiledField)) is null)) { + if ((targetField = memberDict.FindField(compiledField)) is not null) { Initialize(compiledField); memberDict.Remove(targetField); } @@ -1398,7 +1398,7 @@ void InitializeTypesStep2(IEnumerable importedTypes) { } foreach (var compiledMethod in compiledType.Methods) { MethodDef? targetMethod; - if (!((targetMethod = memberDict.FindMethod(compiledMethod)!) is null) || editedMethodsToFix.TryGetValue(compiledMethod, out targetMethod)) { + if ((targetMethod = memberDict.FindMethod(compiledMethod)!) is not null || editedMethodsToFix.TryGetValue(compiledMethod, out targetMethod)) { Initialize(compiledMethod); memberDict.Remove(targetMethod); } @@ -1407,7 +1407,7 @@ void InitializeTypesStep2(IEnumerable importedTypes) { } foreach (var compiledProperty in compiledType.Properties) { PropertyDef? targetProperty; - if (!((targetProperty = memberDict.FindProperty(compiledProperty)) is null)) { + if ((targetProperty = memberDict.FindProperty(compiledProperty)) is not null) { Initialize(compiledProperty); memberDict.Remove(targetProperty); } @@ -1416,7 +1416,7 @@ void InitializeTypesStep2(IEnumerable importedTypes) { } foreach (var compiledEvent in compiledType.Events) { EventDef? targetEvent; - if (!((targetEvent = memberDict.FindEvent(compiledEvent)) is null)) { + if ((targetEvent = memberDict.FindEvent(compiledEvent)) is not null) { Initialize(compiledEvent); memberDict.Remove(targetEvent); } @@ -1488,7 +1488,7 @@ void InitializeTypesMethods(IEnumerable importedTypes) { return null; var res = TryGetTypeInTargetModule(type, out var importedType); - if (!(res is null)) + if (res is not null) return res; if (type is TypeRef tr) @@ -1564,7 +1564,7 @@ void InitializeTypesMethods(IEnumerable importedTypes) { var tr2 = (TypeRef)tr.GetNonNestedTypeRefScope(); if (IsTarget(tr2.ResolutionScope)) { td = targetModule.Find(tr); - if (!(td is null)) { + if (td is not null) { importedType = null; return td; } @@ -1609,8 +1609,8 @@ bool IsTarget(IResolutionScope scope) { bool IsTarget(ModuleRef modRef) => StringComparer.OrdinalIgnoreCase.Equals(modRef?.Name, targetModule.Name); // The type/method could be in some external assembly, eg. System.Private.CoreLib, don't return those defs. - TypeDef? TryImportTypeDef(TypeDef? type) => !(type is null) && oldTypeToNewType.TryGetValue(type, out var importedType) ? importedType.TargetType : null; - MethodDef? TryImportMethodDef(MethodDef? method) => !(method is null) && oldMethodToNewMethod.TryGetValue(method, out var importedMethod) ? importedMethod.TargetMember : null; + TypeDef? TryImportTypeDef(TypeDef? type) => type is not null && oldTypeToNewType.TryGetValue(type, out var importedType) ? importedType.TargetType : null; + MethodDef? TryImportMethodDef(MethodDef? method) => method is not null && oldMethodToNewMethod.TryGetValue(method, out var importedMethod) ? importedMethod.TargetMember : null; TypeSig? Import(TypeSig type) { if (type is null) @@ -1679,7 +1679,7 @@ bool IsTarget(IResolutionScope scope) { TypeSig CreateClassOrValueType(ITypeDefOrRef type, bool isValueType) { var corLibType = targetModule.CorLibTypes.GetCorLibTypeSig(type); - if (!(corLibType is null)) + if (corLibType is not null) return corLibType; if (isValueType) @@ -1876,7 +1876,7 @@ T Import(T sig, T old) where T : MethodBaseSig { sig.Params.Add(Import(p)); sig.GenParamCount = old.GenParamCount; var paramsAfterSentinel = sig.ParamsAfterSentinel; - if (!(paramsAfterSentinel is null)) { + if (paramsAfterSentinel is not null) { foreach (var p in old.ParamsAfterSentinel) paramsAfterSentinel.Add(Import(p)); } @@ -2019,17 +2019,17 @@ void Create(EventDef eventDef) { importedPropertyDef.Constant = Import(propDef.Constant); foreach (var m in propDef.GetMethods) { var newMethod = TryGetMethod(m); - if (!(newMethod is null)) + if (newMethod is not null) importedPropertyDef.GetMethods.Add(newMethod); } foreach (var m in propDef.SetMethods) { var newMethod = TryGetMethod(m); - if (!(newMethod is null)) + if (newMethod is not null) importedPropertyDef.SetMethods.Add(newMethod); } foreach (var m in propDef.OtherMethods) { var newMethod = TryGetMethod(m); - if (!(newMethod is null)) + if (newMethod is not null) importedPropertyDef.OtherMethods.Add(newMethod); } return importedPropertyDef; @@ -2052,24 +2052,24 @@ void Create(EventDef eventDef) { importedEventDef.EventType = Import(eventDef.EventType); importedEventDef.Attributes = eventDef.Attributes; ImportCustomAttributes(importedEventDef, eventDef); - if (!(eventDef.AddMethod is null)) { + if (eventDef.AddMethod is not null) { var newMethod = TryGetMethod(eventDef.AddMethod); - if (!(newMethod is null)) + if (newMethod is not null) importedEventDef.AddMethod = newMethod; } - if (!(eventDef.InvokeMethod is null)) { + if (eventDef.InvokeMethod is not null) { var newMethod = TryGetMethod(eventDef.InvokeMethod); - if (!(newMethod is null)) + if (newMethod is not null) importedEventDef.InvokeMethod = newMethod; } - if (!(eventDef.RemoveMethod is null)) { + if (eventDef.RemoveMethod is not null) { var newMethod = TryGetMethod(eventDef.RemoveMethod); - if (!(newMethod is null)) + if (newMethod is not null) importedEventDef.RemoveMethod = newMethod; } foreach (var m in eventDef.OtherMethods) { var newMethod = TryGetMethod(m); - if (!(newMethod is null)) + if (newMethod is not null) importedEventDef.OtherMethods.Add(newMethod); } return importedEventDef; @@ -2188,13 +2188,13 @@ void Create(EventDef eventDef) { var mr = (MemberRef)method; var td = TryGetTypeInTargetModule(mr.Class as ITypeDefOrRef, out var importedType); - if (!(td is null)) { + if (td is not null) { var targetMethod = FindMethod(td, mr); - if (!(targetMethod is null)) + if (targetMethod is not null) return targetMethod; - if (!(importedType is null)) { + if (importedType is not null) { var compiledMethod = FindMethod(toExtraData[importedType].CompiledType, mr); - if (!(compiledMethod is null)) + if (compiledMethod is not null) return oldMethodToNewMethod[compiledMethod].TargetMember; } @@ -2206,7 +2206,7 @@ void Create(EventDef eventDef) { } MethodDef? FindMethod(TypeDef targetType, MemberRef mr) { - Debug2.Assert(!(importSigComparerOptions is null)); + Debug2.Assert(importSigComparerOptions is not null); var comparer = new ImportSigComparer(importSigComparerOptions, SIG_COMPARER_OPTIONS, targetModule); foreach (var method in targetType.Methods) { if (!UTF8String.Equals(method.Name, mr.Name)) @@ -2226,13 +2226,13 @@ void Create(EventDef eventDef) { var mr = (MemberRef)field; var td = TryGetTypeInTargetModule(mr.Class as ITypeDefOrRef, out var importedType); - if (!(td is null)) { + if (td is not null) { var targetField = FindField(td, mr); - if (!(targetField is null)) + if (targetField is not null) return targetField; - if (!(importedType is null)) { + if (importedType is not null) { var compiledField = FindField(toExtraData[importedType].CompiledType, mr); - if (!(compiledField is null)) + if (compiledField is not null) return oldFieldToNewField[compiledField].TargetMember; } @@ -2244,7 +2244,7 @@ void Create(EventDef eventDef) { } FieldDef? FindField(TypeDef targetType, MemberRef mr) { - Debug2.Assert(!(importSigComparerOptions is null)); + Debug2.Assert(importSigComparerOptions is not null); var comparer = new ImportSigComparer(importSigComparerOptions, SIG_COMPARER_OPTIONS, targetModule); foreach (var field in targetType.Fields) { if (!UTF8String.Equals(field.Name, mr.Name)) diff --git a/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporterAssemblyResolver.cs b/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporterAssemblyResolver.cs index 9863a710d5..b5470f11e3 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporterAssemblyResolver.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/ModuleImporterAssemblyResolver.cs @@ -64,7 +64,7 @@ bool TryResolve(IAssembly assemblyReference, AssemblyNameComparer comparer, [Not foreach (var reference in references) { if (comparer.Equals(reference.Assembly, assemblyReference)) { assembly = GetModule(reference)?.Assembly; - if (!(assembly is null)) + if (assembly is not null) return true; } } diff --git a/Extensions/dnSpy.AsmEditor/Compiler/ModulePatcher.cs b/Extensions/dnSpy.AsmEditor/Compiler/ModulePatcher.cs index 18da499358..b02236f7a4 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/ModulePatcher.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/ModulePatcher.cs @@ -44,7 +44,7 @@ public unsafe bool Patch(ModuleDef module, out RawModuleBytes newModuleData) { // NOTE: We can't remove the type from the corlib (eg. mscorlib) because the compiler // (Roslyn) won't recognize it as the corlib if it has any AssemblyRefs. // A possible fix is to add a new netmodule to the corlib assembly. - bool fixTypeDefRefs = !(nonNestedEditedType is null) && + bool fixTypeDefRefs = nonNestedEditedType is not null && MDPatcherUtils.ExistsInMetadata(nonNestedEditedType) && MDPatcherUtils.ReferencesModule(module, nonNestedEditedType?.Module) && !module.Assembly.IsCorLib(); diff --git a/Extensions/dnSpy.AsmEditor/Compiler/RawModuleBytes.cs b/Extensions/dnSpy.AsmEditor/Compiler/RawModuleBytes.cs index 53e1a68ed3..66c4f63e70 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/RawModuleBytes.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/RawModuleBytes.cs @@ -56,7 +56,7 @@ public NativeMemoryRawModuleBytes(int size, bool isFileLayout) { } protected override void Dispose(bool disposing) { - if (!(pointer is null)) { + if (pointer is not null) { NativeMemoryAllocator.Free(pointer, size); pointer = null; size = 0; diff --git a/Extensions/dnSpy.AsmEditor/Compiler/RawModuleBytesProvider.cs b/Extensions/dnSpy.AsmEditor/Compiler/RawModuleBytesProvider.cs index a6b843b30b..5a08ba1d85 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/RawModuleBytesProvider.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/RawModuleBytesProvider.cs @@ -41,7 +41,7 @@ sealed unsafe class RawModuleBytesProviderImpl : RawModuleBytesProvider { // Try the file, if it still exists var rawData = TryReadFile(module.Location); - if (!(rawData is null)) + if (rawData is not null) return rawData; // If there's no file, use the in-memory data diff --git a/Extensions/dnSpy.AsmEditor/Compiler/RemappedTypeTokens.cs b/Extensions/dnSpy.AsmEditor/Compiler/RemappedTypeTokens.cs index acc8fedc6c..7ac58269ea 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/RemappedTypeTokens.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/RemappedTypeTokens.cs @@ -68,7 +68,7 @@ public void SetReadOnly() { public bool TryGetValue(uint token, out uint newToken) { Debug.Assert(isReadOnly); var arrayDict = this.arrayDict; - if (!(arrayDict is null)) { + if (arrayDict is not null) { // Most likely code path if (token == enclosingTypeToken) { diff --git a/Extensions/dnSpy.AsmEditor/Compiler/ResourceNodeCreator.cs b/Extensions/dnSpy.AsmEditor/Compiler/ResourceNodeCreator.cs index 82d46fec01..756f699336 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/ResourceNodeCreator.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/ResourceNodeCreator.cs @@ -31,7 +31,7 @@ sealed class ResourceNodeCreator { public ResourceNodeCreator(ResourcesFolderNode rsrcListNode, NodeAndResource[] nodes) { module = rsrcListNode.GetModule()!; - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); this.rsrcListNode = rsrcListNode; this.nodes = nodes; } diff --git a/Extensions/dnSpy.AsmEditor/Compiler/TIAHelper.cs b/Extensions/dnSpy.AsmEditor/Compiler/TIAHelper.cs index 86b1116603..a0738d4c1d 100644 --- a/Extensions/dnSpy.AsmEditor/Compiler/TIAHelper.cs +++ b/Extensions/dnSpy.AsmEditor/Compiler/TIAHelper.cs @@ -71,7 +71,7 @@ static bool stricmp(UTF8String? a, UTF8String? b) { UTF8String? scope = null, identifier = null; var tia = td.CustomAttributes.Find("System.Runtime.InteropServices.TypeIdentifierAttribute"); - if (!(tia is null)) { + if (tia is not null) { if (tia.ConstructorArguments.Count >= 2) { if (tia.ConstructorArguments[0].Type.GetElementType() != ElementType.String) return null; @@ -134,9 +134,9 @@ static byte[] Concat(byte[] a, byte b, byte[] c) { } static bool CheckEquivalent(TypeDef td) { - Debug2.Assert(!(td is null)); + Debug2.Assert(td is not null); - for (int i = 0; !(td is null) && i < 1000; i++) { + for (int i = 0; td is not null && i < 1000; i++) { if (i != 0) { var info = GetInfo(td); if (info is null) diff --git a/Extensions/dnSpy.AsmEditor/Converters/CilObjectConverter.cs b/Extensions/dnSpy.AsmEditor/Converters/CilObjectConverter.cs index 7d24493881..599f353815 100644 --- a/Extensions/dnSpy.AsmEditor/Converters/CilObjectConverter.cs +++ b/Extensions/dnSpy.AsmEditor/Converters/CilObjectConverter.cs @@ -56,7 +56,7 @@ static class Cache { public object? Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { var flags = WriteObjectFlags.None; - if (!(parameter is null)) { + if (parameter is not null) { foreach (var c in (string)parameter) { if (c == 's') flags |= WriteObjectFlags.ShortInstruction; diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/CAArgumentVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/CAArgumentVM.cs index e92db83018..1fe093bed8 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/CAArgumentVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/CAArgumentVM.cs @@ -154,7 +154,7 @@ void InitializeFrom(CAArgument arg, TypeSig? storageType) { return value; } td = tdr.ResolveTypeDef(); - if (!(td is null) && !td.IsEnum) + if (td is not null && !td.IsEnum) break; return new EnumInfo() { EnumType = tdr, @@ -186,7 +186,7 @@ void InitializeFrom(CAArgument arg, TypeSig? storageType) { if (tdr.IsSystemType()) return Null.Instance; td = tdr.ResolveTypeDef(); - if (!(td is null) && !td.IsEnum) + if (td is not null && !td.IsEnum) break; return EnumInfo.CreateNullArray(tdr); } @@ -217,7 +217,7 @@ void InitializeFrom(CAArgument arg, TypeSig? storageType) { if (tdr.IsSystemType()) return ConvertArray(elemType, oldList); td = tdr.ResolveTypeDef(); - if (!(td is null) && !td.IsEnum) + if (td is not null && !td.IsEnum) break; return ConvertEnum(elemType, oldList); } @@ -232,10 +232,10 @@ void InitializeFrom(CAArgument arg, TypeSig? storageType) { object ConvertEnum(TypeSig elemType, IList oldList) { var td = elemType.GetScopeTypeDefOrRef().ResolveTypeDef(); ElementType underlyingElemType = ElementType.End; - if (!(td is null) && td.IsEnum) + if (td is not null && td.IsEnum) underlyingElemType = td.GetEnumUnderlyingType().RemovePinnedAndModifiers().GetElementType(); if (!(ElementType.Boolean <= underlyingElemType && underlyingElemType <= ElementType.R8)) { - if (oldList.Count > 0 && !(oldList[0].Value is null)) + if (oldList.Count > 0 && oldList[0].Value is not null) underlyingElemType = ModelUtils.GetElementType(oldList[0].Value.GetType()); } @@ -337,7 +337,7 @@ CAArgument CreateCAArgument(TypeSig ownerType, object? value) { return new CAArgument(enumSig, enumInfo.Value); var res = CreateArray(enumSig, enumInfo.Value); var list = (IList?)res.Value; - if (!(list is null)) { + if (list is not null) { for (int i = 0; i < list.Count; i++) list[i] = new CAArgument(enumSig, list[i].Value); } @@ -383,7 +383,7 @@ CAArgument CreateCAArgument(TypeSig ownerType, object? value) { CAArgument CreateArray(TypeSig elemType, object? value) { var aryType = new SZArraySig(elemType); var list = value as System.Collections.IList; - Debug2.Assert(!(list is null) || value is null); + Debug2.Assert(list is not null || value is null); if (list is null) return new CAArgument(aryType, null); var ary = new List(list.Count); diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/CANamedArgumentVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/CANamedArgumentVM.cs index a9fb4ed7ac..c8c5a310cb 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/CANamedArgumentVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/CANamedArgumentVM.cs @@ -166,7 +166,7 @@ void OnConstantTypeChanged() { } void UpdateArgumentType() { - if (!(CAArgumentVM is null)) { + if (CAArgumentVM is not null) { var ct = (ConstantType)ConstantTypeEnumList.SelectedItem!; if (ct != ConstantType.Object && ct != ConstantType.ObjectArray) CAArgumentVM.ConstantTypeVM.ConstantTypeEnumList.SelectedItem = ct; @@ -181,7 +181,7 @@ void OnNamedArgTypeChanged() { } void InitializeFrom(CANamedArgument namedArg, TypeSigCreatorOptions options) { - if (!(CAArgumentVM is null)) + if (CAArgumentVM is not null) CAArgumentVM.PropertyChanged -= caArgumentVM_PropertyChanged; CAArgumentVM = new CAArgumentVM(ownerModule, namedArg.Argument, options, null); OnPropertyChanged(nameof(CAArgumentVM)); @@ -314,7 +314,7 @@ void PickEnumType() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var type = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_EnumType, new FlagsDocumentTreeNodeFilter(VisibleMembersFlags.EnumTypeDef), EnumType, ownerModule); - if (!(type is null)) + if (type is not null) EnumType = type; } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ConstantTypeVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ConstantTypeVM.cs index 67f272a545..67c94ffe97 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ConstantTypeVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ConstantTypeVM.cs @@ -254,7 +254,7 @@ public object? Value { if (ArraysCanBeNull && enumInfo.Value is null) EnumArrayIsNull = true; } else { - Debug2.Assert(!(enumInfo.Value is null) && !(enumInfo.Value is System.Collections.IList)); + Debug2.Assert(enumInfo.Value is not null && !(enumInfo.Value is System.Collections.IList)); SetSelectedItem(ConstantType.Enum); Enum.Value = enumInfo; } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/Converters/BooleanToGridrowLengthConverter.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/Converters/BooleanToGridrowLengthConverter.cs index 8010d8b70a..a8c6d68549 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/Converters/BooleanToGridrowLengthConverter.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/Converters/BooleanToGridrowLengthConverter.cs @@ -31,7 +31,7 @@ namespace dnSpy.AsmEditor.DnlibDialogs.Converters { sealed class BooleanToGridrowLengthConverter : IValueConverter { public object? Convert(object value, Type targetType, object parameter, CultureInfo culture) { double starValue = 1; - if (!(parameter is null)) + if (parameter is not null) starValue = System.Convert.ToDouble(parameter, culture); return (bool)value ? new GridLength(starValue, GridUnitType.Star) : new GridLength(0); } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/CreateTypeSigArrayVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/CreateTypeSigArrayVM.cs index 6a08f95c22..2621ea98d3 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/CreateTypeSigArrayVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/CreateTypeSigArrayVM.cs @@ -77,7 +77,7 @@ public int? RequiredCount { } int? requiredCount; - public bool IsFiniteCount => !(RequiredCount is null); + public bool IsFiniteCount => RequiredCount is not null; public bool IsUnlimitedCount => RequiredCount is null; public int NumberOfTypesLeft => RequiredCount is null ? -1 : RequiredCount.Value - TypeSigCollection.Count; public bool CanNotAddMore => !CanAddMore; @@ -114,7 +114,7 @@ void AddCurrent() { if (!AddCurrentCanExecute()) return; var typeSig = TypeSigCreator.TypeSig; - Debug2.Assert(!(typeSig is null)); + Debug2.Assert(typeSig is not null); TypeSigCollection.Add(typeSig); TypeSigCollection.SelectedIndex = TypeSigCollection.Count - 1; TypeSigCreator.TypeSig = null; @@ -123,7 +123,7 @@ void AddCurrent() { bool AddCurrentCanExecute() => IsEnabled && (IsUnlimitedCount || NumberOfTypesLeft > 0) && - !(TypeSigCreator.TypeSig is null); + TypeSigCreator.TypeSig is not null; public override bool HasError => !IsUnlimitedCount && NumberOfTypesLeft > 0; } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/CustomAttributeOptions.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/CustomAttributeOptions.cs index e4b30303c9..995599f651 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/CustomAttributeOptions.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/CustomAttributeOptions.cs @@ -39,7 +39,7 @@ public CustomAttributeOptions(CustomAttribute ca) { } public CustomAttribute Create() { - if (!(RawData is null)) + if (RawData is not null) return new CustomAttribute(Constructor, RawData); return new CustomAttribute(Constructor, ConstructorArguments, NamedArguments); } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/CustomAttributeVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/CustomAttributeVM.cs index e84a22302a..642c3ce7f9 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/CustomAttributeVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/CustomAttributeVM.cs @@ -50,7 +50,7 @@ public string TypeFullName { if (Constructor is MethodDef mdCtor) { var declType = mdCtor.DeclaringType; - if (!(declType is null)) + if (declType is not null) return declType.FullName; } @@ -152,11 +152,11 @@ void Args_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) } void Hook(NotifyCollectionChangedEventArgs e) { - if (!(e.OldItems is null)) { + if (e.OldItems is not null) { foreach (INotifyPropertyChanged? i in e.OldItems) i!.PropertyChanged -= arg_PropertyChanged; } - if (!(e.NewItems is null)) { + if (e.NewItems is not null) { foreach (INotifyPropertyChanged? i in e.NewItems) i!.PropertyChanged += arg_PropertyChanged; } @@ -183,7 +183,7 @@ void PickConstructor() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var newCtor = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_Constructor, new FlagsDocumentTreeNodeFilter(VisibleMembersFlags.InstanceConstructor), Constructor, ownerModule); - if (!(newCtor is null)) + if (newCtor is not null) Constructor = newCtor; } @@ -191,14 +191,14 @@ void PickConstructor() { public CustomAttributeOptions CreateCustomAttributeOptions() => CopyTo(new CustomAttributeOptions()); void InitializeFrom(CustomAttributeOptions options) { - IsRawData = !(options.RawData is null); + IsRawData = options.RawData is not null; RawData.Value = options.RawData!; Constructor = options.Constructor; ConstructorArguments.Clear(); var sig = Constructor is null ? null : Constructor.MethodSig; for (int i = 0; i < options.ConstructorArguments.Count; i++) { TypeSig? type = null; - if (!(sig is null) && i < sig.Params.Count) + if (sig is not null && i < sig.Params.Count) type = sig.Params[i]; ConstructorArguments.Add(new CAArgumentVM(ownerModule, options.ConstructorArguments[i], new TypeSigCreatorOptions(ownerModule, decompilerService), type)); } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/EnumDataFieldVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/EnumDataFieldVM.cs index 4f60777304..d2498ec6f3 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/EnumDataFieldVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/EnumDataFieldVM.cs @@ -40,9 +40,9 @@ struct EnumInfo { public override string ToString() { var td = EnumType.ResolveTypeDef(); - if (!(td is null)) { + if (td is not null) { var s = ModelUtils.GetEnumFieldName(td, Value); - if (!(s is null)) + if (s is not null) return $"{EnumType}.{s}"; } if (!IsArray) @@ -86,7 +86,7 @@ public ITypeDefOrRef? EnumType { enumUnderlyingTypeField = null; else { enumUnderlyingTypeField = CreateEnumUnderlyingTypeField(td.GetEnumUnderlyingType().RemovePinnedAndModifiers().GetElementType()); - if (!(enumUnderlyingTypeField is null)) { + if (enumUnderlyingTypeField is not null) { enumUnderlyingTypeField.StringValue = StringValue; ForceWriteStringValue(enumUnderlyingTypeField.StringValue); } @@ -114,7 +114,7 @@ protected EnumDataFieldVMBase(ModuleDef ownerModule, EnumInfo value, Action 0) + if (ownerMethod is not null && ownerMethod.GenericParameters.Count > 0) typeSigCreatorOptions.CanAddGenericMethodVar = true; TypeSigCreator = new TypeSigCreatorVM(typeSigCreatorOptions); diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ImplMapVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ImplMapVM.cs index 1177c376d8..9ce7de377a 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ImplMapVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ImplMapVM.cs @@ -144,7 +144,7 @@ public ImplMap? ImplMap { return ownerModule.UpdateRowId(new ImplMapUser(modRef, Name, Attributes)); } set { - IsEnabled = !(value is null); + IsEnabled = value is not null; if (value is null) return; diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ListVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ListVM.cs index baa3e60c9b..f5198dd4b7 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ListVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ListVM.cs @@ -112,7 +112,7 @@ public override void EditItem() { return; int index = Collection.SelectedIndex; var vm = EditClone(Clone(Collection[index])); - if (!(vm is null)) { + if (vm is not null) { Collection[index] = vm; Collection.SelectedIndex = index; } @@ -125,7 +125,7 @@ protected virtual void AddItem() { return; var vm = AddNew(Create()); - if (!(vm is null)) { + if (vm is not null) { var index = GetAddIndex(vm); Collection.Insert(index, vm); Collection.SelectedIndex = index; diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MarshalTypeVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MarshalTypeVM.cs index 7a021f3baf..1e318eb8cd 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MarshalTypeVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MarshalTypeVM.cs @@ -347,9 +347,9 @@ static TypeSigCreatorVM CreateTypeSigCreatorVM(ModuleDef ownerModule, IDecompile OwnerMethod = ownerMethod, NullTypeSigAllowed = allowNullTypeSig, }; - if (!(ownerType is null) && ownerType.GenericParameters.Count == 0) + if (ownerType is not null && ownerType.GenericParameters.Count == 0) typeSigCreatorOptions.CanAddGenericTypeVar = false; - if (!(ownerMethod is null) && ownerMethod.GenericParameters.Count > 0) + if (ownerMethod is not null && ownerMethod.GenericParameters.Count > 0) typeSigCreatorOptions.CanAddGenericMethodVar = true; var typeSigCreator = new TypeSigCreatorVM(typeSigCreatorOptions); typeSigCreator.PropertyChanged += handler; @@ -465,7 +465,7 @@ public MarshalType? Type { throw new InvalidOperationException(); } set { - IsEnabled = !(value is null); + IsEnabled = value is not null; if (value is null) return; diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MemberPickerVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MemberPickerVM.cs index ba26cf949e..033ec51b72 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MemberPickerVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MemberPickerVM.cs @@ -64,7 +64,7 @@ public object? SelectedItem { if (selectedItem != value) { selectedItem = value; OnPropertyChanged(nameof(SelectedItem)); - if (!(value is null)) { + if (value is not null) { searchResult = null; OnPropertyChanged(nameof(SearchResult)); } @@ -77,7 +77,7 @@ public object? SelectedItem { public object? SelectedDnlibObject { get { var res = SearchResult; - if (!(res is null)) { + if (res is not null) { var obj = res.Object; if (obj is AssemblyDef && filter.GetResult((AssemblyDef)obj).IsMatch) @@ -105,7 +105,7 @@ public object? SelectedDnlibObject { } var item = documentTreeView.TreeView.FromImplNode(SelectedItem); - if (!(item is null)) { + if (item is not null) { if (item is AssemblyDocumentNode && filter.GetResult(((AssemblyDocumentNode)item).Document.AssemblyDef!).IsMatch) return ((AssemblyDocumentNode)item).Document; else if (item is ModuleDocumentNode && filter.GetResult(((ModuleDocumentNode)item).Document.ModuleDef!).IsMatch) @@ -185,7 +185,7 @@ public ISearchResult? SearchResult { if (searchResult != value) { searchResult = value; OnPropertyChanged(nameof(SearchResult)); - if (!(value is null)) { + if (value is not null) { selectedItem = null; OnPropertyChanged(nameof(SelectedItem)); } @@ -332,7 +332,7 @@ public void Clear() { void CancelSearch() { TooManyResults = false; delayedSearch.Cancel(); - if (!(fileSearcher is null)) { + if (fileSearcher is not null) { fileSearcher.Cancel(); fileSearcher = null; } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MemberRefVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MemberRefVM.cs index 241f593b9f..823fe4d854 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MemberRefVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MemberRefVM.cs @@ -116,7 +116,7 @@ void InitializeFromField() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var newField = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_Field, new FlagsDocumentTreeNodeFilter(VisibleMembersFlags.FieldDef), null, typeSigCreatorOptions.OwnerModule); - if (!(newField is null)) + if (newField is not null) InitializeFrom(new MemberRefOptions(typeSigCreatorOptions.OwnerModule.Import(newField))); } @@ -124,7 +124,7 @@ void InitializeFromMethod() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var newMethod = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_Method, new FlagsDocumentTreeNodeFilter(VisibleMembersFlags.MethodDef), null, typeSigCreatorOptions.OwnerModule); - if (!(newMethod is null)) { + if (newMethod is not null) { if (typeSigCreatorOptions.OwnerModule.Import(newMethod) is MemberRef mr) InitializeFrom(new MemberRefOptions(mr)); } @@ -134,7 +134,7 @@ void PickType() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var newType = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_Type, new FlagsDocumentTreeNodeFilter(VisibleMembersFlags.TypeDef), Class as ITypeDefOrRef, typeSigCreatorOptions.OwnerModule); - if (!(newType is null)) + if (newType is not null) Class = newType; } @@ -150,10 +150,10 @@ void PickMethodDef() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var newMethod = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_Method, new SameAssemblyDocumentTreeNodeFilter(typeSigCreatorOptions.OwnerModule, new FlagsDocumentTreeNodeFilter(VisibleMembersFlags.MethodDef)), Class as IMethod, typeSigCreatorOptions.OwnerModule); - if (!(newMethod is null)) { + if (newMethod is not null) { var md = newMethod as MethodDef; - Debug2.Assert(!(md is null)); - if (!(md is null)) + Debug2.Assert(md is not null); + if (md is not null) Class = md; } } @@ -162,9 +162,9 @@ void PickModuleRef() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var document = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_Module, new SameAssemblyDocumentTreeNodeFilter(typeSigCreatorOptions.OwnerModule, new FlagsDocumentTreeNodeFilter(VisibleMembersFlags.ModuleDef)), null, typeSigCreatorOptions.OwnerModule); - if (!(document is null)) { + if (document is not null) { var module = document.ModuleDef; - if (!(module is null)) { + if (module is not null) { var modRef = new ModuleRefUser(typeSigCreatorOptions.OwnerModule, module.Name); Class = typeSigCreatorOptions.OwnerModule.UpdateRowId(modRef); } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodDefVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodDefVM.cs index ea253f404a..f805df5ba3 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodDefVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodDefVM.cs @@ -62,6 +62,6 @@ public MethodDefVM(MethodDef? method) { return string.Empty; } - public override bool HasError => !(Method is null); + public override bool HasError => Method is not null; } } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodSigCreatorVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodSigCreatorVM.cs index 9530eb6375..6bc6d00499 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodSigCreatorVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodSigCreatorVM.cs @@ -156,7 +156,7 @@ public MethodSigCreatorVM(MethodSigCreatorOptions options) { GenericParameterCount = new UInt32VM(0, a => { HasErrorUpdated(); OnPropertyChanged(nameof(SignatureFullName)); - if (!(GenericParameterCount is null) && !GenericParameterCount.HasError) + if (GenericParameterCount is not null && !GenericParameterCount.HasError) IsGeneric = GenericParameterCount.Value != 0; }) { Min = ModelUtils.COMPRESSED_UINT32_MIN, @@ -204,7 +204,7 @@ void WriteSignature(MethodBaseSig? sig) { ParametersCreateTypeSigArray.TypeSigCollection.AddRange(sig.Params); GenericParameterCount.Value = sig.GenParamCount; SentinelCreateTypeSigArray.TypeSigCollection.Clear(); - if (!(sig.ParamsAfterSentinel is null)) + if (sig.ParamsAfterSentinel is not null) SentinelCreateTypeSigArray.TypeSigCollection.AddRange(sig.ParamsAfterSentinel); } } @@ -214,13 +214,13 @@ void AddReturnType() { throw new InvalidOperationException(); var newTypeSig = typeSigCreator.Create(options.TypeSigCreatorOptions.Clone(dnSpy_AsmEditor_Resources.CreateReturnType), ReturnType, out bool canceled); - if (!(newTypeSig is null)) + if (newTypeSig is not null) ReturnType = newTypeSig; } protected override string? Verify(string columnName) { if (columnName == nameof(ReturnType)) - return !(ReturnType is null) ? string.Empty : dnSpy_AsmEditor_Resources.ReturnTypeRequired; + return ReturnType is not null ? string.Empty : dnSpy_AsmEditor_Resources.ReturnTypeRequired; return string.Empty; } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodSpecVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodSpecVM.cs index 0f6cd23717..04ec78dd5e 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodSpecVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/MethodSpecVM.cs @@ -83,7 +83,7 @@ void PickMethod() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var newMethod = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_Method, new FlagsDocumentTreeNodeFilter(VisibleMembersFlags.MethodDef), Method, typeSigCreatorOptions.OwnerModule); - if (!(newMethod is null)) + if (newMethod is not null) Method = newMethod; } @@ -94,7 +94,7 @@ void InitializeFrom(MethodSpecOptions options) { Method = options.Method; var gim = options.Instantiation as GenericInstMethodSig; CreateTypeSigArrayVM.TypeSigCollection.Clear(); - if (!(gim is null)) + if (gim is not null) CreateTypeSigArrayVM.TypeSigCollection.AddRange(gim.GenericArguments); CustomAttributesVM.InitializeFrom(options.CustomAttributes); } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ModelUtils.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ModelUtils.cs index 033848ece3..d1237431c4 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ModelUtils.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ModelUtils.cs @@ -29,7 +29,7 @@ static class ModelUtils { public const int COMPRESSED_INT32_MAX = 0x0FFFFFFF; public static bool IsSystemType(this ITypeDefOrRef? tdr) => - !(tdr is null) && + tdr is not null && tdr.DeclaringType is null && tdr.Namespace == "System" && tdr.Name == "Type" && @@ -59,7 +59,7 @@ public static ElementType GetElementType(Type? type) { if (td is null || value is null) return null; foreach (var fd in td.Fields) { - if (fd.IsLiteral && !(fd.Constant is null) && value.Equals(fd.Constant.Value)) + if (fd.IsLiteral && fd.Constant is not null && value.Equals(fd.Constant.Value)) return fd.Name; } return null; diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ObjectListDataFieldVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ObjectListDataFieldVM.cs index 42c4230678..59a30f5d2f 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ObjectListDataFieldVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ObjectListDataFieldVM.cs @@ -49,7 +49,7 @@ public ObjectListDataFieldVM(ModuleDef ownerModule, Action onUpdate public ObjectListDataFieldVM(ModuleDef ownerModule, IList value, Action onUpdated, TypeSigCreatorOptions? options) : base(onUpdated) { this.ownerModule = ownerModule; - if (!(options is null)) { + if (options is not null) { this.options = options.Clone(dnSpy_AsmEditor_Resources.CreateType); this.options.NullTypeSigAllowed = true; } @@ -58,7 +58,7 @@ public ObjectListDataFieldVM(ModuleDef ownerModule, IList value, Action protected override string OnNewValue(IList value) { objects.Clear(); - if (!(value is null)) + if (value is not null) objects.AddRange(value); return CalculateStringValue(); } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ParamDefVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ParamDefVM.cs index bc4d60eca2..82bf3f5be1 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/ParamDefVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/ParamDefVM.cs @@ -172,7 +172,7 @@ void InitializeFrom(ParamDefOptions options) { Name = options.Name; Sequence.Value = options.Sequence; Attributes = options.Attributes; - if (!(options.Constant is null)) { + if (options.Constant is not null) { HasDefault = true; ConstantVM.Value = options.Constant.Value; } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/SecurityAttributeVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/SecurityAttributeVM.cs index 4b1c7602e2..0767bca645 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/SecurityAttributeVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/SecurityAttributeVM.cs @@ -94,11 +94,11 @@ void Args_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) } void Hook(NotifyCollectionChangedEventArgs e) { - if (!(e.OldItems is null)) { + if (e.OldItems is not null) { foreach (INotifyPropertyChanged? i in e.OldItems) i!.PropertyChanged -= arg_PropertyChanged; } - if (!(e.NewItems is null)) { + if (e.NewItems is not null) { foreach (INotifyPropertyChanged? i in e.NewItems) i!.PropertyChanged += arg_PropertyChanged; } @@ -113,7 +113,7 @@ void PickAttributeType() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var newAttrType = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_Type, new FlagsDocumentTreeNodeFilter(VisibleMembersFlags.TypeDef), AttributeType, ownerModule); - if (!(newAttrType is null)) + if (newAttrType is not null) AttributeType = newAttrType; } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeDefOrRefAndCAVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeDefOrRefAndCAVM.cs index 0d19e5b1bb..ce7ae15a76 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeDefOrRefAndCAVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeDefOrRefAndCAVM.cs @@ -43,9 +43,9 @@ public TypeDefOrRefAndCAVM(TypeDefOrRefAndCAOptions options, ModuleDef ownerModu OwnerType = ownerType, OwnerMethod = ownerMethod, }; - if (!(ownerType is null) && ownerType.GenericParameters.Count == 0) + if (ownerType is not null && ownerType.GenericParameters.Count == 0) typeSigCreatorOptions.CanAddGenericTypeVar = false; - if (!(ownerMethod is null) && ownerMethod.GenericParameters.Count > 0) + if (ownerMethod is not null && ownerMethod.GenericParameters.Count > 0) typeSigCreatorOptions.CanAddGenericMethodVar = true; TypeSigCreator = new TypeSigCreatorVM(typeSigCreatorOptions); diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeDefOrRefAndCAsVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeDefOrRefAndCAsVM.cs index c922112ee2..903e774454 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeDefOrRefAndCAsVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeDefOrRefAndCAsVM.cs @@ -34,7 +34,7 @@ public TypeDefOrRefAndCAsVM(string editString, string createString, ModuleDef ow protected override TypeDefOrRefAndCAVM Create(TModel model) { var gpc = model as GenericParamConstraint; - if (!(gpc is null)) + if (gpc is not null) return new TypeDefOrRefAndCAVM(new TypeDefOrRefAndCAOptions(gpc), OwnerModule, decompilerService, ownerType, ownerMethod); return new TypeDefOrRefAndCAVM(new TypeDefOrRefAndCAOptions((InterfaceImpl)(object)model), OwnerModule, decompilerService, ownerType, ownerMethod); } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeSigCreatorVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeSigCreatorVM.cs index bf2c12b973..5acf8ba173 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeSigCreatorVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeSigCreatorVM.cs @@ -110,11 +110,11 @@ public bool ShowTypeFullName { bool showTypeFullName = true; public bool CanAddGeneric => IsEnabled && (options.CanAddGenericTypeVar || options.CanAddGenericMethodVar); - public bool IsValidTypeSig => options.NullTypeSigAllowed || !(TypeSig is null); + public bool IsValidTypeSig => options.NullTypeSigAllowed || TypeSig is not null; public bool CanAddLeafTypeSig => IsEnabled && TypeSig is null; public bool AddingLeafTypeSig => TypeSig is null; - public bool CanAddNonLeafTypeSig => IsEnabled && !(TypeSig is PinnedSig) && !(TypeSig is null); - public bool AddingNonLeafTypeSig => !(TypeSig is null); + public bool CanAddNonLeafTypeSig => IsEnabled && !(TypeSig is PinnedSig) && TypeSig is not null; + public bool AddingNonLeafTypeSig => TypeSig is not null; public string TypeSigDnlibFullName => TypeSig is null ? "null" : TypeSig.FullName; public string TypeSigLanguageFullName { @@ -128,8 +128,8 @@ public string TypeSigLanguageFullName { } public ICommand ReinitializeCommand => new RelayCommand(a => Reinitialize()); - public ICommand ClearTypeSigCommand => new RelayCommand(a => TypeSig = null, a => IsEnabled && !(TypeSig is null)); - public ICommand RemoveLastTypeSigCommand => new RelayCommand(a => RemoveLastTypeSig(), a => IsEnabled && !(TypeSig is null)); + public ICommand ClearTypeSigCommand => new RelayCommand(a => TypeSig = null, a => IsEnabled && TypeSig is not null); + public ICommand RemoveLastTypeSigCommand => new RelayCommand(a => RemoveLastTypeSig(), a => IsEnabled && TypeSig is not null); public ICommand AddTypeDefOrRefCommand => new RelayCommand(a => AddTypeDefOrRef(), a => AddTypeDefOrRefCanExecute()); public ICommand AddGenericVarCommand => new RelayCommand(a => AddGenericVar(), a => AddGenericVarCanExecute()); public ICommand AddGenericMVarCommand => new RelayCommand(a => AddGenericMVar(), a => AddGenericMVarCanExecute()); @@ -189,7 +189,7 @@ void ShowWarning(Guid? guid, string msg) { } void RemoveLastTypeSig() { - if (!(TypeSig is null)) + if (TypeSig is not null) TypeSig = TypeSig.Next; } @@ -204,7 +204,7 @@ void RemoveLastTypeSig() { return null; var corLibSig = options.OwnerModule.CorLibTypes.GetCorLibTypeSig(type); - if (!(corLibSig is null)) + if (corLibSig is not null) return corLibSig; else { var td = type.ResolveTypeDef(); @@ -308,7 +308,7 @@ bool AddArraySigCanExecute() => void AddCModReqdSig() { var type = GetTypeSig(); - if (!(type is null)) + if (type is not null) TypeSig = new CModReqdSig(type.ToTypeDefOrRef(), TypeSig); } @@ -316,7 +316,7 @@ void AddCModReqdSig() { void AddCModOptSig() { var type = GetTypeSig(); - if (!(type is null)) + if (type is not null) TypeSig = new CModOptSig(type.ToTypeDefOrRef(), TypeSig); } diff --git a/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeSigVM.cs b/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeSigVM.cs index aa7d1a44e5..b1b0ea96a6 100644 --- a/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeSigVM.cs +++ b/Extensions/dnSpy.AsmEditor/DnlibDialogs/TypeSigVM.cs @@ -41,7 +41,7 @@ public ITypeSigCreator TypeSigCreator { protected TypeVMBase(T value, Action onUpdated, TypeSigCreatorOptions? options) : base(onUpdated) { type = default!; - if (!(options is null)) { + if (options is not null) { this.options = options.Clone(dnSpy_AsmEditor_Resources.CreateType); this.options.NullTypeSigAllowed = true; } @@ -114,7 +114,7 @@ public ITypeSigCreator TypeSigCreator { protected TypeListDataFieldVMBase(IList value, Action onUpdated, TypeSigCreatorOptions? options) : base(onUpdated) { - if (!(options is null)) { + if (options is not null) { this.options = options.Clone(dnSpy_AsmEditor_Resources.CreateType); this.options.NullTypeSigAllowed = true; } @@ -123,7 +123,7 @@ protected TypeListDataFieldVMBase(IList value, Action onUpdated, protected override string OnNewValue(IList value) { types.Clear(); - if (!(value is null)) + if (value is not null) types.AddRange(value); return CalculateStringValue(); } diff --git a/Extensions/dnSpy.AsmEditor/Event/EventDefCommands.cs b/Extensions/dnSpy.AsmEditor/Event/EventDefCommands.cs index ecc3e0a9f1..199a44b01d 100644 --- a/Extensions/dnSpy.AsmEditor/Event/EventDefCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Event/EventDefCommands.cs @@ -119,11 +119,11 @@ public ModelInfo(EventDef evt) { } static IEnumerable GetMethods(EventDef evt) { - if (!(evt.AddMethod is null)) + if (evt.AddMethod is not null) yield return evt.AddMethod; - if (!(evt.InvokeMethod is null)) + if (evt.InvokeMethod is not null) yield return evt.InvokeMethod; - if (!(evt.RemoveMethod is null)) + if (evt.RemoveMethod is not null) yield return evt.RemoveMethod; foreach (var m in evt.OtherMethods) yield return m; @@ -132,7 +132,7 @@ static IEnumerable GetMethods(EventDef evt) { public void Delete(EventNode[] nodes) { Debug2.Assert(infos is null); - if (!(infos is null)) + if (infos is not null) throw new InvalidOperationException(); infos = new ModelInfo[nodes.Length]; @@ -156,7 +156,7 @@ public void Delete(EventNode[] nodes) { } public void Restore(EventNode[] nodes) { - Debug2.Assert(!(infos is null)); + Debug2.Assert(infos is not null); if (infos is null) throw new InvalidOperationException(); Debug.Assert(infos.Length == nodes.Length); @@ -251,7 +251,7 @@ public override bool IsEnabled(CodeContext context) => static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length == 1 && - (nodes[0] is TypeNode || (!(nodes[0].TreeNode.Parent is null) && nodes[0].TreeNode.Parent!.Data is TypeNode)); + (nodes[0] is TypeNode || (nodes[0].TreeNode.Parent is not null && nodes[0].TreeNode.Parent!.Data is TypeNode)); static void Execute(Lazy undoCommandService, IAppService appService, DocumentTreeNodeData[] nodes) { if (!CanExecute(nodes)) @@ -261,12 +261,12 @@ static void Execute(Lazy undoCommandService, IAppService ap if (!(ownerNode is TypeNode)) ownerNode = (DocumentTreeNodeData)ownerNode.TreeNode.Parent!.Data; var typeNode = ownerNode as TypeNode; - Debug2.Assert(!(typeNode is null)); + Debug2.Assert(typeNode is not null); if (typeNode is null) throw new InvalidOperationException(); var module = typeNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); var options = EventDefOptions.Create("MyEvent", module.CorLibTypes.GetTypeRef("System", "EventHandler")); @@ -371,7 +371,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var eventNode = (EventNode)nodes[0]; var module = nodes[0].GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); diff --git a/Extensions/dnSpy.AsmEditor/Event/EventOptionsVM.cs b/Extensions/dnSpy.AsmEditor/Event/EventOptionsVM.cs index 57ac58fb85..9d593db3b7 100644 --- a/Extensions/dnSpy.AsmEditor/Event/EventOptionsVM.cs +++ b/Extensions/dnSpy.AsmEditor/Event/EventOptionsVM.cs @@ -42,9 +42,9 @@ public IDnlibTypePicker DnlibTypePicker { public ICommand PickAddMethodCommand => new RelayCommand(a => PickAddMethod()); public ICommand PickInvokeMethodCommand => new RelayCommand(a => PickInvokeMethod()); public ICommand PickRemoveMethodCommand => new RelayCommand(a => PickRemoveMethod()); - public ICommand ClearAddMethodCommand => new RelayCommand(a => AddMethod = null, a => !(AddMethod is null)); - public ICommand ClearInvokeMethodCommand => new RelayCommand(a => InvokeMethod = null, a => !(InvokeMethod is null)); - public ICommand ClearRemoveMethodCommand => new RelayCommand(a => RemoveMethod = null, a => !(RemoveMethod is null)); + public ICommand ClearAddMethodCommand => new RelayCommand(a => AddMethod = null, a => AddMethod is not null); + public ICommand ClearInvokeMethodCommand => new RelayCommand(a => InvokeMethod = null, a => InvokeMethod is not null); + public ICommand ClearRemoveMethodCommand => new RelayCommand(a => RemoveMethod = null, a => RemoveMethod is not null); public EventAttributes Attributes { get => attributes; @@ -150,7 +150,7 @@ public EventOptionsVM(EventDefOptions options, ModuleDef ownerModule, IDecompile CanAddGenericMethodVar = true, OwnerType = ownerType, }; - if (!(ownerType is null) && ownerType.GenericParameters.Count == 0) + if (ownerType is not null && ownerType.GenericParameters.Count == 0) typeSigCreatorOptions.CanAddGenericTypeVar = false; TypeSigCreator = new TypeSigCreatorVM(typeSigCreatorOptions); TypeSigCreator.PropertyChanged += typeSigCreator_PropertyChanged; @@ -180,19 +180,19 @@ void typeSigCreator_PropertyChanged(object? sender, PropertyChangedEventArgs e) void PickAddMethod() { var method = PickMethod(AddMethod); - if (!(method is null)) + if (method is not null) AddMethod = method; } void PickInvokeMethod() { var method = PickMethod(InvokeMethod); - if (!(method is null)) + if (method is not null) InvokeMethod = method; } void PickRemoveMethod() { var method = PickMethod(RemoveMethod); - if (!(method is null)) + if (method is not null) RemoveMethod = method; } diff --git a/Extensions/dnSpy.AsmEditor/Field/FieldDefCommands.cs b/Extensions/dnSpy.AsmEditor/Field/FieldDefCommands.cs index 91f893f933..dfecce7ca7 100644 --- a/Extensions/dnSpy.AsmEditor/Field/FieldDefCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Field/FieldDefCommands.cs @@ -121,7 +121,7 @@ public ModelInfo(FieldDef field) { public void Delete(FieldNode[] nodes) { Debug2.Assert(infos is null); - if (!(infos is null)) + if (infos is not null) throw new InvalidOperationException(); infos = new ModelInfo[nodes.Length]; @@ -136,7 +136,7 @@ public void Delete(FieldNode[] nodes) { } public void Restore(FieldNode[] nodes) { - Debug2.Assert(!(infos is null)); + Debug2.Assert(infos is not null); if (infos is null) throw new InvalidOperationException(); Debug.Assert(infos.Length == nodes.Length); @@ -228,7 +228,7 @@ public override bool IsEnabled(CodeContext context) => static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length == 1 && - (nodes[0] is TypeNode || (!(nodes[0].TreeNode.Parent is null) && nodes[0].TreeNode.Parent!.Data is TypeNode)); + (nodes[0] is TypeNode || (nodes[0].TreeNode.Parent is not null && nodes[0].TreeNode.Parent!.Data is TypeNode)); static void Execute(Lazy undoCommandService, IAppService appService, DocumentTreeNodeData[] nodes) { if (!CanExecute(nodes)) @@ -238,12 +238,12 @@ static void Execute(Lazy undoCommandService, IAppService ap if (!(ownerNode is TypeNode)) ownerNode = (DocumentTreeNodeData)ownerNode.TreeNode.Parent!.Data; var typeNode = ownerNode as TypeNode; - Debug2.Assert(!(typeNode is null)); + Debug2.Assert(typeNode is not null); if (typeNode is null) throw new InvalidOperationException(); var module = typeNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -251,7 +251,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var type = typeNode.TypeDef; if (type.IsEnum) { var ts = type.GetEnumUnderlyingType(); - if (!(ts is null)) { + if (ts is not null) { options = FieldDefOptions.Create("MyField", new FieldSig(new ValueTypeSig(typeNode.TypeDef))); options.Constant = module.UpdateRowId(new ConstantUser(ModelUtils.GetDefaultValue(ts), ts.RemovePinnedAndModifiers().GetElementType())); options.Attributes |= FieldAttributes.Literal | FieldAttributes.Static | FieldAttributes.HasDefault; @@ -378,7 +378,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var fieldNode = (FieldNode)nodes[0]; var module = nodes[0].GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -432,7 +432,7 @@ public void Execute() { } else newOptions.CopyTo(fieldNode.FieldDef); - if (!(memberRefInfos is null)) { + if (memberRefInfos is not null) { foreach (var info in memberRefInfos) info.MemberRef.Name = fieldNode.FieldDef.Name; } @@ -452,7 +452,7 @@ public void Undo() { } else origOptions.CopyTo(fieldNode.FieldDef); - if (!(memberRefInfos is null)) { + if (memberRefInfos is not null) { foreach (var info in memberRefInfos) info.MemberRef.Name = info.OrigName; } diff --git a/Extensions/dnSpy.AsmEditor/Field/FieldOptionsVM.cs b/Extensions/dnSpy.AsmEditor/Field/FieldOptionsVM.cs index aa2b25cba9..3364969886 100644 --- a/Extensions/dnSpy.AsmEditor/Field/FieldOptionsVM.cs +++ b/Extensions/dnSpy.AsmEditor/Field/FieldOptionsVM.cs @@ -176,7 +176,7 @@ public FieldOptionsVM(FieldDefOptions options, ModuleDef ownerModule, IDecompile CanAddGenericMethodVar = false, OwnerType = ownerType, }; - if (!(ownerType is null) && ownerType.GenericParameters.Count == 0) + if (ownerType is not null && ownerType.GenericParameters.Count == 0) typeSigCreatorOptions.CanAddGenericTypeVar = false; TypeSigCreator = new TypeSigCreatorVM(typeSigCreatorOptions); TypeSigCreator.PropertyChanged += typeSigCreator_PropertyChanged; @@ -240,7 +240,7 @@ void InitializeFrom(FieldDefOptions options) { RVA.Value = (uint)options.RVA; InitialValue.Value = options.InitialValue!; ImplMap = options.ImplMap; - if (!(options.Constant is null)) { + if (options.Constant is not null) { HasDefault = true; ConstantVM.Value = options.Constant.Value; } diff --git a/Extensions/dnSpy.AsmEditor/Hex/Commands.cs b/Extensions/dnSpy.AsmEditor/Hex/Commands.cs index 36d3fd0bc3..bf46974fe2 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/Commands.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/Commands.cs @@ -91,7 +91,7 @@ abstract class HexTextEditorCommand : MenuItemBase { var textRef = context.Find(); bool isDefinition = false; object? @ref = null; - if (!(textRef is null)) { + if (textRef is not null) { @ref = textRef.Reference; isDefinition = textRef.IsDefinition; } @@ -128,14 +128,14 @@ abstract class HexMenuCommand : MenuItemBase { internal static HexContext CreateContext(IDocumentTabService documentTabService) { var documentViewer = documentTabService.ActiveTab.TryGetDocumentViewer(); - if (!(documentViewer is null) && documentViewer.UIObject.IsKeyboardFocusWithin) + if (documentViewer is not null && documentViewer.UIObject.IsKeyboardFocusWithin) return CreateContext(documentViewer); if (documentTabService.DocumentTreeView.TreeView.UIObject.IsKeyboardFocusWithin) return CreateContext(documentTabService.DocumentTreeView); if (documentTabService.DocumentTreeView.TreeView.SelectedItems.Length != 0) { - if (!(documentViewer is null)) + if (documentViewer is not null) return CreateContext(documentViewer); if (UIUtils.HasSelectedChildrenFocus(documentTabService.DocumentTreeView.TreeView.UIObject as ListBox)) return CreateContext(documentTabService.DocumentTreeView); @@ -148,7 +148,7 @@ static HexContext CreateContext(IDocumentViewer documentViewer) { var refInfo = documentViewer.SelectedReference; bool isDefinition = false; object? @ref = null; - if (!(refInfo is null)) { + if (refInfo is not null) { @ref = refInfo.Value.Data.Reference; isDefinition = refInfo.Value.Data.IsDefinition; } @@ -275,7 +275,7 @@ static bool CanExecuteCommand(IDocumentTabService documentTabService, Lazy methodAnnotations, HexContext context) { var node = GetNode(documentTabService, methodAnnotations, context); - if (!(node is null)) { + if (node is not null) { var tab = documentTabService.ActiveTab; var uiContext = tab?.UIContext as HexViewDocumentTabUIContext; if (uiContext is null) @@ -285,7 +285,7 @@ internal static void ExecuteInternal(IDocumentTabService documentTabService, Laz static bool IsVisibleInternal(IDocumentTabService documentTabService, Lazy methodAnnotations, HexContext context) { var node = GetNode(documentTabService, methodAnnotations, context); - return !(node is null) && !string.IsNullOrEmpty(node.Document.Filename); + return node is not null && !string.IsNullOrEmpty(node.Document.Filename); } static DsDocumentNode? GetDocumentNode(IDocumentTabService documentTabService, Lazy methodAnnotations, HexContext context) { @@ -298,7 +298,7 @@ static bool IsVisibleInternal(IDocumentTabService documentTabService, Lazy !(GetAddressReference(context) is null); + internal static bool IsVisibleInternal(HexContext context) => GetAddressReference(context) is not null; static AddressReference? GetAddressReference(HexContext context) { if (context.Reference is null) @@ -368,10 +368,10 @@ internal static void ExecuteInternal(IDocumentTabService documentTabService, Hex if (fileNode is null) return null; var mod = fileNode.Document.ModuleDef; - if (!(mod is null) && File.Exists(mod.Location)) + if (mod is not null && File.Exists(mod.Location)) return mod.Location; var peImage = fileNode.Document.PEImage; - if (!(peImage is null) && File.Exists(peImage.Filename)) + if (peImage is not null && File.Exists(peImage.Filename)) return peImage.Filename; return null; } @@ -407,11 +407,11 @@ sealed class TheHexMenuCommand : HexMenuCommand { internal static void ExecuteInternal(IDocumentTabService documentTabService, Lazy methodAnnotations, HexContext context) { var @ref = GetAddressReference(methodAnnotations, context); - if (!(@ref is null)) + if (@ref is not null) documentTabService.FollowReference(@ref); } - internal static bool IsVisibleInternal(Lazy methodAnnotations, HexContext context) => !(GetAddressReference(methodAnnotations, context) is null); + internal static bool IsVisibleInternal(Lazy methodAnnotations, HexContext context) => GetAddressReference(methodAnnotations, context) is not null; static AddressReference? GetAddressReference(Lazy methodAnnotations, HexContext context) { if (ShowAddressReferenceInHexEditorCommand.IsVisibleInternal(context)) @@ -481,11 +481,11 @@ sealed class TheHexMenuCommand : HexMenuCommand { internal static void ExecuteInternal(IDocumentTabService documentTabService, Lazy methodAnnotations, HexContext context) { var @ref = GetAddressReference(methodAnnotations, context); - if (!(@ref is null)) + if (@ref is not null) documentTabService.FollowReference(@ref); } - internal static bool IsVisibleInternal(Lazy methodAnnotations, HexContext context) => !(GetAddressReference(methodAnnotations, context) is null); + internal static bool IsVisibleInternal(Lazy methodAnnotations, HexContext context) => GetAddressReference(methodAnnotations, context) is not null; static AddressReference? GetAddressReference(Lazy methodAnnotations, HexContext context) { if (ShowAddressReferenceInHexEditorCommand.IsVisibleInternal(context)) @@ -537,11 +537,11 @@ sealed class TheHexMenuCommand : HexMenuCommand { internal static void ExecuteInternal(IDocumentTabService documentTabService, Lazy methodAnnotations, HexContext context) { var @ref = GetAddressReference(methodAnnotations, context); - if (!(@ref is null)) + if (@ref is not null) documentTabService.FollowReference(@ref); } - internal static bool IsVisibleInternal(Lazy methodAnnotations, HexContext context) => !(GetAddressReference(methodAnnotations, context) is null); + internal static bool IsVisibleInternal(Lazy methodAnnotations, HexContext context) => GetAddressReference(methodAnnotations, context) is not null; static AddressReference? GetAddressReference(Lazy methodAnnotations, HexContext context) { if (ShowAddressReferenceInHexEditorCommand.IsVisibleInternal(context)) @@ -608,11 +608,11 @@ sealed class TheHexMenuCommand : HexMenuCommand { static void ExecuteInternal(IDocumentTabService documentTabService, Lazy methodAnnotations, HexContext context) { var @ref = GetAddressReference(methodAnnotations, context); - if (!(@ref is null)) + if (@ref is not null) documentTabService.FollowReference(@ref); } - internal static bool IsVisibleInternal(Lazy methodAnnotations, HexContext context) => !(GetAddressReference(methodAnnotations, context) is null); + internal static bool IsVisibleInternal(Lazy methodAnnotations, HexContext context) => GetAddressReference(methodAnnotations, context) is not null; static IMemberDef? ResolveDef(object? mr) { if (mr is ITypeDefOrRef) @@ -626,12 +626,12 @@ static void ExecuteInternal(IDocumentTabService documentTabService, Lazy !(GetAddressReference(context) is null); + static bool IsVisibleInternal(HexContext context) => GetAddressReference(context) is not null; static AddressReference? GetAddressReference(HexContext context) { var info = TVChangeBodyHexEditorCommand.GetMethodLengthAndOffset(context); - if (!(info is null)) + if (info is not null) return new AddressReference(info.Value.Filename, false, info.Value.Offset, info.Value.Size); return null; @@ -720,11 +720,11 @@ sealed class TheHexMenuCommand : HexMenuCommand { static void ExecuteInternal(IDocumentTabService documentTabService, HexContext context) { var @ref = GetAddressReference(context); - if (!(@ref is null)) + if (@ref is not null) documentTabService.FollowReference(@ref); } - static bool IsVisibleInternal(HexContext context) => !(GetAddressReference(context) is null); + static bool IsVisibleInternal(HexContext context) => GetAddressReference(context) is not null; static AddressReference? GetAddressReference(HexContext context) { var fd = TVShowMethodInstructionsInHexEditorCommand.GetMemberDef(context) as FieldDef; @@ -764,11 +764,11 @@ sealed class TheHexMenuCommand : HexMenuCommand { static void ExecuteInternal(IDocumentTabService documentTabService, HexContext context) { var @ref = GetAddressReference(context); - if (!(@ref is null)) + if (@ref is not null) documentTabService.FollowReference(@ref); } - static bool IsVisibleInternal(HexContext context) => !(GetAddressReference(context) is null); + static bool IsVisibleInternal(HexContext context) => GetAddressReference(context) is not null; static AddressReference? GetAddressReference(HexContext context) { if (context.Nodes is null || context.Nodes.Length != 1) @@ -776,7 +776,7 @@ static void ExecuteInternal(IDocumentTabService documentTabService, HexContext c if (context.Nodes[0] is DocumentTreeNodeData node && ResourceDataProviderUtils.GetResourceDataProvider(node) is IResourceDataProvider rsrc && rsrc.FileOffset != 0) { var mod = node.GetParentModule(); - if (!(mod is null) && File.Exists(mod.Location)) + if (mod is not null && File.Exists(mod.Location)) return new AddressReference(mod.Location, false, rsrc.FileOffset, rsrc.Length); } @@ -828,7 +828,7 @@ internal static bool IsVisibleInternal(ITVChangeBodyHexEditorCommand cmd, HexCon if (data is null) return false; var info = GetMethodLengthAndOffset(context); - return !(info is null) && info.Value.Size >= (ulong)data.Length; + return info is not null && info.Value.Size >= (ulong)data.Length; } static byte[]? GetData(ITVChangeBodyHexEditorCommand cmd, HexContext context) { @@ -1003,7 +1003,7 @@ public override void Execute(HexContext context) => case ElementType.ValueType: var td = ((ValueTypeSig)retType).TypeDefOrRef.ResolveTypeDef(); - if (!(td is null) && td.IsEnum) { + if (td is not null && td.IsEnum) { var undType = td.GetEnumUnderlyingType().RemovePinnedAndModifiers(); var et = undType.GetElementType(); if ((ElementType.Boolean <= et && et <= ElementType.R8) || et == ElementType.I || et == ElementType.U) @@ -1083,7 +1083,7 @@ static void ExecuteInternal(Lazy hexBufferService, HexContext ClipboardUtils.SetText(ClipboardUtils.ToHexString(data)); } - static bool IsVisibleInternal(HexContext context) => !(TVChangeBodyHexEditorCommand.GetMethodLengthAndOffset(context) is null); + static bool IsVisibleInternal(HexContext context) => TVChangeBodyHexEditorCommand.GetMethodLengthAndOffset(context) is not null; static byte[]? GetMethodBodyBytes(Lazy hexBufferService, HexContext context) { var info = TVChangeBodyHexEditorCommand.GetMethodLengthAndOffset(context); @@ -1169,7 +1169,7 @@ static void Execute(IDocumentTabService documentTabService) => static string GetHeaderInternal(IDocumentTabService documentTabService, HexContext context) { var tokRef = GetTokenReference(documentTabService, context); - Debug2.Assert(!(tokRef is null)); + Debug2.Assert(tokRef is not null); return string.Format(dnSpy_AsmEditor_Resources.GoToMetaDataTableRowCommand, tokRef.Token); } @@ -1181,11 +1181,11 @@ static string GetHeaderInternal(IDocumentTabService documentTabService, HexConte internal static void ExecuteInternal(IDocumentTabService documentTabService, HexContext context) { var @ref = GetTokenReference(documentTabService, context); - if (!(@ref is null)) + if (@ref is not null) documentTabService.FollowReference(@ref); } - internal static bool IsVisibleInternal(IDocumentTabService documentTabService, HexContext context) => !(GetTokenReference(documentTabService, context) is null); + internal static bool IsVisibleInternal(IDocumentTabService documentTabService, HexContext context) => GetTokenReference(documentTabService, context) is not null; static TokenReference? GetTokenReference(IDocumentTabService documentTabService, HexContext context) { var @ref = GetTokenReference2(context); @@ -1204,7 +1204,7 @@ internal static bool HasPENode(ModuleDocumentNode? node) { static TokenReference? GetTokenReference2(HexContext context) { if (context is null) return null; - if (!(context.Reference is null)) { + if (context.Reference is not null) { if (context.Reference is TokenReference tokRef) return tokRef; @@ -1213,14 +1213,14 @@ internal static bool HasPENode(ModuleDocumentNode? node) { if (context.Reference is Parameter p) { var pd = p.ParamDef; - if (!(pd is null) && !(pd.DeclaringMethod is null)) + if (pd is not null && pd.DeclaringMethod is not null) return CreateTokenReference(pd.DeclaringMethod.Module, pd); } } - if (!(context.Nodes is null) && context.Nodes.Length == 1) { - if (context.Nodes[0] is IMDTokenNode node && !(node.Reference is null)) { + if (context.Nodes is not null && context.Nodes.Length == 1) { + if (context.Nodes[0] is IMDTokenNode node && node.Reference is not null) { var mod = (node as TreeNodeData).GetModule(); - if (!(mod is null)) + if (mod is not null) return new TokenReference(mod, node.Reference.MDToken.Raw); } } @@ -1278,7 +1278,7 @@ static void ExecuteInternal(IDocumentTabService documentTabService, HexContext c Execute2(documentTabService, context); static bool IsVisibleInternal(HexContext context) => CanExecute(context); - static bool CanExecute(HexContext context) => !(GetModule(context, out var tab) is null); + static bool CanExecute(HexContext context) => GetModule(context, out var tab) is not null; static ModuleDef? GetModule(HexContext context, out IDocumentTab? tab) { tab = null; @@ -1289,11 +1289,11 @@ static void ExecuteInternal(IDocumentTabService documentTabService, HexContext c tab = uiContext.DocumentTab!; var content = tab.Content; var node = content.Nodes.FirstOrDefault(); - if (!(node is null)) + if (node is not null) return GetModule(GetModuleNode(node)); } - if (!(context.Nodes is null) && context.Nodes.Length == 1) + if (context.Nodes is not null && context.Nodes.Length == 1) return GetModule(GetModuleNode(context.Nodes[0])); return null; @@ -1301,7 +1301,7 @@ static void ExecuteInternal(IDocumentTabService documentTabService, HexContext c static ModuleDocumentNode? GetModuleNode(TreeNodeData node) { var modNode = node.GetModuleNode(); - if (!(modNode is null)) + if (modNode is not null) return modNode; if (node is AssemblyDocumentNode asmNode) { asmNode.TreeNode.EnsureChildrenLoaded(); @@ -1327,7 +1327,7 @@ static void Execute2(IDocumentTabService documentTabService, HexContext context) return; } - if (!(tab is null)) + if (tab is not null) tab.FollowReference(tokRef, false); else documentTabService.FollowReference(tokRef); @@ -1341,7 +1341,7 @@ static void Execute2(IDocumentTabService documentTabService, HexContext context) if (!string.IsNullOrEmpty(error)) return error; var memberRef = module.ResolveToken(token); - if (!(memberRef is null)) + if (memberRef is not null) return string.Empty; if (module is ModuleDefMD md) { var mdToken = new MDToken(token); diff --git a/Extensions/dnSpy.AsmEditor/Hex/HexAddressReferenceFileTabContentProvider.cs b/Extensions/dnSpy.AsmEditor/Hex/HexAddressReferenceFileTabContentProvider.cs index 43afd1593c..0a853904e6 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/HexAddressReferenceFileTabContentProvider.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/HexAddressReferenceFileTabContentProvider.cs @@ -43,7 +43,7 @@ sealed class HexAddressReferenceFileTabContentCreator : IReferenceDocumentTabCon var addrRef = @ref as AddressReference; if (addrRef is null) addrRef = (@ref as TextReference)?.Reference as AddressReference; - if (!(addrRef is null)) + if (addrRef is not null) return Create(addrRef, documentTabService.DocumentTreeView); return null; } @@ -62,7 +62,7 @@ void CreateHandler(ShowTabContentEventArgs e, HexViewDocumentTabContent content, Debug.Assert(e.Tab.Content == content); var uiContext = e.Tab.UIContext as HexViewDocumentTabUIContext; - Debug2.Assert(!(uiContext is null)); + Debug2.Assert(uiContext is not null); if (uiContext is null || fileOffset is null) return; diff --git a/Extensions/dnSpy.AsmEditor/Hex/HexBoxDocumentTabContent.cs b/Extensions/dnSpy.AsmEditor/Hex/HexBoxDocumentTabContent.cs index bd815640be..dc8a66704f 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/HexBoxDocumentTabContent.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/HexBoxDocumentTabContent.cs @@ -127,7 +127,7 @@ sealed class HexViewDocumentTabUIContext : DocumentTabUIContext, IDisposable, IZ public HexViewDocumentTabUIContext(HexEditorGroupFactoryService hexEditorGroupFactoryService, HexBuffer buffer) => hexViewHost = hexEditorGroupFactoryService.Create(buffer, PredefinedHexViewRoles.HexEditorGroup, PredefinedHexViewRoles.HexEditorGroupDefault, new Guid(MenuConstants.GUIDOBJ_ASMEDITOR_HEXVIEW_GUID)); public override object? CreateUIState() { - if (!(cachedHexViewUIState is null)) + if (cachedHexViewUIState is not null) return cachedHexViewUIState; var state = new HexViewUIState(HexView); state.ShowOffsetColumn = HexView.Options.ShowOffsetColumn(); diff --git a/Extensions/dnSpy.AsmEditor/Hex/HexBufferService.cs b/Extensions/dnSpy.AsmEditor/Hex/HexBufferService.cs index 4289fb95e9..7c5a0a7ce8 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/HexBufferService.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/HexBufferService.cs @@ -101,7 +101,7 @@ HexBuffer[] IHexBufferService.Clear() { var buffersToDispose = new List(objs.Length); foreach (var obj in objs) { var buffer = TryGetBuffer(obj); - if (!(buffer is null)) + if (buffer is not null) buffersToDispose.Add(buffer); } foreach (var lz in hexBufferServiceListeners) @@ -126,7 +126,7 @@ HexBuffer[] IHexBufferService.Clear() { if (obj is HexBuffer buffer) return buffer; var weakRef = obj as WeakReference; - Debug2.Assert(!(weakRef is null)); + Debug2.Assert(weakRef is not null); return weakRef?.Target as HexBuffer; } @@ -138,7 +138,7 @@ HexBuffer[] IHexBufferService.Clear() { HexBuffer? buffer; lock (lockObj) { buffer = TryGet_NoLock(filename); - if (!(buffer is null)) + if (buffer is not null) return buffer; byte[] data; @@ -167,7 +167,7 @@ HexBuffer GetOrCreate(IPEImage peImage) { HexBuffer? buffer; lock (lockObj) { buffer = TryGet_NoLock(filename); - if (!(buffer is null)) + if (buffer is not null) return buffer; buffer = hexBufferFactoryService.Create(peImage.CreateReader().ToArray(), filename, hexBufferFactoryService.DefaultFileTags); diff --git a/Extensions/dnSpy.AsmEditor/Hex/HexUndoableDocumentsProvider.cs b/Extensions/dnSpy.AsmEditor/Hex/HexUndoableDocumentsProvider.cs index 498ee25a27..ac3b01df9e 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/HexUndoableDocumentsProvider.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/HexUndoableDocumentsProvider.cs @@ -34,7 +34,7 @@ sealed class HexUndoableDocumentsProvider : IUndoableDocumentsProvider, IHexBuff [ImportingConstructor] HexUndoableDocumentsProvider(Lazy hexBufferService) => this.hexBufferService = hexBufferService; - IEnumerable IUndoableDocumentsProvider.GetObjects() => hexBufferService.Value.GetBuffers().Select(a => TryGetUndoObject(a)).Where(a => !(a is null)); + IEnumerable IUndoableDocumentsProvider.GetObjects() => hexBufferService.Value.GetBuffers().Select(a => TryGetUndoObject(a)).Where(a => a is not null); IUndoObject? IUndoableDocumentsProvider.GetUndoObject(object obj) { if (obj is HexBuffer buffer) @@ -42,7 +42,7 @@ sealed class HexUndoableDocumentsProvider : IUndoableDocumentsProvider, IHexBuff return null; } - bool IUndoableDocumentsProvider.OnExecutedOneCommand(IUndoObject obj) => !(TryGetHexBuffer(obj) is null); + bool IUndoableDocumentsProvider.OnExecutedOneCommand(IUndoObject obj) => TryGetHexBuffer(obj) is not null; object? IUndoableDocumentsProvider.GetDocument(IUndoObject obj) => TryGetHexBuffer(obj); internal static HexBuffer? TryGetHexBuffer(IUndoObject? iuo) => (iuo as UndoObject)?.Value as HexBuffer; diff --git a/Extensions/dnSpy.AsmEditor/Hex/MDTableContextMenuCommands.cs b/Extensions/dnSpy.AsmEditor/Hex/MDTableContextMenuCommands.cs index bccbf6a041..2848024b75 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/MDTableContextMenuCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/MDTableContextMenuCommands.cs @@ -101,9 +101,9 @@ public CtxMenuMDTableCommandProxy(IDocumentTabService documentTabService, MenuIt MDTableContext? CreateMDTableContext() { var tab = documentTabService.ActiveTab; - if (!(tab is null)) { + if (tab is not null) { var listView = FindListView(tab); - if (!(listView is null) && UIUtils.HasSelectedChildrenFocus(listView)) + if (listView is not null && UIUtils.HasSelectedChildrenFocus(listView)) return MenuMDTableCommand.ToMDTableContext(listView, false); } @@ -112,7 +112,7 @@ public CtxMenuMDTableCommandProxy(IDocumentTabService documentTabService, MenuIt static ListView? FindListView(IDocumentTab tab) { var o = tab.UIContext.UIObject as DependencyObject; - while (!(o is null)) { + while (o is not null) { if (o is ListView lv && InitDataTemplateAP.GetInitialize(lv)) return lv; var children = UIUtils.GetChildren(o).ToArray(); @@ -131,12 +131,12 @@ event EventHandler? ICommand.CanExecuteChanged { bool ICommand.CanExecute(object? parameter) { var ctx = CreateMDTableContext(); - return !(ctx is null) && cmd.IsVisible(ctx) && cmd.IsEnabled(ctx); + return ctx is not null && cmd.IsVisible(ctx) && cmd.IsEnabled(ctx); } void ICommand.Execute(object? parameter) { var ctx = CreateMDTableContext(); - if (!(ctx is null)) + if (ctx is not null) cmd.Execute(ctx); } } @@ -233,7 +233,7 @@ internal sealed class TheMenuMDTableCommand : MenuMDTableCommand { static void ExecuteInternal(MDTableContext context) { var recVM = Ask(dnSpy_AsmEditor_Resources.GoToRowIdentifier_Title, context); - if (!(recVM is null)) + if (recVM is not null) UIUtils.ScrollSelectAndSetFocus(context.ListView, recVM); } @@ -277,11 +277,11 @@ internal sealed class TheMenuMDTableCommand : MenuMDTableCommand { static void ExecuteInternal(IDocumentTabService documentTabService, MDTableContext context) { var @ref = GetAddressReference(context); - if (!(@ref is null)) + if (@ref is not null) documentTabService.FollowReference(@ref); } - static bool IsEnabledInternal(MDTableContext context) => !(GetAddressReference(context) is null); + static bool IsEnabledInternal(MDTableContext context) => GetAddressReference(context) is not null; static AddressReference? GetAddressReference(MDTableContext context) { if (context.Records.Length == 0) @@ -390,7 +390,7 @@ static void ExecuteInternal(MDTableContext context) { HexBufferWriterHelper.Write(buffer, context.Records[0].Span.Start, data); } - static bool IsEnabledInternal(MDTableContext context) => !(GetPasteData(context) is null); + static bool IsEnabledInternal(MDTableContext context) => GetPasteData(context) is not null; static byte[]? GetPasteData(MDTableContext context) { if (context.Records.Length == 0) diff --git a/Extensions/dnSpy.AsmEditor/Hex/Nodes/HexNode.cs b/Extensions/dnSpy.AsmEditor/Hex/Nodes/HexNode.cs index b5be7695ed..5369ddb4a2 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/Nodes/HexNode.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/Nodes/HexNode.cs @@ -102,7 +102,7 @@ public virtual void OnBufferChanged(NormalizedHexChangeCollection changes) { TreeNode.EnsureChildrenLoaded(); foreach (var child in TreeNode.DataChildren.OfType()) { var node = child.FindNode(structure, field); - if (!(node is null)) + if (node is not null) return node; } diff --git a/Extensions/dnSpy.AsmEditor/Hex/Nodes/ImageCor20HeaderNode.cs b/Extensions/dnSpy.AsmEditor/Hex/Nodes/ImageCor20HeaderNode.cs index c20d383ee1..ab3f5ad330 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/Nodes/ImageCor20HeaderNode.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/Nodes/ImageCor20HeaderNode.cs @@ -38,7 +38,7 @@ protected override IEnumerable HexVMs { readonly ImageCor20HeaderVM imageCor20HeaderVM; public static ImageCor20HeaderNode? Create(ImageCor20HeaderVM? cor20) { - if (!(cor20 is null)) + if (cor20 is not null) return new ImageCor20HeaderNode(cor20); return null; } diff --git a/Extensions/dnSpy.AsmEditor/Hex/Nodes/MetadataTableRecordNode.cs b/Extensions/dnSpy.AsmEditor/Hex/Nodes/MetadataTableRecordNode.cs index ce1b80ee40..e3a152ef28 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/Nodes/MetadataTableRecordNode.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/Nodes/MetadataTableRecordNode.cs @@ -54,7 +54,7 @@ public MetadataTableRecordNode(TableInfo tableInfo, int index, HexPosition start protected override void WriteCore(ITextColorWriter output, DocumentNodeWriteOptions options) { output.Write(BoxedTextColor.Number, (index + 1).ToString()); - if (!(infoTuple is null)) { + if (infoTuple is not null) { output.WriteSpace(); output.Write(BoxedTextColor.Operator, "-"); output.WriteSpace(); @@ -63,7 +63,7 @@ protected override void WriteCore(ITextColorWriter output, DocumentNodeWriteOpti } public override void OnBufferChanged(NormalizedHexChangeCollection changes) { - if (!(infoTuple is null)) { + if (infoTuple is not null) { var tableInfo = ((MetadataTableNode)TreeNode.Parent!.Data).TableInfo; foreach (var index in infoTuple.Value.Item1) { var col = tableInfo.Columns[index]; diff --git a/Extensions/dnSpy.AsmEditor/Hex/Nodes/PENode.cs b/Extensions/dnSpy.AsmEditor/Hex/Nodes/PENode.cs index 0e99f2a218..f19b805a9c 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/Nodes/PENode.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/Nodes/PENode.cs @@ -50,7 +50,7 @@ public PENode(Func createBufferFile, PEStructureProviderFactory p public override IEnumerable CreateChildren() { Debug2.Assert(TreeNode.Children.Count == 0 && weakDocListener is null); - if (!(weakDocListener is null)) + if (weakDocListener is not null) yield break; var file = createBufferFile(); @@ -71,9 +71,9 @@ public override IEnumerable CreateChildren() { for (int i = 0; i < peStructureProvider.Sections.Length; i++) yield return new ImageSectionHeaderNode(peStructureProvider.Sections[i], i); var cor20Hdr = ImageCor20HeaderNode.Create(peStructureProvider.ImageCor20Header); - if (!(cor20Hdr is null)) + if (cor20Hdr is not null) yield return cor20Hdr; - if (!(cor20Hdr is null) && !(peStructureProvider.StorageSignature is null)) { + if (cor20Hdr is not null && peStructureProvider.StorageSignature is not null) { yield return new StorageSignatureNode(peStructureProvider.StorageSignature); yield return new StorageHeaderNode(peStructureProvider.StorageHeader!); foreach (var storageStream in peStructureProvider.StorageStreams) { @@ -142,7 +142,7 @@ public bool Decompile(IDecompileNodeContext context) { TreeNode.EnsureChildrenLoaded(); foreach (var child in TreeNode.DataChildren.OfType()) { var node = child.FindNode(structure, field); - if (!(node is null)) + if (node is not null) return node; } return null; diff --git a/Extensions/dnSpy.AsmEditor/Hex/Nodes/PETreeNodeDataProvider.cs b/Extensions/dnSpy.AsmEditor/Hex/Nodes/PETreeNodeDataProvider.cs index 3db062860b..f301901d9e 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/Nodes/PETreeNodeDataProvider.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/Nodes/PETreeNodeDataProvider.cs @@ -42,20 +42,20 @@ protected PETreeNodeDataProviderBase(Lazy hexBufferService, L public IEnumerable Create(TreeNodeDataProviderContext context) { var fileNode = context.Owner.Data as DsDocumentNode; - Debug2.Assert(!(fileNode is null)); + Debug2.Assert(fileNode is not null); if (fileNode is null) yield break; bool hasPENode = HasPENode(fileNode); var peImage = fileNode.Document.PEImage; - Debug2.Assert(!hasPENode || !(peImage is null)); - if (hasPENode && !(peImage is null)) { + Debug2.Assert(!hasPENode || peImage is not null); + if (hasPENode && peImage is not null) { Func createBufferFile = () => { var buffer = hexBufferService.Value.GetOrCreate(peImage); var service = hexBufferFileServiceFactory.Value.Create(buffer); var pePosition = HexPosition.Zero; var bufferFile = service.GetFile(pePosition, checkNestedFiles: false); - Debug2.Assert(!(bufferFile is null), "File hasn't been created"); + Debug2.Assert(bufferFile is not null, "File hasn't been created"); return bufferFile; }; yield return new PENode(createBufferFile, peStructureProviderFactory.Value); @@ -73,7 +73,7 @@ public static bool HasPENode(DsDocumentNode node) { // RVA/FileOffset won't work and the wrong data will be displayed, eg. in the .NET // storage stream nodes. bool loadedFromFile = node.Document.Key is FilenameKey; - return loadedFromFile && !(peImage is null); + return loadedFromFile && peImage is not null; } } diff --git a/Extensions/dnSpy.AsmEditor/Hex/Nodes/TablesStreamNode.cs b/Extensions/dnSpy.AsmEditor/Hex/Nodes/TablesStreamNode.cs index 01650a98db..e28a12025c 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/Nodes/TablesStreamNode.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/Nodes/TablesStreamNode.cs @@ -49,7 +49,7 @@ public TablesStreamNode(TablesStreamVM tablesStream) newChildren = new List(); foreach (var mdTable in tablesStream.MetadataTables) { - if (!(mdTable is null)) + if (mdTable is not null) newChildren.Add(new MetadataTableNode(mdTable)); } } diff --git a/Extensions/dnSpy.AsmEditor/Hex/Nodes/TokenReferenceDocumentTabContentProvider.cs b/Extensions/dnSpy.AsmEditor/Hex/Nodes/TokenReferenceDocumentTabContentProvider.cs index 46dab4976b..027c3ecb6a 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/Nodes/TokenReferenceDocumentTabContentProvider.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/Nodes/TokenReferenceDocumentTabContentProvider.cs @@ -29,7 +29,7 @@ sealed class TokenReferenceDocumentTabContentProvider : IReferenceDocumentTabCon var tokRef = @ref as TokenReference; if (tokRef is null) tokRef = (@ref as TextReference)?.Reference as TokenReference; - if (!(tokRef is null)) + if (tokRef is not null) return Create(tokRef, documentTabService); return null; } diff --git a/Extensions/dnSpy.AsmEditor/Hex/PE/HexField.cs b/Extensions/dnSpy.AsmEditor/Hex/PE/HexField.cs index 6ae4054b87..2972769234 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/PE/HexField.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/PE/HexField.cs @@ -97,7 +97,7 @@ protected void UpdateValue() { if (DataFieldVM.HasError) return; var newData = GetDataAsByteArray(); - Debug2.Assert(!(newData is null) && newData.LongLength == Span.Length); + Debug2.Assert(newData is not null && newData.LongLength == Span.Length); var origData = buffer.ReadBytes(Span.Start, newData.LongLength); if (Equals(newData, origData)) @@ -201,7 +201,7 @@ sealed class UInt32HexField : HexField { public override string FormattedValue => $"{ReadData():X8}"; public static UInt32HexField TryCreate(StructField? field, bool useDecimal = false) { - if (!(field is null)) + if (field is not null) return new UInt32HexField(field, useDecimal); return new UInt32HexField(); } diff --git a/Extensions/dnSpy.AsmEditor/Hex/PE/HexFileStructureInfoProviderImpl.cs b/Extensions/dnSpy.AsmEditor/Hex/PE/HexFileStructureInfoProviderImpl.cs index f2e340bb2a..326a2ea020 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/PE/HexFileStructureInfoProviderImpl.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/PE/HexFileStructureInfoProviderImpl.cs @@ -57,7 +57,7 @@ public static PEStructure TryCreate(PEStructureProviderFactory peStructureProvid return peStructure; var provider = peStructureProviderFactory.TryGetProvider(file); - if (!(provider is null)) + if (provider is not null) peStructure = new PEStructure(provider); file.Properties.AddProperty(typeof(PEStructure), peStructure); @@ -72,25 +72,25 @@ public static PEStructure TryCreate(PEStructureProviderFactory peStructureProvid peStructureProvider.ImageFileHeader, peStructureProvider.ImageOptionalHeader, }; - if (!(peStructureProvider.ImageCor20Header is null)) + if (peStructureProvider.ImageCor20Header is not null) list.Add(peStructureProvider.ImageCor20Header); - if (!(peStructureProvider.StorageSignature is null)) + if (peStructureProvider.StorageSignature is not null) list.Add(peStructureProvider.StorageSignature); - if (!(peStructureProvider.StorageHeader is null)) + if (peStructureProvider.StorageHeader is not null) list.Add(peStructureProvider.StorageHeader); - if (!(peStructureProvider.TablesStream is null)) + if (peStructureProvider.TablesStream is not null) list.Add(peStructureProvider.TablesStream); list.AddRange(peStructureProvider.Sections); list.AddRange(peStructureProvider.StorageStreams); hexStructures = list.ToArray(); var tblsStream = peStructureProvider.TablesStream; - if (!(tblsStream is null)) { - var first = tblsStream.MetadataTables.FirstOrDefault(a => !(a is null)); - var last = tblsStream.MetadataTables.LastOrDefault(a => !(a is null)); - Debug2.Assert(!(first is null)); - if (!(first is null)) { - Debug2.Assert(!(last is null)); + if (tblsStream is not null) { + var first = tblsStream.MetadataTables.FirstOrDefault(a => a is not null); + var last = tblsStream.MetadataTables.LastOrDefault(a => a is not null); + Debug2.Assert(first is not null); + if (first is not null) { + Debug2.Assert(last is not null); metadataTablesSpan = HexSpan.FromBounds(first.Span.Start, last.Span.End); } } @@ -143,7 +143,7 @@ public FieldAndStructure(HexVM structure, HexField field) { return null; var info = peStructure.GetField(position); - if (!(info is null)) + if (info is not null) return new HexFieldReference(file, info.Value.Structure, info.Value.Field); return null; diff --git a/Extensions/dnSpy.AsmEditor/Hex/PE/MetadataTableRecordVM.cs b/Extensions/dnSpy.AsmEditor/Hex/PE/MetadataTableRecordVM.cs index 4715acde91..60400720b5 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/PE/MetadataTableRecordVM.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/PE/MetadataTableRecordVM.cs @@ -190,7 +190,7 @@ string GetStringsDescription(HexField field) { string GetGuidDescription(HexField field) { var g = ReadGuidHeap(field); - if (!(g is null)) + if (g is not null) return $"{g.Value.ToString()} (#GUID Heap Index)"; return "#GUID Heap Index"; } @@ -348,7 +348,7 @@ public override void OnBufferChanged(NormalizedHexChangeCollection changes) { InvalidateDescription(i); } var infoCols = InfoColumnIndexes; - if (!(infoCols is null)) { + if (infoCols is not null) { foreach (var index in infoCols) { var field = hexFields[index]; if (changes.OverlapsWith(field.Span)) { diff --git a/Extensions/dnSpy.AsmEditor/Hex/PE/MetadataTableVM.cs b/Extensions/dnSpy.AsmEditor/Hex/PE/MetadataTableVM.cs index 932032ac7c..e9273b38f9 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/PE/MetadataTableVM.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/PE/MetadataTableVM.cs @@ -236,7 +236,7 @@ public override void OnBufferChanged(NormalizedHexChangeCollection changes) { Debug.Assert(0 <= i && i <= endi && endi < Collection.Count); while (i <= endi) { var obj = Collection.TryGet(i); - if (!(obj is null)) + if (obj is not null) obj.OnBufferChanged(changes); i++; } diff --git a/Extensions/dnSpy.AsmEditor/Hex/PE/PEStructureProvider.cs b/Extensions/dnSpy.AsmEditor/Hex/PE/PEStructureProvider.cs index 7128c0a8a0..11fe3930d1 100644 --- a/Extensions/dnSpy.AsmEditor/Hex/PE/PEStructureProvider.cs +++ b/Extensions/dnSpy.AsmEditor/Hex/PE/PEStructureProvider.cs @@ -110,10 +110,10 @@ public PEStructureProviderImpl(HexBufferFile file, PeHeaders peHeaders) { sections[i] = new ImageSectionHeaderVM(buffer, peHeaders.Sections[i].Data); var dnHeaders = file.GetHeaders(); storageStreams = Array.Empty(); - if (!(dnHeaders is null)) { + if (dnHeaders is not null) { imageCor20Header = new ImageCor20HeaderVM(buffer, dnHeaders.Cor20); var mdHeaders = dnHeaders.MetadataHeaders; - if (!(mdHeaders is null)) { + if (mdHeaders is not null) { storageSignature = new StorageSignatureVM(buffer, mdHeaders.MetadataHeader); storageHeader = new StorageHeaderVM(buffer, mdHeaders.MetadataHeader); storageStreams = new StorageStreamVM[mdHeaders.Streams.Count]; @@ -124,7 +124,7 @@ public PEStructureProviderImpl(HexBufferFile file, PeHeaders peHeaders) { } var metadataTables = new MetadataTableVM[0x40]; - if (!(mdHeaders.TablesStream is null)) { + if (mdHeaders.TablesStream is not null) { tablesStream = new TablesStreamVM(buffer, mdHeaders.TablesStream, metadataTables); var stringsHeapSpan = GetSpan(mdHeaders.StringsStream); var guidHeapSpan = GetSpan(mdHeaders.GUIDStream); diff --git a/Extensions/dnSpy.AsmEditor/Method/MethodDefCommands.cs b/Extensions/dnSpy.AsmEditor/Method/MethodDefCommands.cs index 28b17d6245..640508d5a7 100644 --- a/Extensions/dnSpy.AsmEditor/Method/MethodDefCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Method/MethodDefCommands.cs @@ -161,7 +161,7 @@ public void AddMethods(ICodedToken propOrEvent, PropEventType propEvtType, IList public void Delete(MethodNode[] nodes) { Debug2.Assert(infos is null); - if (!(infos is null)) + if (infos is not null) throw new InvalidOperationException(); infos = new ModelInfo[nodes.Length]; @@ -199,7 +199,7 @@ public void Delete(MethodNode[] nodes) { } public void Restore(MethodNode[] nodes) { - Debug2.Assert(!(infos is null)); + Debug2.Assert(infos is not null); if (infos is null) throw new InvalidOperationException(); Debug.Assert(infos.Length == nodes.Length); @@ -231,7 +231,7 @@ public void Restore(MethodNode[] nodes) { case ModelInfo.PropEventType.EventAdd: evt = (EventDef)pinfo.PropOrEvent; Debug2.Assert(evt.AddMethod is null); - if (!(evt.AddMethod is null)) + if (evt.AddMethod is not null) throw new InvalidOperationException(); evt.AddMethod = node.MethodDef; break; @@ -239,7 +239,7 @@ public void Restore(MethodNode[] nodes) { case ModelInfo.PropEventType.EventInvoke: evt = (EventDef)pinfo.PropOrEvent; Debug2.Assert(evt.InvokeMethod is null); - if (!(evt.InvokeMethod is null)) + if (evt.InvokeMethod is not null) throw new InvalidOperationException(); evt.InvokeMethod = node.MethodDef; break; @@ -247,7 +247,7 @@ public void Restore(MethodNode[] nodes) { case ModelInfo.PropEventType.EventRemove: evt = (EventDef)pinfo.PropOrEvent; Debug2.Assert(evt.RemoveMethod is null); - if (!(evt.RemoveMethod is null)) + if (evt.RemoveMethod is not null) throw new InvalidOperationException(); evt.RemoveMethod = node.MethodDef; break; @@ -341,7 +341,7 @@ public override bool IsEnabled(CodeContext context) => static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length == 1 && - (nodes[0] is TypeNode || (!(nodes[0].TreeNode.Parent is null) && nodes[0].TreeNode.Parent!.Data is TypeNode)); + (nodes[0] is TypeNode || (nodes[0].TreeNode.Parent is not null && nodes[0].TreeNode.Parent!.Data is TypeNode)); static void Execute(Lazy undoCommandService, IAppService appService, DocumentTreeNodeData[] nodes) { if (!CanExecute(nodes)) @@ -351,12 +351,12 @@ static void Execute(Lazy undoCommandService, IAppService ap if (!(ownerNode is TypeNode)) ownerNode = (DocumentTreeNodeData)ownerNode.TreeNode.Parent!.Data; var typeNode = ownerNode as TypeNode; - Debug2.Assert(!(typeNode is null)); + Debug2.Assert(typeNode is not null); if (typeNode is null) throw new InvalidOperationException(); var module = typeNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -466,7 +466,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var methodNode = (MethodNode)nodes[0]; var module = nodes[0].GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -520,7 +520,7 @@ public void Execute() { } else newOptions.CopyTo(methodNode.MethodDef); - if (!(memberRefInfos is null)) { + if (memberRefInfos is not null) { foreach (var info in memberRefInfos) info.MemberRef.Name = methodNode.MethodDef.Name; } @@ -540,7 +540,7 @@ public void Undo() { } else origOptions.CopyTo(methodNode.MethodDef); - if (!(memberRefInfos is null)) { + if (memberRefInfos is not null) { foreach (var info in memberRefInfos) info.MemberRef.Name = info.OrigName; } diff --git a/Extensions/dnSpy.AsmEditor/Method/MethodDefOptions.cs b/Extensions/dnSpy.AsmEditor/Method/MethodDefOptions.cs index ce37fc654f..d1cad3e480 100644 --- a/Extensions/dnSpy.AsmEditor/Method/MethodDefOptions.cs +++ b/Extensions/dnSpy.AsmEditor/Method/MethodDefOptions.cs @@ -72,7 +72,7 @@ public MethodDef CopyTo(MethodDef method) { method.GenericParameters.Clear(); method.GenericParameters.AddRange(GenericParameters); method.Overrides.Clear(); - method.Overrides.AddRange(Overrides.Select(e => !(e.MethodBody is null) ? e : new MethodOverride(method, e.MethodDeclaration))); + method.Overrides.AddRange(Overrides.Select(e => e.MethodBody is not null ? e : new MethodOverride(method, e.MethodDeclaration))); method.Parameters.UpdateParameterTypes(); return method; } diff --git a/Extensions/dnSpy.AsmEditor/Method/MethodOptionsVM.cs b/Extensions/dnSpy.AsmEditor/Method/MethodOptionsVM.cs index 2d954cc008..5d971b79ef 100644 --- a/Extensions/dnSpy.AsmEditor/Method/MethodOptionsVM.cs +++ b/Extensions/dnSpy.AsmEditor/Method/MethodOptionsVM.cs @@ -297,7 +297,7 @@ public MethodOptionsVM(MethodDefOptions options, ModuleDef ownerModule, IDecompi OwnerType = ownerType, OwnerMethod = ownerMethod, }; - if (!(ownerType is null) && ownerType.GenericParameters.Count == 0) + if (ownerType is not null && ownerType.GenericParameters.Count == 0) typeSigCreatorOptions.CanAddGenericTypeVar = false; var methodSigCreatorOptions = new MethodSigCreatorOptions(typeSigCreatorOptions); diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/BodyUtils.cs b/Extensions/dnSpy.AsmEditor/MethodBody/BodyUtils.cs index 0b4c866dc7..220924c05c 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/BodyUtils.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/BodyUtils.cs @@ -79,7 +79,7 @@ op is null || public static object? TryGetModel(Dictionary ops, object? objVm) { if (IsNull(objVm)) return null; - Debug2.Assert(!(objVm is null)); + Debug2.Assert(objVm is not null); if (!ops.TryGetValue(objVm, out var objModel)) return objVm; return objModel; @@ -529,12 +529,12 @@ public static void OptimizeBranches(this IList instrs) { } public static void WriteObject(ITextColorWriter output, object? obj, WriteObjectFlags flags = WriteObjectFlags.None) { - Debug2.Assert(!(simpleILPrinter is null)); + Debug2.Assert(simpleILPrinter is not null); if (IsNull(obj)) { output.Write(BoxedTextColor.Keyword, "null"); return; } - Debug2.Assert(!(obj is null)); + Debug2.Assert(obj is not null); if (obj is IMemberRef mr) { if (simpleILPrinter.Write(TextColorWriterToDecompilerOutput.Create(output), mr)) diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/CilBodyVM.cs b/Extensions/dnSpy.AsmEditor/MethodBody/CilBodyVM.cs index 394a6c1f5a..f1734fdc07 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/CilBodyVM.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/CilBodyVM.cs @@ -348,12 +348,12 @@ void ReplaceInstructionWithMultipleNops(InstructionVM[] instrs) { void InvertBranch(InstructionVM[] instrs) { foreach (var instr in instrs) { var code = InvertBcc(instr.Code); - if (!(code is null)) + if (code is not null) instr.Code = code.Value; } } - bool InvertBranchCanExecute(InstructionVM[] instrs) => instrs.Any(a => !(InvertBcc(a.Code) is null)); + bool InvertBranchCanExecute(InstructionVM[] instrs) => instrs.Any(a => InvertBcc(a.Code) is not null); static Code? InvertBcc(Code code) { switch (code) { @@ -462,7 +462,7 @@ void RemoveInstructionAndAddPops(InstructionVM[] instrs) { } } - bool RemoveInstructionAndAddPopsCanExecute(InstructionVM[] instrs) => instrs.Any(a => !(GetInstructionPops(a) is null)); + bool RemoveInstructionAndAddPopsCanExecute(InstructionVM[] instrs) => instrs.Any(a => GetInstructionPops(a) is not null); readonly struct InstructionPushPopInfo { public readonly int PopCount; @@ -545,7 +545,7 @@ void AddPushDefaultValue(int count, ref int index, TypeSig? pushType) { case ElementType.ValueType: var td = ((ValueTypeSig)pushType!).TypeDefOrRef.ResolveTypeDef(); - if (!(td is null) && td.IsEnum) { + if (td is not null && td.IsEnum) { var undType = td.GetEnumUnderlyingType().RemovePinnedAndModifiers(); var et = undType.GetElementType(); if ((ElementType.Boolean <= et && et <= ElementType.R8) || et == ElementType.I || et == ElementType.U) { @@ -626,7 +626,7 @@ void AddPushDefaultValue(int count, ref int index, TypeSig? pushType) { IList? typeGenArgs = null; if (type is TypeSpec ts) { var genSig = ts.TypeSig.ToGenericInstSig(); - if (!(genSig is null)) + if (genSig is not null) typeGenArgs = genSig.GenericArguments; } if (typeGenArgs is null && methodGenArgs is null) @@ -635,7 +635,7 @@ void AddPushDefaultValue(int count, ref int index, TypeSig? pushType) { } void InstructionsListVM_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { - if (!(e.NewItems is null)) + if (e.NewItems is not null) InstallInstructionHandlers(e.NewItems); if (!InstructionsListVM.DisableAutoUpdateProps) @@ -680,7 +680,7 @@ void InstructionOperandVM_PropertyChanged(object? sender, PropertyChangedEventAr bool disableInstrOpUpdate = false; void LocalsListVM_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { - if (!(e.NewItems is null)) { + if (e.NewItems is not null) { foreach (LocalVM? local in e.NewItems) { local!.PropertyChanged -= local_PropertyChanged; local.PropertyChanged += local_PropertyChanged; @@ -701,7 +701,7 @@ void local_PropertyChanged(object? sender, PropertyChangedEventArgs e) { } void ExceptionHandlersListVM_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { - if (!(e.NewItems is null)) { + if (e.NewItems is not null) { foreach (ExceptionHandlerVM? eh in e.NewItems) { eh!.PropertyChanged -= eh_PropertyChanged; eh.PropertyChanged += eh_PropertyChanged; @@ -710,7 +710,7 @@ void ExceptionHandlersListVM_CollectionChanged(object? sender, NotifyCollectionC if (!ExceptionHandlersListVM.DisableAutoUpdateProps) { if (e.Action == NotifyCollectionChangedAction.Add) { - if (!(e.NewItems is null)) { + if (e.NewItems is not null) { foreach (ExceptionHandlerVM? eh in e.NewItems) eh!.InstructionChanged(InstructionsListVM); } diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/ExceptionHandlerVM.cs b/Extensions/dnSpy.AsmEditor/MethodBody/ExceptionHandlerVM.cs index ec6de0ba80..5019dbf82e 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/ExceptionHandlerVM.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/ExceptionHandlerVM.cs @@ -99,10 +99,10 @@ public ExceptionHandlerVM(TypeSigCreatorOptions typeSigCreatorOptions, Exception string VerifyInstruction(ListVM list) { var item = list.SelectedItem; var instr = item as InstructionVM; - if (!(item is null) && instr is null) + if (item is not null && instr is null) return dnSpy_AsmEditor_Resources.Error_OnlyInstrsCanBeSelected; - if (!(instr is null) && instr.Index == -1) + if (instr is not null && instr.Index == -1) return dnSpy_AsmEditor_Resources.Error_InstrHasBeenRemoved; return string.Empty; @@ -143,7 +143,7 @@ public void InitializeFrom(ExceptionHandlerOptions options) { } static InstructionVM? RemoveNullInstance(InstructionVM? vm) { - Debug2.Assert(!(vm is null)); + Debug2.Assert(vm is not null); if (vm is null || vm == InstructionVM.Null) return null; return vm; diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/ExceptionHandlersListHelper.cs b/Extensions/dnSpy.AsmEditor/MethodBody/ExceptionHandlersListHelper.cs index 27972d678c..eb3706c483 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/ExceptionHandlersListHelper.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/ExceptionHandlersListHelper.cs @@ -89,11 +89,11 @@ void CopyCatchTypeMDTokens(ExceptionHandlerVM[] ehs) { } } - bool CopyCatchTypeMDTokensCanExecute(ExceptionHandlerVM[] ehs) => ehs.Any(a => !(GetCatchTypeToken(a.CatchType) is null)); + bool CopyCatchTypeMDTokensCanExecute(ExceptionHandlerVM[] ehs) => ehs.Any(a => GetCatchTypeToken(a.CatchType) is not null); static uint? GetCatchTypeToken(ITypeDefOrRef? type) => type is null ? (uint?)null : type.MDToken.Raw; void coll_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { - if (!(e.NewItems is null)) + if (e.NewItems is not null) InitializeExceptionHandlers(e.NewItems); } diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/FastClickButton.cs b/Extensions/dnSpy.AsmEditor/MethodBody/FastClickButton.cs index 670408ee64..cb9ee5a610 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/FastClickButton.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/FastClickButton.cs @@ -26,7 +26,7 @@ namespace dnSpy.AsmEditor.MethodBody { sealed class FastClickButton : Button { protected override void OnClick() { var cmd = Command; - if (!(cmd is null)) { + if (cmd is not null) { if (cmd.CanExecute(CommandParameter)) cmd.Execute(CommandParameter); } diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/InstructionOperandControl.cs b/Extensions/dnSpy.AsmEditor/MethodBody/InstructionOperandControl.cs index fca7bcbdf9..869c77cdaf 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/InstructionOperandControl.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/InstructionOperandControl.cs @@ -90,9 +90,9 @@ static void OnInstructionOperandVMChanged(DependencyObject d, DependencyProperty } void OnInstructionOperandVMChanged(InstructionOperandVM oldValue, InstructionOperandVM newValue) { - if (!(oldValue is null)) + if (oldValue is not null) oldValue.PropertyChanged -= instructionOperandVM_PropertyChanged; - if (!(newValue is null)) { + if (newValue is not null) { newValue.PropertyChanged += instructionOperandVM_PropertyChanged; InitializeOperandType(newValue); } diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/InstructionOperandVM.cs b/Extensions/dnSpy.AsmEditor/MethodBody/InstructionOperandVM.cs index 61086f9990..aca204b26e 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/InstructionOperandVM.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/InstructionOperandVM.cs @@ -419,33 +419,33 @@ public void ImportFrom(ModuleDef ownerModule, InstructionOperandVM other) { break; case MethodBody.InstructionOperandType.Field: - if (!(Other is null)) { + if (Other is not null) { if (!(Other is IField)) return dnSpy_AsmEditor_Resources.Error_OpMustBeField; - if (Other is IMethod method && !(method.MethodSig is null)) + if (Other is IMethod method && method.MethodSig is not null) return dnSpy_AsmEditor_Resources.Error_OpMustBeField; } break; case MethodBody.InstructionOperandType.Method: - if (!(Other is null)) { + if (Other is not null) { if (!(Other is IMethod)) return dnSpy_AsmEditor_Resources.Error_OpMustBeMethod; - if (Other is IField field && !(field.FieldSig is null)) + if (Other is IField field && field.FieldSig is not null) return dnSpy_AsmEditor_Resources.Error_OpMustBeMethod; } break; case MethodBody.InstructionOperandType.Token: - if (!(Other is null) && !(Other is ITokenOperand)) return dnSpy_AsmEditor_Resources.Error_OpMustBeTypeMethodField; + if (Other is not null && !(Other is ITokenOperand)) return dnSpy_AsmEditor_Resources.Error_OpMustBeTypeMethodField; break; case MethodBody.InstructionOperandType.Type: - if (!(Other is null) && !(Other is ITypeDefOrRef)) return dnSpy_AsmEditor_Resources.Error_OpMustBeType; + if (Other is not null && !(Other is ITypeDefOrRef)) return dnSpy_AsmEditor_Resources.Error_OpMustBeType; break; case MethodBody.InstructionOperandType.MethodSig: - if (!(Other is null) && !(Other is MethodSig)) return dnSpy_AsmEditor_Resources.Error_OpMustBeMethodSig; + if (Other is not null && !(Other is MethodSig)) return dnSpy_AsmEditor_Resources.Error_OpMustBeMethodSig; break; case MethodBody.InstructionOperandType.SwitchTargets: @@ -453,7 +453,7 @@ public void ImportFrom(ModuleDef ownerModule, InstructionOperandVM other) { if (list is null) return dnSpy_AsmEditor_Resources.Error_OpMustBeListInstrs; foreach (var i in list) { - if (!(i is null) && i.Index == -1) + if (i is not null && i.Index == -1) return dnSpy_AsmEditor_Resources.Error_SwitchInstrTargetHasBeenRemoved; } break; diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/InstructionVM.cs b/Extensions/dnSpy.AsmEditor/MethodBody/InstructionVM.cs index 20617e0a7e..c07509f9e8 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/InstructionVM.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/InstructionVM.cs @@ -138,7 +138,7 @@ Instruction GetTempInstruction() { case InstructionOperandType.SwitchTargets: var list = InstructionOperandVM.Other as IList; - if (!(list is null)) + if (list is not null) return new Instruction(opCode, new Instruction[list.Count]); return new Instruction(opCode, Array.Empty()); diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/InstructionsListHelper.cs b/Extensions/dnSpy.AsmEditor/MethodBody/InstructionsListHelper.cs index d718891f3f..0e96bcd4d0 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/InstructionsListHelper.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/InstructionsListHelper.cs @@ -201,7 +201,7 @@ void CopyOperandMDTokens(InstructionVM[] instrs) { } } - bool CopyOperandMDTokensCanExecute(InstructionVM[] instrs) => instrs.Any(a => !(GetOperandMDToken(a.InstructionOperandVM) is null)); + bool CopyOperandMDTokensCanExecute(InstructionVM[] instrs) => instrs.Any(a => GetOperandMDToken(a.InstructionOperandVM) is not null); static uint? GetOperandMDToken(InstructionOperandVM op) { switch (op.InstructionOperandType) { @@ -236,7 +236,7 @@ void CopyOperandMDTokens(InstructionVM[] instrs) { } void coll_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { - if (!(e.NewItems is null)) + if (e.NewItems is not null) InitializeInstructions(e.NewItems); } @@ -409,7 +409,7 @@ void AddFieldMemberRef(InstructionOperandVM opvm) { MemberRef? mr = opvm.Other as MemberRef; if (opvm.Other is FieldDef fd) mr = cilBodyVM.OwnerModule.Import(fd); - if (!(mr is null) && mr.FieldSig is null) + if (mr is not null && mr.FieldSig is null) mr = null; AddMemberRef(opvm, mr, true); } @@ -428,9 +428,9 @@ void AddMethodMemberRef(InstructionOperandVM opvm) { mr = ms.Method as MemberRef; md = ms.Method as MethodDef; } - if (!(md is null)) + if (md is not null) mr = cilBodyVM.OwnerModule.Import(md); - if (!(mr is null) && mr.MethodSig is null) + if (mr is not null && mr.MethodSig is null) mr = null; AddMemberRef(opvm, mr, false); } @@ -481,7 +481,7 @@ void EditMethodSig(InstructionOperandVM opvm) { var opts = new MethodSigCreatorOptions(cilBodyVM.TypeSigCreatorOptions.Clone(dnSpy_AsmEditor_Resources.CreateMethodSig)); opts.CanHaveSentinel = true; var sig = (MethodSig?)creator.Create(opts, opvm.Other as MethodSig); - if (!(sig is null)) + if (sig is not null) opvm.Other = sig; } diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/LocalsListHelper.cs b/Extensions/dnSpy.AsmEditor/MethodBody/LocalsListHelper.cs index 018f2cc83b..607dc4325c 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/LocalsListHelper.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/LocalsListHelper.cs @@ -55,7 +55,7 @@ protected override void OnDataContextChangedInternal(object dataContext) { } void coll_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { - if (!(e.NewItems is null)) + if (e.NewItems is not null) InitializeLocals(e.NewItems); } diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/MethodBodyCommands.cs b/Extensions/dnSpy.AsmEditor/MethodBody/MethodBodyCommands.cs index 0f5458fe6d..f9d9c743c1 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/MethodBodyCommands.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/MethodBodyCommands.cs @@ -98,7 +98,7 @@ internal static void Execute(Lazy methodAnnotations, Lazy methodAnnotations, Lazy IsVisible(BodyCommandUtils.GetStatements(context, FindByTextPositionOptions.None)); static bool IsVisible(IList? list) => - !(list is null) && + list is not null && list.Count != 0 && - !(list[0].Method.Body is null) && + list[0].Method.Body is not null && list[0].Method.Body.Instructions.Count > 0; public override void Execute(IMenuItemContext context) => Execute(BodyCommandUtils.GetStatements(context, FindByTextPositionOptions.None)); diff --git a/Extensions/dnSpy.AsmEditor/MethodBody/SwitchOperandVM.cs b/Extensions/dnSpy.AsmEditor/MethodBody/SwitchOperandVM.cs index d0b203b26e..8f250b5d4a 100644 --- a/Extensions/dnSpy.AsmEditor/MethodBody/SwitchOperandVM.cs +++ b/Extensions/dnSpy.AsmEditor/MethodBody/SwitchOperandVM.cs @@ -63,7 +63,7 @@ void AppendInstruction() => public void InitializeFrom(IList? instrs) { InstructionsListVM.Clear(); - if (!(instrs is null)) + if (instrs is not null) InstructionsListVM.AddRange(instrs.Select(a => new SwitchInstructionVM(a))); SelectedIndex = InstructionsListVM.Count == 0 ? -1 : 0; } diff --git a/Extensions/dnSpy.AsmEditor/Module/ModuleCommands.cs b/Extensions/dnSpy.AsmEditor/Module/ModuleCommands.cs index d73eb6c4e3..dbcca9f18a 100644 --- a/Extensions/dnSpy.AsmEditor/Module/ModuleCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Module/ModuleCommands.cs @@ -81,7 +81,7 @@ sealed class EditMenuCommand : EditMenuHandler { public override void Execute(AsmEditorContext context) => CreateNetModuleCommand.Execute(undoCommandService, appService, context.Nodes); } - static bool CanExecute(DocumentTreeNodeData[] nodes) => !(nodes is null) && + static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes is not null && (nodes.Length == 0 || nodes.Any(a => a is DsDocumentNode)); static void Execute(Lazy undoCommandService, IAppService appService, DocumentTreeNodeData[] nodes) { @@ -150,10 +150,10 @@ sealed class EditMenuCommand : EditMenuHandler { } static bool CanExecute(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && nodes.Length > 0 && nodes.All(n => n is ModuleDocumentNode && - !(n.TreeNode.Parent is null) && + n.TreeNode.Parent is not null && !(n.TreeNode.Parent.Data is AssemblyDocumentNode)); static void Execute(Lazy undoCommandService, DocumentTreeNodeData[] nodes) { @@ -190,11 +190,11 @@ public void Execute() { var savedState = savedStates[i]; var module = node.Document.ModuleDef; - bool b = !(module is null) && module.Assembly is null; + bool b = module is not null && module.Assembly is null; Debug.Assert(b); if (!b) throw new InvalidOperationException(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); savedState.ModuleKind = module.Kind; ModuleUtils.AddToNewAssemblyDef(module, ModuleKind.Dll, out savedState.Characteristics); @@ -242,7 +242,7 @@ public void Undo() { node.Context.DocumentTreeView.TreeView.Root.Children[index] = node.TreeNode; var module = node.Document.ModuleDef; - b = !(module is null) && !(module.Assembly is null) && + b = module is not null && module.Assembly is not null && module.Assembly.Modules.Count == 1 && module.Assembly.ManifestModule == module; Debug.Assert(b); @@ -286,15 +286,15 @@ sealed class EditMenuCommand : EditMenuHandler { } static bool IsVisible(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && nodes.Length > 0 && nodes.All(n => n is AssemblyDocumentNode); static bool CanExecute(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && nodes.Length > 0 && nodes.All(n => n is AssemblyDocumentNode && - !(((AssemblyDocumentNode)n).Document.AssemblyDef is null) && + ((AssemblyDocumentNode)n).Document.AssemblyDef is not null && ((AssemblyDocumentNode)n).Document.AssemblyDef!.Modules.Count == 1); static void Execute(Lazy undoCommandService, DocumentTreeNodeData[] nodes) { @@ -319,7 +319,7 @@ sealed class SavedState { public void Execute() { Debug2.Assert(savedStates is null); - if (!(savedStates is null)) + if (savedStates is not null) throw new InvalidOperationException(); savedStates = new SavedState[nodes.Length]; for (int i = 0; i < nodes.Length; i++) { @@ -337,7 +337,7 @@ public void Execute() { node.TreeNode.Parent.Children[index] = savedState.ModuleNode.TreeNode; var module = node.Document.ModuleDef; - b = !(module is null) && !(module.Assembly is null) && + b = module is not null && module.Assembly is not null && module.Assembly.Modules.Count == 1 && module.Assembly.ManifestModule == module; Debug.Assert(b); @@ -352,7 +352,7 @@ public void Execute() { } public void Undo() { - Debug2.Assert(!(savedStates is null)); + Debug2.Assert(savedStates is not null); if (savedStates is null) throw new InvalidOperationException(); @@ -361,7 +361,7 @@ public void Undo() { var savedState = savedStates[i]; var module = node.Document.ModuleDef; - bool b = !(module is null) && module.Assembly is null; + bool b = module is not null && module.Assembly is null; Debug.Assert(b); if (!b) throw new InvalidOperationException(); @@ -387,7 +387,7 @@ public void Undo() { abstract class AddNetModuleToAssemblyCommand : IUndoCommand2 { internal static bool CanExecute(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && nodes.Length == 1 && (nodes[0] is AssemblyDocumentNode || nodes[0] is ModuleDocumentNode); @@ -409,7 +409,7 @@ protected AddNetModuleToAssemblyCommand(IUndoCommandService undoCommandService, public void Execute() { Debug2.Assert(modNode.TreeNode.Parent is null); - if (!(modNode.TreeNode.Parent is null)) + if (modNode.TreeNode.Parent is not null) throw new InvalidOperationException(); asmNode.TreeNode.EnsureChildrenLoaded(); asmNode.Document.AssemblyDef!.Modules.Add(modNode.Document.ModuleDef); @@ -420,7 +420,7 @@ public void Execute() { } public void Undo() { - Debug2.Assert(!(modNode.TreeNode.Parent is null)); + Debug2.Assert(modNode.TreeNode.Parent is not null); if (modNode.TreeNode.Parent is null) throw new InvalidOperationException(); asmNode.Document.AssemblyDef!.Modules.Remove(modNode.Document.ModuleDef); @@ -553,7 +553,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var fm = appService.DocumentTreeView.DocumentService; var file = fm.CreateDocument(DsDocumentInfo.CreateDocument(dialog.FileName), dialog.FileName, true); - if (file.ModuleDef is null || !(file.AssemblyDef is null) || !(file is IDsDotNetDocument)) { + if (file.ModuleDef is null || file.AssemblyDef is not null || !(file is IDsDotNetDocument)) { MsgBox.Instance.Show(string.Format(dnSpy_AsmEditor_Resources.Error_NotNetModule, file.Filename), MsgBoxButton.OK); if (file is IDisposable id) id.Dispose(); @@ -613,17 +613,17 @@ internal sealed class EditMenuCommand : EditMenuHandler { } static bool IsVisible(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && nodes.Length == 1 && nodes[0] is ModuleDocumentNode && - !(nodes[0].TreeNode.Parent is null) && + nodes[0].TreeNode.Parent is not null && nodes[0].TreeNode.Parent!.Data is AssemblyDocumentNode; static bool CanExecute(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && nodes.Length == 1 && nodes[0] is ModuleDocumentNode && - !(nodes[0].TreeNode.Parent is null) && + nodes[0].TreeNode.Parent is not null && nodes[0].TreeNode.Parent!.DataChildren.ToList().IndexOf(nodes[0]) > 0; static void Execute(Lazy undoCommandService, Lazy documentSaver, IAppService appService, DocumentTreeNodeData[] nodes) { @@ -645,11 +645,11 @@ static void Execute(Lazy undoCommandService, Lazy undoCommandService, ModuleDocumentNode modNode) { this.undoCommandService = undoCommandService; asmNode = (AssemblyDocumentNode)modNode.TreeNode.Parent!.Data; - Debug2.Assert(!(asmNode is null)); + Debug2.Assert(asmNode is not null); this.modNode = modNode; removeIndex = asmNode.TreeNode.DataChildren.ToList().IndexOf(modNode); Debug.Assert(removeIndex > 0); - Debug2.Assert(!(asmNode.Document.AssemblyDef is null) && + Debug2.Assert(asmNode.Document.AssemblyDef is not null && asmNode.Document.AssemblyDef.Modules.IndexOf(modNode.Document.ModuleDef) == removeIndex); removeIndexDocument = asmNode.Document.Children.IndexOf(modNode.Document); Debug.Assert(removeIndexDocument >= 0); @@ -658,7 +658,7 @@ static void Execute(Lazy undoCommandService, Lazy dnSpy_AsmEditor_Resources.RemoveNetModuleCommand; public void Execute() { - Debug2.Assert(!(modNode.TreeNode.Parent is null)); + Debug2.Assert(modNode.TreeNode.Parent is not null); if (modNode.TreeNode.Parent is null) throw new InvalidOperationException(); @@ -681,7 +681,7 @@ public void Execute() { public void Undo() { Debug2.Assert(modNode.TreeNode.Parent is null); - if (!(modNode.TreeNode.Parent is null)) + if (modNode.TreeNode.Parent is not null) throw new InvalidOperationException(); asmNode.Document.AssemblyDef!.Modules.Insert(removeIndex, modNode.Document.ModuleDef); asmNode.Document.Children.Insert(removeIndexDocument, modNode.Document); @@ -731,7 +731,7 @@ internal sealed class EditMenuCommand : EditMenuHandler { } static bool CanExecute(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && nodes.Length == 1 && nodes[0] is ModuleDocumentNode; diff --git a/Extensions/dnSpy.AsmEditor/Module/ModuleOptions.cs b/Extensions/dnSpy.AsmEditor/Module/ModuleOptions.cs index ede0a744cc..11e647f50c 100644 --- a/Extensions/dnSpy.AsmEditor/Module/ModuleOptions.cs +++ b/Extensions/dnSpy.AsmEditor/Module/ModuleOptions.cs @@ -75,7 +75,7 @@ public ModuleDef CopyTo(ModuleDef module) { module.Cor20HeaderFlags = Cor20HeaderFlags; module.Cor20HeaderRuntimeVersion = Cor20HeaderRuntimeVersion; module.TablesHeaderVersion = TablesHeaderVersion; - if (!(ManagedEntryPoint is null)) + if (ManagedEntryPoint is not null) module.ManagedEntryPoint = ManagedEntryPoint; else module.NativeEntryPoint = NativeEntryPoint; diff --git a/Extensions/dnSpy.AsmEditor/Module/ModuleOptionsVM.cs b/Extensions/dnSpy.AsmEditor/Module/ModuleOptionsVM.cs index 75cf9978f8..2f78a23325 100644 --- a/Extensions/dnSpy.AsmEditor/Module/ModuleOptionsVM.cs +++ b/Extensions/dnSpy.AsmEditor/Module/ModuleOptionsVM.cs @@ -404,7 +404,7 @@ string GetEntryPointString(int maxChars) { string s; if (ep is MethodDef method) { var declType = method.DeclaringType; - if (!(declType is null)) + if (declType is not null) s = $"{method.Name} ({declType.FullName})"; else s = method.Name; @@ -452,22 +452,22 @@ void OnClrVersionChanged() { if (clrValues is null) return; - if (!(Cor20HeaderRuntimeVersion is null)) + if (Cor20HeaderRuntimeVersion is not null) Cor20HeaderRuntimeVersion.Value = clrValues.Cor20HeaderRuntimeVersion; - if (!(TablesHeaderVersion is null)) + if (TablesHeaderVersion is not null) TablesHeaderVersion.Value = clrValues.TablesHeaderVersion; RuntimeVersion = clrValues.RuntimeVersion; } void UpdateClrVersion() { ClrVersion clrVersion = Module.ClrVersion.Unknown; - if (!(Cor20HeaderRuntimeVersion is null) && !Cor20HeaderRuntimeVersion.HasError && !(Cor20HeaderRuntimeVersion.Value is null) && - !(TablesHeaderVersion is null) && !TablesHeaderVersion.HasError && !(TablesHeaderVersion.Value is null)) { + if (Cor20HeaderRuntimeVersion is not null && !Cor20HeaderRuntimeVersion.HasError && Cor20HeaderRuntimeVersion.Value is not null && + TablesHeaderVersion is not null && !TablesHeaderVersion.HasError && TablesHeaderVersion.Value is not null) { var clrValues = ClrVersionValues.Find(Cor20HeaderRuntimeVersion.Value.Value, TablesHeaderVersion.Value.Value, RuntimeVersion); - if (!(clrValues is null)) + if (clrValues is not null) clrVersion = clrValues.ClrVersion; } - if (!(ClrVersion is null)) + if (ClrVersion is not null) ClrVersion.SelectedItem = clrVersion; } @@ -489,7 +489,7 @@ void InitializeFrom(ModuleOptions options) { ManagedEntryPoint = options.ManagedEntryPoint; NativeEntryPointRva.Value = (uint)options.NativeEntryPoint; - if (!(options.ManagedEntryPoint is null)) + if (options.ManagedEntryPoint is not null) EntryPointEnum = EntryPointType.Managed; else if (options.NativeEntryPoint != 0) EntryPointEnum = EntryPointType.Native; @@ -542,7 +542,7 @@ void PickManagedEntryPoint() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var ep = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_EntryPoint, new EntryPointDocumentTreeNodeFilter(module), ManagedEntryPoint, module); - if (!(ep is null)) { + if (ep is not null) { ManagedEntryPoint = ep; EntryPointEnum = EntryPointType.Managed; } diff --git a/Extensions/dnSpy.AsmEditor/Namespace/NamespaceCommands.cs b/Extensions/dnSpy.AsmEditor/Namespace/NamespaceCommands.cs index 36faddbe16..a4247fdbf7 100644 --- a/Extensions/dnSpy.AsmEditor/Namespace/NamespaceCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Namespace/NamespaceCommands.cs @@ -72,7 +72,7 @@ static string GetCommandName(int count) => string.Format(dnSpy_AsmEditor_Resources.DeleteNamespacesCommand, count); static bool CanExecute(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && nodes.Length > 0 && nodes.All(a => a is NamespaceNode); @@ -100,9 +100,9 @@ public ModuleInfo(ModuleDef module, int count) { } public void Delete(NamespaceNode[] nodes, DocumentTreeNodeData[] parents) { - Debug2.Assert(!(parents is null) && nodes.Length == parents.Length); + Debug2.Assert(parents is not null && nodes.Length == parents.Length); Debug2.Assert(infos is null); - if (!(infos is null)) + if (infos is not null) throw new InvalidOperationException(); infos = new ModuleInfo[nodes.Length]; @@ -110,7 +110,7 @@ public void Delete(NamespaceNode[] nodes, DocumentTreeNodeData[] parents) { for (int i = 0; i < infos.Length; i++) { var node = nodes[i]; var module = parents[i].GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -131,7 +131,7 @@ public void Delete(NamespaceNode[] nodes, DocumentTreeNodeData[] parents) { } public void Restore(NamespaceNode[] nodes, DocumentTreeNodeData[] parents) { - Debug2.Assert(!(infos is null)); + Debug2.Assert(infos is not null); if (infos is null) throw new InvalidOperationException(); Debug.Assert(infos.Length == nodes.Length); @@ -210,12 +210,12 @@ sealed class EditMenuCommand : EditMenuHandler { } static bool CanExecute(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && nodes.Length > 0 && nodes.All(a => a is NamespaceNode) && nodes.Any(a => ((NamespaceNode)a).Name != string.Empty) && IsInSameModule(nodes) && - !(nodes[0].TreeNode.Parent is null) && + nodes[0].TreeNode.Parent is not null && nodes[0].TreeNode.Parent!.DataChildren.Any(a => a is NamespaceNode && ((NamespaceNode)a).Name == string.Empty); static bool IsInSameModule(DocumentTreeNodeData[] nodes) { @@ -262,7 +262,7 @@ sealed class ModelInfo { public void Execute() { Debug2.Assert(infos is null); - if (!(infos is null)) + if (infos is not null) throw new InvalidOperationException(); nodes.Delete(); @@ -290,7 +290,7 @@ public void Execute() { } public void Undo() { - Debug2.Assert(!(infos is null)); + Debug2.Assert(infos is not null); if (infos is null) throw new InvalidOperationException(); @@ -320,7 +320,7 @@ public void Undo() { public IEnumerable ModifiedObjects { get { - if (!(nsTarget is null)) + if (nsTarget is not null) yield return nsTarget; foreach (var n in nodes.Nodes) yield return n; @@ -362,7 +362,7 @@ sealed class EditMenuCommand : EditMenuHandler { } static bool CanExecute(DocumentTreeNodeData[] nodes) => - !(nodes is null) && + nodes is not null && nodes.Length == 1 && nodes[0] is NamespaceNode; @@ -412,7 +412,7 @@ internal static TypeRefInfo[] GetTypeRefInfos(ModuleDef module, IEnumerable a is NamespaceNode && newName == ((NamespaceNode)a).Name); var module = nsNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -437,7 +437,7 @@ internal static TypeRefInfo[] GetTypeRefInfos(ModuleDef module, IEnumerable GetMethods(PropertyDef evt) { public void Delete(PropertyNode[] nodes) { Debug2.Assert(infos is null); - if (!(infos is null)) + if (infos is not null) throw new InvalidOperationException(); infos = new ModelInfo[nodes.Length]; @@ -151,7 +151,7 @@ public void Delete(PropertyNode[] nodes) { } public void Restore(PropertyNode[] nodes) { - Debug2.Assert(!(infos is null)); + Debug2.Assert(infos is not null); if (infos is null) throw new InvalidOperationException(); Debug.Assert(infos.Length == nodes.Length); @@ -246,7 +246,7 @@ public override bool IsEnabled(CodeContext context) => static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length == 1 && - (nodes[0] is TypeNode || (!(nodes[0].TreeNode.Parent is null) && nodes[0].TreeNode.Parent!.Data is TypeNode)); + (nodes[0] is TypeNode || (nodes[0].TreeNode.Parent is not null && nodes[0].TreeNode.Parent!.Data is TypeNode)); static void Execute(Lazy undoCommandService, IAppService appService, DocumentTreeNodeData[] nodes) { if (!CanExecute(nodes)) @@ -256,12 +256,12 @@ static void Execute(Lazy undoCommandService, IAppService ap if (!(ownerNode is TypeNode)) ownerNode = (DocumentTreeNodeData)ownerNode.TreeNode.Parent!.Data; var typeNode = ownerNode as TypeNode; - Debug2.Assert(!(typeNode is null)); + Debug2.Assert(typeNode is not null); if (typeNode is null) throw new InvalidOperationException(); var module = typeNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -368,7 +368,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var propNode = (PropertyNode)nodes[0]; var module = nodes[0].GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); diff --git a/Extensions/dnSpy.AsmEditor/Property/PropertyOptionsVM.cs b/Extensions/dnSpy.AsmEditor/Property/PropertyOptionsVM.cs index 5b3fa3289e..a248f7926a 100644 --- a/Extensions/dnSpy.AsmEditor/Property/PropertyOptionsVM.cs +++ b/Extensions/dnSpy.AsmEditor/Property/PropertyOptionsVM.cs @@ -109,7 +109,7 @@ public PropertyOptionsVM(PropertyDefOptions options, ModuleDef ownerModule, IDec CanAddGenericMethodVar = true, OwnerType = ownerType, }; - if (!(ownerType is null) && ownerType.GenericParameters.Count == 0) + if (ownerType is not null && ownerType.GenericParameters.Count == 0) typeSigCreatorOptions.CanAddGenericTypeVar = false; var methodSigCreatorOptions = new MethodSigCreatorOptions(typeSigCreatorOptions); methodSigCreatorOptions.IsPropertySig = true; @@ -146,7 +146,7 @@ void InitializeFrom(PropertyDefOptions options) { Attributes = options.Attributes; Name = options.Name; PropertySig = options.PropertySig; - if (!(options.Constant is null)) { + if (options.Constant is not null) { HasDefault = true; ConstantVM.Value = options.Constant.Value; } diff --git a/Extensions/dnSpy.AsmEditor/Resources/ImageResourceElementVM.cs b/Extensions/dnSpy.AsmEditor/Resources/ImageResourceElementVM.cs index bbf88c1f3e..0ed77986c9 100644 --- a/Extensions/dnSpy.AsmEditor/Resources/ImageResourceElementVM.cs +++ b/Extensions/dnSpy.AsmEditor/Resources/ImageResourceElementVM.cs @@ -74,7 +74,7 @@ void FillData() { if (openFile is null) throw new InvalidOperationException(); var newBytes = openFile.Open(PickFilenameConstants.ImagesFilter); - if (!(newBytes is null)) + if (newBytes is not null) Data = newBytes; } diff --git a/Extensions/dnSpy.AsmEditor/Resources/NodeAndResource.cs b/Extensions/dnSpy.AsmEditor/Resources/NodeAndResource.cs index 669c2c509a..e1f7c4f089 100644 --- a/Extensions/dnSpy.AsmEditor/Resources/NodeAndResource.cs +++ b/Extensions/dnSpy.AsmEditor/Resources/NodeAndResource.cs @@ -31,7 +31,7 @@ readonly struct NodeAndResource { readonly DocumentTreeNodeData node; public NodeAndResource(DocumentTreeNodeData node) { - Debug2.Assert(!(ResourceNode.GetResource(node) is null)); + Debug2.Assert(ResourceNode.GetResource(node) is not null); this.node = node; } } diff --git a/Extensions/dnSpy.AsmEditor/Resources/NodeAndResourceElement.cs b/Extensions/dnSpy.AsmEditor/Resources/NodeAndResourceElement.cs index 15256233ea..5e530b1bd6 100644 --- a/Extensions/dnSpy.AsmEditor/Resources/NodeAndResourceElement.cs +++ b/Extensions/dnSpy.AsmEditor/Resources/NodeAndResourceElement.cs @@ -31,7 +31,7 @@ readonly struct NodeAndResourceElement { readonly DocumentTreeNodeData node; public NodeAndResourceElement(DocumentTreeNodeData node) { - Debug2.Assert(!(ResourceElementNode.GetResourceElement(node) is null)); + Debug2.Assert(ResourceElementNode.GetResourceElement(node) is not null); this.node = node; } } diff --git a/Extensions/dnSpy.AsmEditor/Resources/ResourceCommands.cs b/Extensions/dnSpy.AsmEditor/Resources/ResourceCommands.cs index 9f6e9f6131..68d43c2ab7 100644 --- a/Extensions/dnSpy.AsmEditor/Resources/ResourceCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Resources/ResourceCommands.cs @@ -119,7 +119,7 @@ static string GetHeader(DocumentTreeNodeData[] nodes) { return string.Format(dnSpy_AsmEditor_Resources.DeleteResourcesCommand, nodes.Length); } - static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length > 0 && nodes.All(n => !(ResourceNode.GetResource(n) is null)); + static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length > 0 && nodes.All(n => ResourceNode.GetResource(n) is not null); static void Execute(Lazy undoCommandService, DocumentTreeNodeData[] nodes) { if (!CanExecute(nodes)) @@ -146,7 +146,7 @@ public ModelInfo(ModuleDef module, Resource rsrc) { public void Delete(DocumentTreeNodeData[] nodes, DocumentTreeNodeData[] parents) { Debug2.Assert(infos is null); - if (!(infos is null)) + if (infos is not null) throw new InvalidOperationException(); infos = new ModelInfo[nodes.Length]; @@ -155,7 +155,7 @@ public void Delete(DocumentTreeNodeData[] nodes, DocumentTreeNodeData[] parents) var node = nodes[i]; var module = parents[i].GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); var resource = ResourceNode.GetResource(node) ?? throw new InvalidOperationException(); @@ -166,7 +166,7 @@ public void Delete(DocumentTreeNodeData[] nodes, DocumentTreeNodeData[] parents) } public void Restore(DocumentTreeNodeData[] nodes) { - Debug2.Assert(!(infos is null)); + Debug2.Assert(infos is not null); if (infos is null) throw new InvalidOperationException(); Debug.Assert(infos.Length == nodes.Length); @@ -250,7 +250,7 @@ static string GetHeader(DocumentTreeNodeData[] nodes) { return string.Format(dnSpy_AsmEditor_Resources.DeleteResourcesCommand, nodes.Length); } - static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length > 0 && nodes.All(n => !(ResourceElementNode.GetResourceElement(n) is null)); + static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length > 0 && nodes.All(n => ResourceElementNode.GetResourceElement(n) is not null); static void Execute(Lazy undoCommandService, DocumentTreeNodeData[] nodes) { if (!CanExecute(nodes)) @@ -269,7 +269,7 @@ sealed class ModuleInfo { public ModuleInfo(ResourceElementSetNode node) { Node = node ?? throw new InvalidOperationException(); var module = node.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); Module = module ?? throw new InvalidOperationException(); Index = module.Resources.IndexOf(node.Resource); Debug.Assert(Index >= 0); @@ -371,7 +371,7 @@ protected SaveResourcesCommandBase(bool useSubDirs, ResourceDataType resourceDat } protected ResourceData[] GetResourceData(IResourceDataProvider[]? nodes) => SaveResources.GetResourceData(nodes, resourceDataType); - public override bool IsVisible(IMenuItemContext context) => !(GetResourceNodes(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetResourceNodes(context) is not null; public override void Execute(IMenuItemContext context) => SaveResources.Save(GetResourceNodes(context), useSubDirs, resourceDataType); } @@ -486,16 +486,16 @@ public DocumentsCommand() } static class ResUtils { - public static bool CanExecuteResourceListCommand(DocumentTreeNodeData[] nodes) => !(GetResourceListTreeNode(nodes) is null); + public static bool CanExecuteResourceListCommand(DocumentTreeNodeData[] nodes) => GetResourceListTreeNode(nodes) is not null; public static ResourcesFolderNode? GetResourceListTreeNode(DocumentTreeNodeData[] nodes) { if (nodes.Length != 1) return null; ResourcesFolderNode? rsrcListNode; - if (!((rsrcListNode = nodes[0] as ResourcesFolderNode) is null)) + if ((rsrcListNode = nodes[0] as ResourcesFolderNode) is not null) return rsrcListNode; rsrcListNode = nodes[0].TreeNode.Parent?.Data as ResourcesFolderNode; - if (!(rsrcListNode is null)) + if (rsrcListNode is not null) return rsrcListNode; var modNode = nodes[0] as ModuleDocumentNode; @@ -576,7 +576,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var rsrcListNode = ResUtils.GetResourceListTreeNode(nodes)!; var module = rsrcListNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -616,7 +616,7 @@ static void Execute(Lazy undoCommandService, IAppService ap CreateFileResourceCommand(ResourcesFolderNode rsrcListNode, NodeAndResource[] nodes) { module = rsrcListNode.GetModule()!; - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); this.rsrcListNode = rsrcListNode; this.nodes = nodes; } @@ -657,7 +657,7 @@ abstract class CreateResourceTreeNodeCommand : IUndoCommand { protected CreateResourceTreeNodeCommand(ResourcesFolderNode rsrcListNode, NodeAndResource resTreeNode) { module = rsrcListNode.GetModule()!; - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); this.rsrcListNode = rsrcListNode; this.resTreeNode = resTreeNode; } @@ -748,7 +748,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var rsrcListNode = ResUtils.GetResourceListTreeNode(nodes)!; var module = rsrcListNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -846,7 +846,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var rsrcListNode = ResUtils.GetResourceListTreeNode(nodes)!; var module = rsrcListNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -941,7 +941,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var rsrcListNode = ResUtils.GetResourceListTreeNode(nodes)!; var module = rsrcListNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -1023,7 +1023,7 @@ internal sealed class CodeCommand : CodeContextMenuHandler { public override void Execute(CodeContext context) => ResourceSettingsCommand.Execute(undoCommandService, appService, context.Nodes); } - static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length == 1 && !(ResourceNode.GetResource(nodes[0]) is null); + static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length == 1 && ResourceNode.GetResource(nodes[0]) is not null; static void Execute(Lazy undoCommandService, IAppService appService, DocumentTreeNodeData[] nodes) { if (!CanExecute(nodes)) @@ -1032,7 +1032,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var rsrcNode = new NodeAndResource(nodes[0]); var module = nodes[0].GetParentModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -1118,7 +1118,7 @@ abstract class CreateResourceElementCommandBase : IUndoCommand { protected CreateResourceElementCommandBase(ResourceElementSetNode rsrcSetNode, NodeAndResourceElement[] nodes) { module = rsrcSetNode.GetModule()!; - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); this.rsrcSetNode = rsrcSetNode; this.nodes = nodes; resource = rsrcSetNode.Resource; @@ -1226,10 +1226,10 @@ static void Execute(Lazy undoCommandService, IAppService ap var rsrcSetNode = nodes[0] as ResourceElementSetNode; if (rsrcSetNode is null) rsrcSetNode = nodes[0].TreeNode.Parent!.Data as ResourceElementSetNode; - Debug2.Assert(!(rsrcSetNode is null)); + Debug2.Assert(rsrcSetNode is not null); var module = rsrcSetNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -1259,7 +1259,7 @@ static void Execute(Lazy undoCommandService, IAppService ap error = string.Format(dnSpy_AsmEditor_Resources.Error_ReadingFiles, ex.Message); } } - if (!(error is null)) + if (error is not null) MsgBox.Instance.Show(error); if (newNodes.Count == 0) return; @@ -1340,10 +1340,10 @@ static void Execute(Lazy undoCommandService, IAppService ap var rsrcSetNode = nodes[0] as ResourceElementSetNode; if (rsrcSetNode is null) rsrcSetNode = nodes[0].TreeNode.Parent!.Data as ResourceElementSetNode; - Debug2.Assert(!(rsrcSetNode is null)); + Debug2.Assert(rsrcSetNode is not null); var module = rsrcSetNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -1374,7 +1374,7 @@ static void Execute(Lazy undoCommandService, IAppService ap MsgBox.Instance.Show(error); return; } - Debug2.Assert(!(opts is null)); + Debug2.Assert(opts is not null); var treeView = appService.DocumentTreeView.TreeView; var treeNodeGroup = appService.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.ResourceElementTreeNodeGroup); @@ -1458,10 +1458,10 @@ internal static void Execute(Lazy undoCommandService, IAppS var rsrcSetNode = nodes[0] as ResourceElementSetNode; if (rsrcSetNode is null) rsrcSetNode = nodes[0].TreeNode.Parent!.Data as ResourceElementSetNode; - Debug2.Assert(!(rsrcSetNode is null)); + Debug2.Assert(rsrcSetNode is not null); var module = rsrcSetNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -1648,10 +1648,10 @@ static void Execute(Lazy undoCommandService, IAppService ap var rsrcSetNode = nodes[0] as ResourceElementSetNode; if (rsrcSetNode is null) rsrcSetNode = nodes[0].TreeNode.Parent!.Data as ResourceElementSetNode; - Debug2.Assert(!(rsrcSetNode is null)); + Debug2.Assert(rsrcSetNode is not null); var module = rsrcSetNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -1702,7 +1702,7 @@ protected ResourceElementSettingsBaseCommand(ResourceElementNode rsrcElNode, Res origOptions = rsrcElNode.ResourceElement; module = rsrcSetNode.GetModule()!; - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); resource = rsrcSetNode.Resource; resourceIndex = module.Resources.IndexOf(resource); Debug.Assert(resourceIndex >= 0); @@ -1833,7 +1833,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var rsrcElNode = (ResourceElementNode)nodes[0]; var module = nodes[0].GetParentModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); diff --git a/Extensions/dnSpy.AsmEditor/Resources/ResourceElementControl.xaml.cs b/Extensions/dnSpy.AsmEditor/Resources/ResourceElementControl.xaml.cs index e335878c5c..0c8562860a 100644 --- a/Extensions/dnSpy.AsmEditor/Resources/ResourceElementControl.xaml.cs +++ b/Extensions/dnSpy.AsmEditor/Resources/ResourceElementControl.xaml.cs @@ -38,10 +38,10 @@ public ResourceElementControl() { void ResourceElementControl_Loaded(object? sender, RoutedEventArgs e) { var vm = DataContext as ResourceElementVM; - Debug2.Assert(!(vm is null)); - if (!(vm is null) && !string.IsNullOrEmpty(vm.Name) && vm.IsSingleLineValue) + Debug2.Assert(vm is not null); + if (vm is not null && !string.IsNullOrEmpty(vm.Name) && vm.IsSingleLineValue) valueTextBox.Focus(); - else if (!(vm is null) && !string.IsNullOrEmpty(vm.Name) && vm.IsMultiLineValue) + else if (vm is not null && !string.IsNullOrEmpty(vm.Name) && vm.IsMultiLineValue) multiLineTextBox.Focus(); else nameTextBox.Focus(); diff --git a/Extensions/dnSpy.AsmEditor/Resources/ResourceElementVM.cs b/Extensions/dnSpy.AsmEditor/Resources/ResourceElementVM.cs index 1f0048caa1..1c916de69e 100644 --- a/Extensions/dnSpy.AsmEditor/Resources/ResourceElementVM.cs +++ b/Extensions/dnSpy.AsmEditor/Resources/ResourceElementVM.cs @@ -206,7 +206,7 @@ void PickRawBytes() { if (openFile is null) throw new InvalidOperationException(); var newBytes = openFile.Open(); - if (!(newBytes is null)) + if (newBytes is not null) Data = newBytes; } diff --git a/Extensions/dnSpy.AsmEditor/Resources/ResourceOptions.cs b/Extensions/dnSpy.AsmEditor/Resources/ResourceOptions.cs index 0509a565be..255d4cc70f 100644 --- a/Extensions/dnSpy.AsmEditor/Resources/ResourceOptions.cs +++ b/Extensions/dnSpy.AsmEditor/Resources/ResourceOptions.cs @@ -62,13 +62,13 @@ public void CopyTo(Resource resource) { case dnlib.DotNet.ResourceType.AssemblyLinked: var al = (AssemblyLinkedResource)resource; - Debug2.Assert(!(Assembly is null)); + Debug2.Assert(Assembly is not null); al.Assembly = Assembly; break; case dnlib.DotNet.ResourceType.Linked: var lr = (LinkedResource)resource; - Debug2.Assert(!(File is null)); + Debug2.Assert(File is not null); lr.File = File; break; diff --git a/Extensions/dnSpy.AsmEditor/Resources/ResourceVM.cs b/Extensions/dnSpy.AsmEditor/Resources/ResourceVM.cs index aa392633f5..c71ca3cf43 100644 --- a/Extensions/dnSpy.AsmEditor/Resources/ResourceVM.cs +++ b/Extensions/dnSpy.AsmEditor/Resources/ResourceVM.cs @@ -144,7 +144,7 @@ void PickAssembly() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var newAsm = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_Assembly, new FlagsDocumentTreeNodeFilter(VisibleMembersFlags.AssemblyDef), null, ownerModule); - if (!(newAsm is null) && !(newAsm.AssemblyDef is null)) + if (newAsm is not null && newAsm.AssemblyDef is not null) Assembly = newAsm.AssemblyDef.ToAssemblyRef(); } @@ -157,7 +157,7 @@ void InitializeFrom(ResourceOptions options) { Attributes = options.Attributes; Name = options.Name; Assembly = options.Assembly; - if (!(options.File is null)) { + if (options.File is not null) { FileHashValue.Value = options.File.HashValue; FileName = options.File.Name ?? UTF8String.Empty; FileContainsNoMetadata = options.File.ContainsNoMetadata; diff --git a/Extensions/dnSpy.AsmEditor/Resources/UserTypeVM.cs b/Extensions/dnSpy.AsmEditor/Resources/UserTypeVM.cs index c1e1b03d22..85c6149ec0 100644 --- a/Extensions/dnSpy.AsmEditor/Resources/UserTypeVM.cs +++ b/Extensions/dnSpy.AsmEditor/Resources/UserTypeVM.cs @@ -73,7 +73,7 @@ void PickType() { if (dnlibTypePicker is null) throw new InvalidOperationException(); var newType = dnlibTypePicker.GetDnlibType(dnSpy_AsmEditor_Resources.Pick_Type, new FlagsDocumentTreeNodeFilter(VisibleMembersFlags.TypeDef), GetTypeRef(), ownerModule); - if (!(newType is null)) + if (newType is not null) TypeFullName = newType.AssemblyQualifiedName; } diff --git a/Extensions/dnSpy.AsmEditor/SaveModule/DocumentSaver.cs b/Extensions/dnSpy.AsmEditor/SaveModule/DocumentSaver.cs index 08ceb162f0..d17f469f29 100644 --- a/Extensions/dnSpy.AsmEditor/SaveModule/DocumentSaver.cs +++ b/Extensions/dnSpy.AsmEditor/SaveModule/DocumentSaver.cs @@ -94,7 +94,7 @@ public bool Save(IEnumerable docs) { } else { var buffer = objsAry[0] as HexBuffer; - Debug2.Assert(!(buffer is null)); + Debug2.Assert(buffer is not null); var optsData = new SaveHexOptionsVM(buffer); var optsWin = new SaveHexOptionsDlg(); optsWin.Owner = appWindow.MainWindow; @@ -132,12 +132,12 @@ bool MarkAsSaved(SaveMultiModuleVM vm, object[] docs) { undoCommandService.Value.MarkAsSaved(undoCommandService.Value.GetUndoObject(doc)!); if (doc is IDsDocument document && string.IsNullOrEmpty(document.Filename)) { var filename = vm.GetSavedFileName(doc); - if (!string2.IsNullOrWhiteSpace(filename) && !(document.ModuleDef is null)) { + if (!string2.IsNullOrWhiteSpace(filename) && document.ModuleDef is not null) { document.ModuleDef.Location = filename; document.Filename = filename; var modNode = documentTabService.DocumentTreeView.FindNode(document.ModuleDef) as ModuleDocumentNode; - Debug2.Assert(!(modNode is null)); - if (!(modNode is null)) { + Debug2.Assert(modNode is not null); + if (modNode is not null) { modNode.TreeNode.RefreshUI(); documentTabService.RefreshModifiedDocument(modNode.Document); } diff --git a/Extensions/dnSpy.AsmEditor/SaveModule/MmapDisabler.cs b/Extensions/dnSpy.AsmEditor/SaveModule/MmapDisabler.cs index 85a4e363c6..0ae33d75de 100644 --- a/Extensions/dnSpy.AsmEditor/SaveModule/MmapDisabler.cs +++ b/Extensions/dnSpy.AsmEditor/SaveModule/MmapDisabler.cs @@ -58,13 +58,13 @@ IEnumerable GetDocuments() { } foreach (var uo in undoCommandService.Value.GetAllObjects()) { var f = DsDocumentUndoableDocumentsProvider.TryGetDocument(uo); - if (!(f is null)) + if (f is not null) yield return f; } } static void DisableMemoryMappedIO(HashSet filenames, IPEImage? peImage) { - if (!(peImage is null) && filenames.Contains(peImage.Filename)) + if (peImage is not null && filenames.Contains(peImage.Filename)) MemoryMappedIOHelper.DisableMemoryMappedIO(peImage); } } diff --git a/Extensions/dnSpy.AsmEditor/SaveModule/ModuleSaver.cs b/Extensions/dnSpy.AsmEditor/SaveModule/ModuleSaver.cs index a35c5e5ba9..deb6a34380 100644 --- a/Extensions/dnSpy.AsmEditor/SaveModule/ModuleSaver.cs +++ b/Extensions/dnSpy.AsmEditor/SaveModule/ModuleSaver.cs @@ -241,7 +241,7 @@ void ModuleWriter_ProgressUpdated(object? sender, ModuleWriterProgressEventArgs void ILogger.Log(object? sender, LoggerEvent loggerEvent, string format, params object[] args) { ThrowIfCanceled(); - if (!(OnLogMessage is null)) { + if (OnLogMessage is not null) { var evtType = loggerEvent == LoggerEvent.Error ? ModuleSaverLogEvent.Error : loggerEvent == LoggerEvent.Warning ? ModuleSaverLogEvent.Warning : diff --git a/Extensions/dnSpy.AsmEditor/SaveModule/SaveModuleCommand.cs b/Extensions/dnSpy.AsmEditor/SaveModule/SaveModuleCommand.cs index b314c0e78a..91ceabf6e2 100644 --- a/Extensions/dnSpy.AsmEditor/SaveModule/SaveModuleCommand.cs +++ b/Extensions/dnSpy.AsmEditor/SaveModule/SaveModuleCommand.cs @@ -102,7 +102,7 @@ HashSet GetDocuments(DocumentTreeNodeData[] nodes) { bool added = false; - if (!(fileNode.Document.ModuleDef is null)) { + if (fileNode.Document.ModuleDef is not null) { var file = fileNode.Document; var uo = undoCommandService.Value.GetUndoObject(file)!; if (undoCommandService.Value.IsModified(uo)) { @@ -112,7 +112,7 @@ HashSet GetDocuments(DocumentTreeNodeData[] nodes) { } var doc = hexBufferService.Value.TryGet(fileNode.Document.Filename); - if (!(doc is null)) { + if (doc is not null) { var uo = undoCommandService.Value.GetUndoObject(doc)!; if (undoCommandService.Value.IsModified(uo)) { hash.Add(doc); @@ -121,7 +121,7 @@ HashSet GetDocuments(DocumentTreeNodeData[] nodes) { } // If nothing was modified, just include the selected module - if (!added && !(fileNode.Document.ModuleDef is null)) + if (!added && fileNode.Document.ModuleDef is not null) hash.Add(fileNode.Document); } return new HashSet(undoCommandService.Value.GetUniqueDocuments(hash)); diff --git a/Extensions/dnSpy.AsmEditor/SaveModule/SaveModuleOptionsVM.cs b/Extensions/dnSpy.AsmEditor/SaveModule/SaveModuleOptionsVM.cs index 37f01ec7d3..071164e3b1 100644 --- a/Extensions/dnSpy.AsmEditor/SaveModule/SaveModuleOptionsVM.cs +++ b/Extensions/dnSpy.AsmEditor/SaveModule/SaveModuleOptionsVM.cs @@ -52,7 +52,7 @@ public bool UseMixedMode { } bool useMixedMode; - public bool CanWritePdb => !(Module.PdbState is null); + public bool CanWritePdb => Module.PdbState is not null; public bool WritePdb { get => writePdb; @@ -197,7 +197,7 @@ public ModuleWriterOptionsBase CreateWriterOptions() { else { var options = new ModuleWriterOptions(Module); CopyTo(options); - if (!(Module.ManagedEntryPoint is null) || Module.NativeEntryPoint == 0) + if (Module.ManagedEntryPoint is not null || Module.NativeEntryPoint == 0) options.Cor20HeaderOptions.Flags &= ~ComImageFlags.NativeEntryPoint; return AddOtherOptions(options); } @@ -845,7 +845,7 @@ public bool? PreserveRids { return null; } set { - if (!(value is null) && value != PreserveRids) { + if (value is not null && value != PreserveRids) { if (value.Value) Flags |= MetadataFlags.PreserveRids; else @@ -945,7 +945,7 @@ void SetFlagValue(MetadataFlags flag, bool value, string prop1, string? prop2 = Flags &= ~flag; OnPropertyChanged(prop1); - if (!(prop2 is null)) + if (prop2 is not null) OnPropertyChanged(prop2); } diff --git a/Extensions/dnSpy.AsmEditor/SaveModule/SaveMultiModuleVM.cs b/Extensions/dnSpy.AsmEditor/SaveModule/SaveMultiModuleVM.cs index 205c16e477..29ad3c5e1f 100644 --- a/Extensions/dnSpy.AsmEditor/SaveModule/SaveMultiModuleVM.cs +++ b/Extensions/dnSpy.AsmEditor/SaveModule/SaveMultiModuleVM.cs @@ -73,7 +73,7 @@ SaveState State { OnPropertyChanged(nameof(IsSavingOrCanceling)); OnModuleSettingsSaved(); - if (saveState == SaveState.Saved && !(OnSavedEvent is null)) + if (saveState == SaveState.Saved && OnSavedEvent is not null) OnSavedEvent(this, EventArgs.Empty); } } @@ -81,7 +81,7 @@ SaveState State { SaveState saveState = SaveState.Loaded; public ICommand SaveCommand => new RelayCommand(a => Save(), a => CanExecuteSave); - public ICommand CancelSaveCommand => new RelayCommand(a => CancelSave(), a => IsSaving && !(moduleSaver is null)); + public ICommand CancelSaveCommand => new RelayCommand(a => CancelSave(), a => IsSaving && moduleSaver is not null); public event EventHandler? OnSavedEvent; public bool IsLoaded => State == SaveState.Loaded; public bool IsSaving => State == SaveState.Saving; diff --git a/Extensions/dnSpy.AsmEditor/TheExtension.cs b/Extensions/dnSpy.AsmEditor/TheExtension.cs index 8ec23ebffe..b96ffab3c5 100644 --- a/Extensions/dnSpy.AsmEditor/TheExtension.cs +++ b/Extensions/dnSpy.AsmEditor/TheExtension.cs @@ -45,7 +45,7 @@ void ThemeFontSettings_PropertyChanged(object? sender, PropertyChangedEventArgs void Initialize(FontSettings fontSettings) { if (prevFontSettings == fontSettings) return; - if (!(prevFontSettings is null)) + if (prevFontSettings is not null) prevFontSettings.PropertyChanged -= FontSettings_PropertyChanged; prevFontSettings = fontSettings; fontSettings.PropertyChanged += FontSettings_PropertyChanged; diff --git a/Extensions/dnSpy.AsmEditor/Types/TypeDefCommands.cs b/Extensions/dnSpy.AsmEditor/Types/TypeDefCommands.cs index ed2e48e04e..f9a8c7b8d8 100644 --- a/Extensions/dnSpy.AsmEditor/Types/TypeDefCommands.cs +++ b/Extensions/dnSpy.AsmEditor/Types/TypeDefCommands.cs @@ -131,7 +131,7 @@ public ModelInfo(TypeDef type) { public void Delete(TypeNode[] nodes) { Debug2.Assert(infos is null); - if (!(infos is null)) + if (infos is not null) throw new InvalidOperationException(); infos = new ModelInfo[nodes.Length]; @@ -146,7 +146,7 @@ public void Delete(TypeNode[] nodes) { } public void Restore(TypeNode[] nodes) { - Debug2.Assert(!(infos is null)); + Debug2.Assert(infos is not null); if (infos is null) throw new InvalidOperationException(); Debug.Assert(infos.Length == nodes.Length); @@ -230,7 +230,7 @@ static void Execute(Lazy undoCommandService, IAppService ap string ns = nsNode?.Name ?? string.Empty; var module = nodes[0].GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); var options = TypeDefOptions.Create(ns, TypeConstants.DEFAULT_TYPE_NAME, module.CorLibTypes.Object.TypeDefOrRef, false); @@ -255,7 +255,7 @@ static void Execute(Lazy undoCommandService, IAppService ap CreateTypeDefCommand(IList ownerList, DocumentTreeNodeData ownerNode, TypeDefOptions options) { this.ownerList = ownerList; var modNode = ownerNode.GetModuleNode(); - Debug2.Assert(!(modNode is null)); + Debug2.Assert(modNode is not null); if (modNode is null) throw new InvalidOperationException(); nsNodeCreator = new NamespaceNodeCreator(options.Namespace, modNode); @@ -338,7 +338,7 @@ public override bool IsEnabled(CodeContext context) => static bool CanExecute(DocumentTreeNodeData[] nodes) => nodes.Length == 1 && - (nodes[0] is TypeNode || (!(nodes[0].TreeNode.Parent is null) && nodes[0].TreeNode.Parent!.Data is TypeNode)); + (nodes[0] is TypeNode || (nodes[0].TreeNode.Parent is not null && nodes[0].TreeNode.Parent!.Data is TypeNode)); static void Execute(Lazy undoCommandService, IAppService appService, DocumentTreeNodeData[] nodes) { if (!CanExecute(nodes)) @@ -348,12 +348,12 @@ static void Execute(Lazy undoCommandService, IAppService ap if (!(ownerNode is TypeNode)) ownerNode = (DocumentTreeNodeData)ownerNode.TreeNode.Parent!.Data; var typeNode = ownerNode as TypeNode; - Debug2.Assert(!(typeNode is null)); + Debug2.Assert(typeNode is not null); if (typeNode is null) throw new InvalidOperationException(); var module = typeNode.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); var options = TypeDefOptions.Create(UTF8String.Empty, TypeConstants.DEFAULT_TYPE_NAME, module.CorLibTypes.Object.TypeDefOrRef, true); @@ -378,7 +378,7 @@ static void Execute(Lazy undoCommandService, IAppService ap this.ownerType = ownerType; var modNode = ownerType.GetModuleNode(); - Debug2.Assert(!(modNode is null)); + Debug2.Assert(modNode is not null); if (modNode is null) throw new InvalidOperationException(); nestedType = ownerType.Create(options.CreateTypeDef(modNode.Document.ModuleDef!)); @@ -463,7 +463,7 @@ static void Execute(Lazy undoCommandService, IAppService ap var typeNode = (TypeNode)nodes[0]; var module = nodes[0].GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); @@ -525,7 +525,7 @@ public TypeRefInfo(TypeRef tr) { public string Description => dnSpy_AsmEditor_Resources.EditTypeCommand2; public void Execute() { - if (!(nsNodeCreator is null)) { + if (nsNodeCreator is not null) { bool b = origParentChildIndex < origParentNode.TreeNode.Children.Count && origParentNode.TreeNode.Children[origParentChildIndex] == typeNode.TreeNode; Debug.Assert(b); if (!b) @@ -549,7 +549,7 @@ public void Execute() { } else newOptions.CopyTo(typeNode.TypeDef, module); - if (!(typeRefInfos is null)) { + if (typeRefInfos is not null) { foreach (var info in typeRefInfos) { info.TypeRef.Namespace = typeNode.TypeDef.Namespace; info.TypeRef.Name = typeNode.TypeDef.Name; @@ -560,7 +560,7 @@ public void Execute() { } public void Undo() { - if (!(nsNodeCreator is null)) { + if (nsNodeCreator is not null) { bool b = nsNodeCreator.NamespaceNode.TreeNode.Children.Remove(typeNode.TreeNode); Debug.Assert(b); if (!b) @@ -582,7 +582,7 @@ public void Undo() { } else origOptions.CopyTo(typeNode.TypeDef, module); - if (!(typeRefInfos is null)) { + if (typeRefInfos is not null) { foreach (var info in typeRefInfos) { info.TypeRef.Namespace = info.OrigNamespace; info.TypeRef.Name = info.OrigName; @@ -594,8 +594,8 @@ public void Undo() { internal static void InvalidateBaseTypeFolderNode(TypeNode typeNode) { var btNode = (BaseTypeFolderNode?)typeNode.TreeNode.DataChildren.FirstOrDefault(a => a is BaseTypeFolderNode); - Debug2.Assert(!(btNode is null) || typeNode.TreeNode.Children.Count == 0); - if (!(btNode is null)) + Debug2.Assert(btNode is not null || typeNode.TreeNode.Children.Count == 0); + if (btNode is not null) btNode.InvalidateChildren(); } diff --git a/Extensions/dnSpy.AsmEditor/Types/TypeDefOptions.cs b/Extensions/dnSpy.AsmEditor/Types/TypeDefOptions.cs index 280086c6f2..e46ce6ab37 100644 --- a/Extensions/dnSpy.AsmEditor/Types/TypeDefOptions.cs +++ b/Extensions/dnSpy.AsmEditor/Types/TypeDefOptions.cs @@ -61,7 +61,7 @@ public TypeDef CopyTo(TypeDef type, ModuleDef ownerModule) { type.Attributes = Attributes; type.Namespace = Namespace ?? UTF8String.Empty; type.Name = Name ?? UTF8String.Empty; - if (!(PackingSize is null) || !(ClassSize is null)) + if (PackingSize is not null || ClassSize is not null) type.ClassLayout = ownerModule.UpdateRowId(new ClassLayoutUser(PackingSize ?? 0, ClassSize ?? 0)); else type.ClassLayout = null; diff --git a/Extensions/dnSpy.AsmEditor/Types/TypeOptionsVM.cs b/Extensions/dnSpy.AsmEditor/Types/TypeOptionsVM.cs index 30891d0db6..4968d3be5c 100644 --- a/Extensions/dnSpy.AsmEditor/Types/TypeOptionsVM.cs +++ b/Extensions/dnSpy.AsmEditor/Types/TypeOptionsVM.cs @@ -258,7 +258,7 @@ public TypeOptionsVM(TypeDefOptions options, ModuleDef ownerModule, IDecompilerS CanAddGenericMethodVar = false, OwnerType = ownerType, }; - if (!(ownerType is null) && ownerType.GenericParameters.Count == 0) + if (ownerType is not null && ownerType.GenericParameters.Count == 0) typeSigCreatorOptions.CanAddGenericTypeVar = false; TypeSigCreator = new TypeSigCreatorVM(typeSigCreatorOptions); TypeSigCreator.PropertyChanged += typeSigCreator_PropertyChanged; @@ -438,7 +438,7 @@ void OnTypeKindChanged2() { } bool IsClassBaseType(IType? type) => - !(type is null) && + type is not null && !IsSystemEnum(type) && !IsSystemValueType(type); diff --git a/Extensions/dnSpy.AsmEditor/UndoRedo/DsDocumentUndoableDocumentsProvider.cs b/Extensions/dnSpy.AsmEditor/UndoRedo/DsDocumentUndoableDocumentsProvider.cs index 87307589d8..f3705bfa47 100644 --- a/Extensions/dnSpy.AsmEditor/UndoRedo/DsDocumentUndoableDocumentsProvider.cs +++ b/Extensions/dnSpy.AsmEditor/UndoRedo/DsDocumentUndoableDocumentsProvider.cs @@ -45,8 +45,8 @@ IEnumerable IUndoableDocumentsProvider.GetObjects() { IUndoObject? IUndoableDocumentsProvider.GetUndoObject(object obj) { if (obj is DocumentTreeNodeData node) { var documentNode = node.GetDocumentNode(); - Debug2.Assert(!(documentNode is null)); - if (!(documentNode is null)) { + Debug2.Assert(documentNode is not null); + if (documentNode is not null) { // Need this check here since some commands (eg. create netmodule) create nodes // and they haven't yet been inserted into the treeview. if (documentNode is ModuleDocumentNode) @@ -54,8 +54,8 @@ IEnumerable IUndoableDocumentsProvider.GetObjects() { if (documentNode is AssemblyDocumentNode asmNode) { asmNode.TreeNode.EnsureChildrenLoaded(); var modNode = asmNode.TreeNode.DataChildren.FirstOrDefault() as ModuleDocumentNode; - Debug2.Assert(!(modNode is null)); - if (!(modNode is null)) + Debug2.Assert(modNode is not null); + if (modNode is not null) return GetUndoObjectNoChecks(modNode.Document); } return GetUndoObject(documentNode.Document); @@ -69,9 +69,9 @@ IEnumerable IUndoableDocumentsProvider.GetObjects() { bool IUndoableDocumentsProvider.OnExecutedOneCommand(IUndoObject obj) { var file = TryGetDocument(obj); - if (!(file is null)) { + if (file is not null) { var module = file.ModuleDef; - if (!(module is null)) + if (module is not null) module.ResetTypeDefFindCache(); documentTabService.RefreshModifiedDocument(file); return true; @@ -87,7 +87,7 @@ IDsDocument GetDocumentFile(IDsDocument document) { // Assemblies and manifest modules don't share a IDsDocument instance, but we must // use the same IUndoObject instance since they're part of the same file. var module = document.ModuleDef; - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); var modFile = FindModule(module); diff --git a/Extensions/dnSpy.AsmEditor/UndoRedo/UndoCommandService.cs b/Extensions/dnSpy.AsmEditor/UndoRedo/UndoCommandService.cs index bc0f558ac4..ad4c52578d 100644 --- a/Extensions/dnSpy.AsmEditor/UndoRedo/UndoCommandService.cs +++ b/Extensions/dnSpy.AsmEditor/UndoRedo/UndoCommandService.cs @@ -122,7 +122,7 @@ public BeginEndAdder(UndoCommandService mgr) { public bool CanUndo => undoCommands.Count != 0; public bool CanRedo => redoCommands.Count != 0; public int NumberOfModifiedDocuments => GetModifiedDocuments().Count(); - bool IsAdding => !(currentCommands is null); + bool IsAdding => currentCommands is not null; public void Add(IUndoCommand command) { if (currentCommands is null) { @@ -144,7 +144,7 @@ public void Add(IUndoCommand command) { /// BeginEndAdder BeginAdd() { Debug2.Assert(currentCommands is null); - if (!(currentCommands is null)) + if (currentCommands is not null) throw new InvalidOperationException(); return new BeginEndAdder(this); @@ -152,7 +152,7 @@ BeginEndAdder BeginAdd() { void BeginAddInternal() { Debug2.Assert(currentCommands is null); - if (!(currentCommands is null)) + if (currentCommands is not null) throw new InvalidOperationException(); int prev = currentCommandCounter; @@ -161,7 +161,7 @@ void BeginAddInternal() { } void EndAddInternal() { - Debug2.Assert(!(currentCommands is null)); + Debug2.Assert(currentCommands is not null); if (currentCommands is null) throw new InvalidOperationException(); @@ -180,7 +180,7 @@ void EndAddInternal() { void Clear(bool clearUndo, bool clearRedo) { Debug2.Assert(currentCommands is null); - if (!(currentCommands is null)) + if (currentCommands is not null) throw new InvalidOperationException(); if (clearUndo) { @@ -195,8 +195,8 @@ void Clear(bool clearUndo, bool clearRedo) { if (clearUndo && clearRedo) { foreach (var p in undoableDocumentsProviders) { foreach (var uo in p.Value.GetObjects()) { - Debug2.Assert(!(uo is null)); - if (!(uo is null) && !IsModified(uo)) + Debug2.Assert(uo is not null); + if (uo is not null && !IsModified(uo)) uo.SavedCommand = 0; } } @@ -216,7 +216,7 @@ static void Clear(List list) { public void Undo() { Debug2.Assert(currentCommands is null); - if (!(currentCommands is null)) + if (currentCommands is not null) throw new InvalidOperationException(); if (undoCommands.Count == 0) @@ -234,7 +234,7 @@ public void Undo() { public void Redo() { Debug2.Assert(currentCommands is null); - if (!(currentCommands is null)) + if (currentCommands is not null) throw new InvalidOperationException(); if (redoCommands.Count == 0) @@ -281,10 +281,10 @@ public IEnumerable GetModifiedDocuments() { var hash = new HashSet(); foreach (var p in undoableDocumentsProviders) { foreach (var uo in p.Value.GetObjects()) { - Debug2.Assert(!(uo is null)); - if (!(uo is null) && IsModified(uo)) { + Debug2.Assert(uo is not null); + if (uo is not null && IsModified(uo)) { var doc = p.Value.GetDocument(uo); - Debug2.Assert(!(doc is null)); + Debug2.Assert(doc is not null); if (doc is null) throw new InvalidOperationException(); hash.Add(doc); @@ -297,7 +297,7 @@ public IEnumerable GetModifiedDocuments() { object? GetDocument(IUndoObject uo) { foreach (var p in undoableDocumentsProviders) { var doc = p.Value.GetDocument(uo); - if (!(doc is null)) + if (doc is not null) return doc; } @@ -371,7 +371,7 @@ void UpdateAssemblySavedState(int newCurrentCommandCounter, UndoState executedGr IEnumerable GetModifiedObjects(IUndoCommand command) { foreach (var obj in command.ModifiedObjects) { var uo = GetUndoObject(obj); - if (!(uo is null)) + if (uo is not null) yield return uo; } } @@ -379,7 +379,7 @@ IEnumerable GetModifiedObjects(IUndoCommand command) { public IUndoObject? GetUndoObject(object obj) { foreach (var up in undoableDocumentsProviders) { var uo = up.Value.GetUndoObject(obj); - if (!(uo is null)) + if (uo is not null) return uo; } @@ -416,7 +416,7 @@ public IEnumerable GetAllObjects() { continue; foreach (var obj in cmd2.NonModifiedObjects) { var uo = GetUndoObject(obj); - if (!(uo is null)) + if (uo is not null) yield return uo; } } diff --git a/Extensions/dnSpy.AsmEditor/ViewHelpers/CreateTypeSigArray.cs b/Extensions/dnSpy.AsmEditor/ViewHelpers/CreateTypeSigArray.cs index 846014d1cb..c7b9ea52f7 100644 --- a/Extensions/dnSpy.AsmEditor/ViewHelpers/CreateTypeSigArray.cs +++ b/Extensions/dnSpy.AsmEditor/ViewHelpers/CreateTypeSigArray.cs @@ -33,7 +33,7 @@ public CreateTypeSigArray() public TypeSig[]? Create(TypeSigCreatorOptions options, int? count, TypeSig[]? typeSigs) { var data = new CreateTypeSigArrayVM(options, count); - if (!(typeSigs is null)) + if (typeSigs is not null) data.TypeSigCollection.AddRange(typeSigs); var win = new CreateTypeSigArrayDlg(); win.DataContext = data; diff --git a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditCustomAttribute.cs b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditCustomAttribute.cs index 1ecabad7bb..d6ff81034c 100644 --- a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditCustomAttribute.cs +++ b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditCustomAttribute.cs @@ -32,7 +32,7 @@ public EditCustomAttribute() public CustomAttributeVM? Edit(string? title, CustomAttributeVM ca) { var win = new CustomAttributeDlg(); - if (!(title is null)) + if (title is not null) win.Title = title; win.DataContext = ca; win.Owner = ownerWindow ?? Application.Current.MainWindow; diff --git a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditDeclSecurity.cs b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditDeclSecurity.cs index 7b6589f1ad..a47a273092 100644 --- a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditDeclSecurity.cs +++ b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditDeclSecurity.cs @@ -32,7 +32,7 @@ public EditDeclSecurity() public DeclSecurityVM? Edit(string? title, DeclSecurityVM ds) { var win = new DeclSecurityDlg(); - if (!(title is null)) + if (title is not null) win.Title = title; win.DataContext = ds; win.Owner = ownerWindow ?? Application.Current.MainWindow; diff --git a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditGenericParam.cs b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditGenericParam.cs index 896bfe6e1d..b476170174 100644 --- a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditGenericParam.cs +++ b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditGenericParam.cs @@ -32,7 +32,7 @@ public EditGenericParam() public GenericParamVM? Edit(string? title, GenericParamVM pd) { var win = new GenericParamDlg(); - if (!(title is null)) + if (title is not null) win.Title = title; win.DataContext = pd; win.Owner = ownerWindow ?? Application.Current.MainWindow; diff --git a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditImage.cs b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditImage.cs index b3750487ec..b1cda597da 100644 --- a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditImage.cs +++ b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditImage.cs @@ -56,7 +56,7 @@ public EditImage() return mo; } catch (Exception ex) { - if (!(imgStream is null)) + if (imgStream is not null) imgStream.Dispose(); MsgBox.Instance.Show(string.Format(dnSpy_AsmEditor_Resources.Error_OpenImage, ex.Message), MsgBoxButton.OK, ownerWindow); return null; diff --git a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditMemberRef.cs b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditMemberRef.cs index ed43cfa7f3..56501f39ba 100644 --- a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditMemberRef.cs +++ b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditMemberRef.cs @@ -32,7 +32,7 @@ public EditMemberRef() public MemberRefVM? Edit(string? title, MemberRefVM pd) { var win = new MemberRefDlg(); - if (!(title is null)) + if (title is not null) win.Title = title; win.DataContext = pd; win.Owner = ownerWindow ?? Application.Current.MainWindow; diff --git a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditMethodSpec.cs b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditMethodSpec.cs index 231bdba389..7f8f5408d4 100644 --- a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditMethodSpec.cs +++ b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditMethodSpec.cs @@ -32,7 +32,7 @@ public EditMethodSpec() public MethodSpecVM? Edit(string? title, MethodSpecVM pd) { var win = new MethodSpecDlg(); - if (!(title is null)) + if (title is not null) win.Title = title; win.DataContext = pd; win.Owner = ownerWindow ?? Application.Current.MainWindow; diff --git a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditParamDef.cs b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditParamDef.cs index d4812c872a..07e568f87f 100644 --- a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditParamDef.cs +++ b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditParamDef.cs @@ -32,7 +32,7 @@ public EditParamDef() public ParamDefVM? Edit(string? title, ParamDefVM pd) { var win = new ParamDefDlg(); - if (!(title is null)) + if (title is not null) win.Title = title; win.DataContext = pd; win.Owner = ownerWindow ?? Application.Current.MainWindow; diff --git a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditSecurityAttribute.cs b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditSecurityAttribute.cs index 11e66c6d3c..df1510f428 100644 --- a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditSecurityAttribute.cs +++ b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditSecurityAttribute.cs @@ -32,7 +32,7 @@ public EditSecurityAttribute() public SecurityAttributeVM? Edit(string? title, SecurityAttributeVM sa) { var win = new SecurityAttributeDlg(); - if (!(title is null)) + if (title is not null) win.Title = title; win.DataContext = sa; win.Owner = ownerWindow ?? Application.Current.MainWindow; diff --git a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditTypeDefOrRefAndCA.cs b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditTypeDefOrRefAndCA.cs index f9b65f6d93..6ea72cc38b 100644 --- a/Extensions/dnSpy.AsmEditor/ViewHelpers/EditTypeDefOrRefAndCA.cs +++ b/Extensions/dnSpy.AsmEditor/ViewHelpers/EditTypeDefOrRefAndCA.cs @@ -32,7 +32,7 @@ public EditTypeDefOrRefAndCA() public TypeDefOrRefAndCAVM? Edit(string? title, TypeDefOrRefAndCAVM obj) { var win = new TypeDefOrRefAndCADlg(); - if (!(title is null)) + if (title is not null) win.Title = title; win.DataContext = obj; win.Owner = ownerWindow ?? Application.Current.MainWindow; diff --git a/Extensions/dnSpy.AsmEditor/ViewHelpers/OpenAssembly.cs b/Extensions/dnSpy.AsmEditor/ViewHelpers/OpenAssembly.cs index cf2bbafd28..4cddff8c4d 100644 --- a/Extensions/dnSpy.AsmEditor/ViewHelpers/OpenAssembly.cs +++ b/Extensions/dnSpy.AsmEditor/ViewHelpers/OpenAssembly.cs @@ -46,7 +46,7 @@ IDsDocument[] Open(bool many) { foreach (var filename in dialog.FileNames) { var info = DsDocumentInfo.CreateDocument(filename); var file = documentService.TryGetOrCreate(info); - if (!(file is null)) + if (file is not null) list.Add(file); } return list.ToArray(); diff --git a/Extensions/dnSpy.BamlDecompiler/Baml/BamlNode.cs b/Extensions/dnSpy.BamlDecompiler/Baml/BamlNode.cs index 9304800531..afe0baba71 100644 --- a/Extensions/dnSpy.BamlDecompiler/Baml/BamlNode.cs +++ b/Extensions/dnSpy.BamlDecompiler/Baml/BamlNode.cs @@ -115,7 +115,7 @@ public static BamlNode Parse(BamlDocument document, CancellationToken token) { Header = document[i] }; - if (!(prev is null)) { + if (prev is not null) { prev.Children.Add(current); current.Parent = prev; stack.Push(prev); diff --git a/Extensions/dnSpy.BamlDecompiler/Baml/BamlRecords.cs b/Extensions/dnSpy.BamlDecompiler/Baml/BamlRecords.cs index e2fa7dea26..03b1992ae6 100644 --- a/Extensions/dnSpy.BamlDecompiler/Baml/BamlRecords.cs +++ b/Extensions/dnSpy.BamlDecompiler/Baml/BamlRecords.cs @@ -984,7 +984,7 @@ public override void Read(BamlBinaryReader reader) { public override void Write(BamlBinaryWriter writer) { writer.Write(TypeId); - if (!(RuntimeName is null)) { + if (RuntimeName is not null) { writer.Write(RuntimeName); } } diff --git a/Extensions/dnSpy.BamlDecompiler/Baml/KnownThings.cs b/Extensions/dnSpy.BamlDecompiler/Baml/KnownThings.cs index 1a170d1795..4616206c6c 100644 --- a/Extensions/dnSpy.BamlDecompiler/Baml/KnownThings.cs +++ b/Extensions/dnSpy.BamlDecompiler/Baml/KnownThings.cs @@ -63,7 +63,7 @@ public KnownThings(ModuleDef module) { KnownMember InitMember(KnownTypes parent, string name, TypeDef type) => new KnownMember(parent, types[parent], name, type); AssemblyDef ResolveThrow(string asmFullName) { var asm = resolver.Resolve(asmFullName, module); - if (!(asm is null)) + if (asm is not null) return asm; var newName = asmFullName switch { "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" => "WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", diff --git a/Extensions/dnSpy.BamlDecompiler/BamlDisassembler.cs b/Extensions/dnSpy.BamlDecompiler/BamlDisassembler.cs index f2c9eebf55..bff9af4bb9 100644 --- a/Extensions/dnSpy.BamlDecompiler/BamlDisassembler.cs +++ b/Extensions/dnSpy.BamlDecompiler/BamlDisassembler.cs @@ -146,7 +146,7 @@ void WriteTypeId(BamlContext ctx, ushort id) { else reference = null; - if (!(reference is null)) + if (reference is not null) reference = IdentifierEscaper.Escape(reference); output.Write($"0x{id:x4}", BamlToolTipReference.Create(reference), DecompilerReferenceFlags.Local, BoxedTextColor.Number); @@ -174,7 +174,7 @@ void WriteAttributeId(BamlContext ctx, ushort id) { declType = name = null; string reference = null; - if (!(declType is null) && !(name is null)) + if (declType is not null && name is not null) reference = $"{IdentifierEscaper.Escape(declType)}::{IdentifierEscaper.Escape(name)}"; output.Write($"0x{id:x4}", BamlToolTipReference.Create(reference), DecompilerReferenceFlags.Local, BoxedTextColor.Number); } @@ -188,7 +188,7 @@ void WriteStringId(BamlContext ctx, ushort id) { else str = null; string reference = null; - if (!(str is null)) + if (str is not null) reference = SimpleTypeConverter.ToString(str, true); output.Write($"0x{id:x4}", BamlToolTipReference.Create(reference), DecompilerReferenceFlags.Local, BoxedTextColor.Number); } diff --git a/Extensions/dnSpy.BamlDecompiler/Handlers/Records/PropertyWithStaticResourceIdHandler.cs b/Extensions/dnSpy.BamlDecompiler/Handlers/Records/PropertyWithStaticResourceIdHandler.cs index d425cec421..92ea6dafcd 100644 --- a/Extensions/dnSpy.BamlDecompiler/Handlers/Records/PropertyWithStaticResourceIdHandler.cs +++ b/Extensions/dnSpy.BamlDecompiler/Handlers/Records/PropertyWithStaticResourceIdHandler.cs @@ -43,7 +43,7 @@ public BamlElement Translate(XamlContext ctx, BamlNode node, BamlElement parent) XamlResourceKey key; do { key = XamlResourceKey.FindKeyInAncestors(found.Parent, out found); - } while (!(key is null) && record.StaticResourceId >= key.StaticResources.Count); + } while (key is not null && record.StaticResourceId >= key.StaticResources.Count); if (key is null) throw new Exception("Cannot find StaticResource @" + node.Record.Position); diff --git a/Extensions/dnSpy.BamlDecompiler/IHandlers.cs b/Extensions/dnSpy.BamlDecompiler/IHandlers.cs index fd7c90bf7c..9ba47fd972 100644 --- a/Extensions/dnSpy.BamlDecompiler/IHandlers.cs +++ b/Extensions/dnSpy.BamlDecompiler/IHandlers.cs @@ -47,7 +47,7 @@ public static IHandler LookupHandler(BamlRecordType type) { public static void ProcessChildren(XamlContext ctx, BamlBlockNode node, BamlElement nodeElem) { ctx.XmlNs.PushScope(nodeElem); - if (!(nodeElem.Xaml.Element is null)) + if (nodeElem.Xaml.Element is not null) nodeElem.Xaml.Element.AddAnnotation(ctx.XmlNs.CurrentScope); foreach (var child in node.Children) { var handler = LookupHandler(child.Type); @@ -56,7 +56,7 @@ public static void ProcessChildren(XamlContext ctx, BamlBlockNode node, BamlElem continue; } var elem = handler.Translate(ctx, (BamlNode)child, nodeElem); - if (!(elem is null)) { + if (elem is not null) { nodeElem.Children.Add(elem); elem.Parent = nodeElem; } diff --git a/Extensions/dnSpy.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs b/Extensions/dnSpy.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs index dc74c565e0..7ffe4453c6 100644 --- a/Extensions/dnSpy.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs +++ b/Extensions/dnSpy.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs @@ -68,7 +68,7 @@ public void Run(XamlContext ctx, XDocument document) { break; } } - if (!(iface is null)) + if (iface is not null) return; Dictionary> connIds = null; @@ -126,7 +126,7 @@ struct EventAttachment { public void Callback(XamlContext ctx, XElement elem) { XName name; - if (!(AttachedType is null)) { + if (AttachedType is not null) { var clrNs = AttachedType.ReflectionNamespace; var xmlNs = ctx.XmlNs.LookupXmlns(AttachedType.DefinitionAssembly, clrNs); name = ctx.GetXmlNamespace(xmlNs)?.GetName(EventName) ?? AttachedType.Name + "." + EventName; @@ -216,7 +216,7 @@ Dictionary> ExtractConnectionId(XamlContext c } } - if (!(cb is null)) { + if (cb is not null) { foreach (var id in info.connIds) connIds[id] = cb; } @@ -232,7 +232,7 @@ Dictionary> ExtractConnectionId(XamlContext c return list; var sw = method.GetSelfAndChildrenRecursive().FirstOrDefault(); - if (!(sw is null)) { + if (sw is not null) { foreach (var lbl in sw.CaseBlocks) { if (lbl.Values is null) continue; diff --git a/Extensions/dnSpy.BamlDecompiler/Rewrite/MarkupExtensionRewritePass.cs b/Extensions/dnSpy.BamlDecompiler/Rewrite/MarkupExtensionRewritePass.cs index 1248c7b9e9..e8e1d0df67 100644 --- a/Extensions/dnSpy.BamlDecompiler/Rewrite/MarkupExtensionRewritePass.cs +++ b/Extensions/dnSpy.BamlDecompiler/Rewrite/MarkupExtensionRewritePass.cs @@ -87,10 +87,10 @@ bool RewriteElement(XamlContext ctx, XElement parent, XElement elem) { bool CanInlineExt(XamlContext ctx, XElement ctxElement) { var type = ctxElement.Annotation(); - if (!(type is null) && !(type.ResolvedType is null)) { + if (type is not null && type.ResolvedType is not null) { var typeDef = type.ResolvedType.GetBaseType(); bool isExt = false; - while (!(typeDef is null)) { + while (typeDef is not null) { if (typeDef.FullName == "System.Windows.Markup.MarkupExtension") { isExt = true; break; @@ -149,7 +149,7 @@ XamlExtension InlineExtension(XamlContext ctx, XElement ctxElement) { return null; if (elem.Name == ctor) { - if (!(ext.Initializer is null)) + if (ext.Initializer is not null) return null; var args = InlineCtor(ctx, elem); diff --git a/Extensions/dnSpy.BamlDecompiler/Xaml/XamlExtension.cs b/Extensions/dnSpy.BamlDecompiler/Xaml/XamlExtension.cs index 0e42e8bd44..24a21c0c58 100644 --- a/Extensions/dnSpy.BamlDecompiler/Xaml/XamlExtension.cs +++ b/Extensions/dnSpy.BamlDecompiler/Xaml/XamlExtension.cs @@ -53,7 +53,7 @@ public string ToString(XamlContext ctx, XElement ctxElement) { sb.Append(typeName); bool comma = false; - if (!(Initializer is null) && Initializer.Length > 0) { + if (Initializer is not null && Initializer.Length > 0) { sb.Append(' '); for (int i = 0; i < Initializer.Length; i++) { if (comma) diff --git a/Extensions/dnSpy.BamlDecompiler/Xaml/XamlProperty.cs b/Extensions/dnSpy.BamlDecompiler/Xaml/XamlProperty.cs index 22c33c8834..5d1ca1e880 100644 --- a/Extensions/dnSpy.BamlDecompiler/Xaml/XamlProperty.cs +++ b/Extensions/dnSpy.BamlDecompiler/Xaml/XamlProperty.cs @@ -37,7 +37,7 @@ public XamlProperty(XamlType type, string name) { } public void TryResolve() { - if (!(ResolvedMember is null)) + if (ResolvedMember is not null) return; var typeDef = DeclaringType.ResolvedType.ResolveTypeDef(); @@ -45,15 +45,15 @@ public void TryResolve() { return; ResolvedMember = typeDef.FindPropertyCheckBaseType(PropertyName); - if (!(ResolvedMember is null)) + if (ResolvedMember is not null) return; ResolvedMember = typeDef.FindFieldCheckBaseType(PropertyName + "Property"); - if (!(ResolvedMember is null)) + if (ResolvedMember is not null) return; ResolvedMember = typeDef.FindEventCheckBaseType(PropertyName); - if (!(ResolvedMember is null)) + if (ResolvedMember is not null) return; ResolvedMember = typeDef.FindFieldCheckBaseType(PropertyName + "Event"); @@ -70,7 +70,7 @@ public bool IsAttachedTo(XamlType type) { if (comparer.Equals(t, declType)) return false; t = t.GetBaseType(); - } while (!(t is null)); + } while (t is not null); return true; } diff --git a/Extensions/dnSpy.BamlDecompiler/Xaml/XamlResourceKey.cs b/Extensions/dnSpy.BamlDecompiler/Xaml/XamlResourceKey.cs index b488776db0..c3cf04208e 100644 --- a/Extensions/dnSpy.BamlDecompiler/Xaml/XamlResourceKey.cs +++ b/Extensions/dnSpy.BamlDecompiler/Xaml/XamlResourceKey.cs @@ -90,7 +90,7 @@ public static XamlResourceKey FindKeyInAncestors(BamlNode node, out BamlNode fou return (XamlResourceKey)n.Annotation; } n = n.Parent; - } while (!(n is null)); + } while (n is not null); found = null; return null; } diff --git a/Extensions/dnSpy.BamlDecompiler/Xaml/XamlType.cs b/Extensions/dnSpy.BamlDecompiler/Xaml/XamlType.cs index 5666db8412..2cc90eaf71 100644 --- a/Extensions/dnSpy.BamlDecompiler/Xaml/XamlType.cs +++ b/Extensions/dnSpy.BamlDecompiler/Xaml/XamlType.cs @@ -46,14 +46,14 @@ public XamlType(IAssembly assembly, string ns, string name, XNamespace xmlns) { } public void ResolveNamespace(XElement elem, XamlContext ctx) { - if (!(Namespace is null)) + if (Namespace is not null) return; // Since XmlnsProperty records are inside the element, // the namespace is resolved after processing the element body. string xmlNs = null; - if (!(elem.Annotation() is null)) + if (elem.Annotation() is not null) xmlNs = elem.Annotation().LookupXmlns(Assembly, TypeNamespace); if (xmlNs is null) xmlNs = ctx.XmlNs.LookupXmlns(Assembly, TypeNamespace); @@ -78,7 +78,7 @@ public void ResolveNamespace(XElement elem, XamlContext ctx) { int count = 0; var truePrefix = prefix; XNamespace prefixNs, ns = ctx.GetXmlNamespace(xmlNs); - while (!((prefixNs = elem.GetNamespaceOfPrefix(truePrefix)) is null) && prefixNs != ns) { + while ((prefixNs = elem.GetNamespaceOfPrefix(truePrefix)) is not null && prefixNs != ns) { count++; truePrefix = prefix + count; } diff --git a/Extensions/dnSpy.BamlDecompiler/XamlContext.cs b/Extensions/dnSpy.BamlDecompiler/XamlContext.cs index 609f8070b7..7282f7af91 100644 --- a/Extensions/dnSpy.BamlDecompiler/XamlContext.cs +++ b/Extensions/dnSpy.BamlDecompiler/XamlContext.cs @@ -183,7 +183,7 @@ public string TryGetXmlNamespace(IAssembly assembly, string typeNamespace) { continue; var xmlNs = attr.ConstructorArguments[0].Value as UTF8String; var typeNs = attr.ConstructorArguments[1].Value as UTF8String; - Debug2.Assert(!(xmlNs is null) && !(typeNs is null)); + Debug2.Assert(xmlNs is not null && typeNs is not null); if (xmlNs is null || typeNs is null) continue; @@ -197,7 +197,7 @@ public string TryGetXmlNamespace(IAssembly assembly, string typeNamespace) { public XName GetXamlNsName(string name, XElement elem = null) { var xNs = GetXmlNamespace("http://schemas.microsoft.com/winfx/2006/xaml"); XName xName; - if (!(elem is null) && xNs == elem.GetDefaultNamespace()) + if (elem is not null && xNs == elem.GetDefaultNamespace()) xName = name; else xName = xNs + name; diff --git a/Extensions/dnSpy.BamlDecompiler/XamlDecompiler.cs b/Extensions/dnSpy.BamlDecompiler/XamlDecompiler.cs index 5d4873184a..7c099ff8cb 100644 --- a/Extensions/dnSpy.BamlDecompiler/XamlDecompiler.cs +++ b/Extensions/dnSpy.BamlDecompiler/XamlDecompiler.cs @@ -53,7 +53,7 @@ public XDocument Decompile(ModuleDef module, BamlDocument document, Cancellation pass.Run(ctx, xaml); } - if (!(assemblyReferences is null)) + if (assemblyReferences is not null) assemblyReferences.AddRange(ctx.Baml.AssemblyIdMap.Select(a => a.Value.AssemblyFullName)); return xaml; diff --git a/Extensions/dnSpy.BamlDecompiler/XmlnsDictionary.cs b/Extensions/dnSpy.BamlDecompiler/XmlnsDictionary.cs index bd91aaaa3e..0fee9640ad 100644 --- a/Extensions/dnSpy.BamlDecompiler/XmlnsDictionary.cs +++ b/Extensions/dnSpy.BamlDecompiler/XmlnsDictionary.cs @@ -76,7 +76,7 @@ NamespaceMap PIFixup(NamespaceMap map) { public NamespaceMap LookupNamespaceFromPrefix(string prefix) { var scope = CurrentScope; - while (!(scope is null)) { + while (scope is not null) { foreach (var ns in scope) { if (ns.XmlnsPrefix == prefix) return PIFixup(ns); @@ -90,7 +90,7 @@ public NamespaceMap LookupNamespaceFromPrefix(string prefix) { public NamespaceMap LookupNamespaceFromXmlns(string xmlNs) { var scope = CurrentScope; - while (!(scope is null)) { + while (scope is not null) { foreach (var ns in scope) { if (ns.XMLNamespace == xmlNs) return ns; @@ -110,7 +110,7 @@ public string LookupXmlns(IAssembly asm, string clrNs) { } var scope = CurrentScope; - while (!(scope is null)) { + while (scope is not null) { foreach (var ns in scope) { if (comparer.Equals(ns.Assembly, asm) && ns.CLRNamespace == clrNs) return ns.XMLNamespace; diff --git a/Extensions/dnSpy.Debugger/AppHostInfoGenerator/Program.cs b/Extensions/dnSpy.Debugger/AppHostInfoGenerator/Program.cs index 7085750273..a60cc6839e 100644 --- a/Extensions/dnSpy.Debugger/AppHostInfoGenerator/Program.cs +++ b/Extensions/dnSpy.Debugger/AppHostInfoGenerator/Program.cs @@ -206,7 +206,7 @@ int DoIt() { Console.WriteLine(error); continue; } - Debug.Assert(!(ridData is null)); + Debug.Assert(ridData is not null); if (ridData is null) throw new InvalidOperationException(); using (var ridZip = new ZipArchive(new MemoryStream(ridData), ZipArchiveMode.Read, leaveOpen: false)) { @@ -430,7 +430,7 @@ void Serialize(in AppHostInfo info, Dictionary stringsTable, bool void WriteComment(string? name, string? origValue) { if (name is null) { - if (!(origValue is null)) + if (origValue is not null) output.Write($"// {origValue}"); } else if (origValue is null) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/CorDebugUtils.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/CorDebugUtils.cs index 5bcf152301..88136f224a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/CorDebugUtils.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/CorDebugUtils.cs @@ -28,12 +28,12 @@ static class CorDebugUtils { public static bool TryGetInternalRuntime(DbgProcess process, [NotNullWhen(true)] out DbgCorDebugInternalRuntime? runtime) { runtime = null; var dbgRuntime = process.Runtimes.FirstOrDefault(); - Debug2.Assert(!(dbgRuntime is null)); + Debug2.Assert(dbgRuntime is not null); if (dbgRuntime is null) return false; runtime = dbgRuntime.InternalRuntime as DbgCorDebugInternalRuntime; - return !(runtime is null); + return runtime is not null; } } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/ECallManager.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/ECallManager.cs index 2fa656257e..9085848cdc 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/ECallManager.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/ECallManager.cs @@ -316,7 +316,7 @@ void InitializeTableFormat(long pos) { ulong nullPtr1 = ReadPtr(pos + ptrSize * 2); ulong nullPtr2 = ReadPtr(pos + ptrSize * 3); var name = ReadAsciizIdPtr(pos + ptrSize * 4); - if (nullPtr1 == 0 && nullPtr2 == 0 && !(name is null) && !(methRva is null) && (methRva.Value == 0 || IsCodeRva(methRva.Value))) { + if (nullPtr1 == 0 && nullPtr2 == 0 && name is not null && methRva is not null && (methRva.Value == 0 || IsCodeRva(methRva.Value))) { tableFormat = TableFormat.V1; return; } @@ -326,7 +326,7 @@ void InitializeTableFormat(long pos) { if (pos + ptrSize * (3 + (hasSig ? 1 : 0)) < reader.Length) { uint? methRva = ReadRva(pos + ptrSize * 1); var name = ReadAsciizIdPtr(pos + ptrSize * 2); - if (!(name is null) && !(methRva is null) && (methRva.Value == 0 || IsCodeRva(methRva.Value))) { + if (name is not null && methRva is not null && (methRva.Value == 0 || IsCodeRva(methRva.Value))) { tableFormat = TableFormat.V2; return; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/ManagedDebuggerPatcherX86.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/ManagedDebuggerPatcherX86.cs index 64e31fca4e..12587c9f3c 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/ManagedDebuggerPatcherX86.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/AntiAntiDebug/ManagedDebuggerPatcherX86.cs @@ -51,7 +51,7 @@ public bool TryPatch([NotNullWhen(false)] out string? errorMessage) { var debuggeeVersion = runtime.Version.Version; bool isClrV2OrOlder = - !(debuggeeVersion is null) && + debuggeeVersion is not null && (debuggeeVersion.StartsWith("v1.", StringComparison.OrdinalIgnoreCase) || debuggeeVersion.StartsWith("v2.", StringComparison.OrdinalIgnoreCase)); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Breakpoints/DbgBreakpointLocationFormatterProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Breakpoints/DbgBreakpointLocationFormatterProviderImpl.cs index 27dfb4fd40..f4e9990fe6 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Breakpoints/DbgBreakpointLocationFormatterProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Breakpoints/DbgBreakpointLocationFormatterProviderImpl.cs @@ -36,7 +36,7 @@ sealed class DbgBreakpointLocationFormatterProviderImpl : DbgBreakpointLocationF switch (location) { case DbgDotNetNativeCodeLocationImpl nativeLoc: var formatter = nativeLoc.Formatter; - if (!(formatter is null)) + if (formatter is not null) return formatter; formatter = breakpointFormatterService.Value.Create(nativeLoc); nativeLoc.Formatter = formatter; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Breakpoints/TextEditor/DbgBreakpointGlyphFormatterImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Breakpoints/TextEditor/DbgBreakpointGlyphFormatterImpl.cs index 86017229cb..912786a76e 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Breakpoints/TextEditor/DbgBreakpointGlyphFormatterImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Breakpoints/TextEditor/DbgBreakpointGlyphFormatterImpl.cs @@ -84,10 +84,10 @@ bool WriteLocation(IDbgTextWriter output, ITextView textView, SnapshotSpan span, output.Write(DbgTextColor.Text, string.Format(dnSpy_Debugger_DotNet_CorDebug_Resources.GlyphToolTip_NativeAddress, "0x" + location.NativeAddress.IP.ToString("X8"))); var documentViewer = textView.TextBuffer.TryGetDocumentViewer(); - Debug2.Assert(!(documentViewer is null)); + Debug2.Assert(documentViewer is not null); var statement = documentViewer?.GetMethodDebugService().FindByCodeOffset(new ModuleTokenId(location.Module, location.Token), location.Offset); - Debug2.Assert((!(documentViewer is null)) == (!(statement is null))); - if (!(statement is null)) { + Debug2.Assert((documentViewer is not null) == (statement is not null)); + if (statement is not null) { output.Write(DbgTextColor.Text, " ('"); var decompiler = (documentViewer?.DocumentTab?.Content as IDecompilerTabContent)?.Decompiler ?? decompilerService.Decompiler; decompiler.Write(new DbgTextColorWriter(output), statement.Value.Method, FormatterOptions.Default); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/CallStack/DbgEngineStackWalkerImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/CallStack/DbgEngineStackWalkerImpl.cs index 90d497b0ff..7d6d3e3d69 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/CallStack/DbgEngineStackWalkerImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/CallStack/DbgEngineStackWalkerImpl.cs @@ -163,7 +163,7 @@ DbgEngineStackFrame CreateErrorStackFrame() { } protected override void CloseCore(DbgDispatcher dispatcher) { - if (!(framesBuffer is null)) + if (framesBuffer is not null) engine.ReturnFramesBuffer(ref framesBuffer); framesBuffer = null; enumerator?.Dispose(); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/CallStack/ILDbgEngineStackFrame.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/CallStack/ILDbgEngineStackFrame.cs index dd5113127e..249666b00f 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/CallStack/ILDbgEngineStackFrame.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/CallStack/ILDbgEngineStackFrame.cs @@ -137,7 +137,7 @@ internal void GetFrameMethodInfo(out DmdModule? module, out int methodMetadataTo var corFrame = CorFrame; methodMetadataToken = (int)corFrame.Token; var corModule = corFrame.Function?.Module; - if (!(corModule is null)) { + if (corModule is not null) { module = engine.TryGetModule(corModule)?.GetReflectionModule() ?? throw new InvalidOperationException(); if (!corFrame.GetTypeAndMethodGenericParameters(out var typeGenArgs, out var methGenArgs)) throw new InvalidOperationException(); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/DAC/ClrDacImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/DAC/ClrDacImpl.cs index 7d91c64446..f09ca98499 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/DAC/ClrDacImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/DAC/ClrDacImpl.cs @@ -113,13 +113,13 @@ public override bool TryGetSymbolCore(ulong address, out SymbolResolverResult re string name; name = clrRuntime.GetJitHelperFunctionName(address); - if (!(name is null)) { + if (name is not null) { result = new SymbolResolverResult(SymbolKind.Function, name, address); return true; } name = clrRuntime.GetMethodTableName(address); - if (!(name is null)) { + if (name is not null) { result = new SymbolResolverResult(SymbolKind.Data, "methodtable(" + name + ")", address); return true; } @@ -129,7 +129,7 @@ public override bool TryGetSymbolCore(ulong address, out SymbolResolverResult re if (clrRuntime.ReadPointer(address, out ulong newAddress) && newAddress >= MIN_ADDR) method = clrRuntime.GetMethodByAddress(newAddress); } - if (!(method is null)) { + if (method is not null) { result = new SymbolResolverResult(SymbolKind.Function, method.ToString()!, address); return true; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/DAC/ClrDacProvider.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/DAC/ClrDacProvider.cs index 8a9e560fd8..8bd5cd69ff 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/DAC/ClrDacProvider.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/DAC/ClrDacProvider.cs @@ -34,7 +34,7 @@ public override ClrDac Create(int pid, string clrPath, IClrDacDebugger clrDacDeb if (clrPath is null) throw new ArgumentNullException(nameof(clrPath)); var clrDac = CreateCore(pid, clrPath, clrDacDebugger); - Debug2.Assert(!(clrDac is null)); + Debug2.Assert(clrDac is not null); return clrDac ?? NullClrDac.Instance; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Dialogs/AttachToProcess/DebuggableProcesses.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Dialogs/AttachToProcess/DebuggableProcesses.cs index ba2d250d42..ecd0f2a6ac 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Dialogs/AttachToProcess/DebuggableProcesses.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Dialogs/AttachToProcess/DebuggableProcesses.cs @@ -58,7 +58,7 @@ public static IEnumerable GetProcesses(int[] processIds, Func GetAppHostInfos(byte[] data) { hashDataSize = info.HashDataSize; } } - if (!(hash is null) && ByteArrayEquals(hash, info.Hash)) + if (hash is not null && ByteArrayEquals(hash, info.Hash)) yield return info; } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Breakpoints.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Breakpoints.cs index c9154b3a27..ef039e9718 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Breakpoints.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Breakpoints.cs @@ -55,8 +55,8 @@ public void Dispose() { void SendCodeBreakpointHitMessage_CorDebug(DnCodeBreakpoint breakpoint, DbgThread? thread) { debuggerThread.VerifyAccess(); var bpData = (BoundBreakpointData?)breakpoint.Tag; - Debug2.Assert(!(bpData is null)); - if (!(bpData is null)) + Debug2.Assert(bpData is not null); + if (bpData is not null) SendMessage(new DbgMessageBreakpoint(bpData.EngineBoundCodeBreakpoint.BoundCodeBreakpoint, thread, GetMessageFlags())); else SendMessage(new DbgMessageBreak(thread, GetMessageFlags())); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Evaluation.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Evaluation.cs index cb75ffafde..9bd04599b2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Evaluation.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Evaluation.cs @@ -43,8 +43,8 @@ internal DbgDotNetValue CreateDotNetValue_CorDebug(CorValue value, DmdAppDomain if (tryCreateStrongHandle && !value.IsNull && !value.IsHandle && value.IsReference && !type.IsPointer && !type.IsFunctionPointer && !type.IsByRef) { var derefValue = value.GetDereferencedValue(out int hr); var strongHandle = derefValue?.CreateHandle(CorDebugHandleType.HANDLE_STRONG); - Debug2.Assert(derefValue is null || !(strongHandle is null) || type == type.AppDomain.System_TypedReference); - if (!(strongHandle is null)) + Debug2.Assert(derefValue is null || strongHandle is not null || type == type.AppDomain.System_TypedReference); + if (strongHandle is not null) value = strongHandle; } @@ -132,9 +132,9 @@ internal void DisposeHandle_CorDebug(CorValue? value) { DbgDotNetRawValue? ReadField_CorDebug(DbgDotNetValueImpl obj, string fieldName1, string? fieldName2) { const DmdBindingFlags fieldFlags = DmdBindingFlags.Public | DmdBindingFlags.NonPublic | DmdBindingFlags.Instance; var field = obj.Type.GetField(fieldName1, fieldFlags); - if (field is null && !(fieldName2 is null)) + if (field is null && fieldName2 is not null) field = obj.Type.GetField(fieldName2, fieldFlags); - Debug2.Assert(!(field is null)); + Debug2.Assert(field is not null); if (field is null) return null; @@ -182,7 +182,7 @@ internal DbgDotNetValueResult FuncEvalCall_CorDebug(DbgEvaluationInfo evalInfo, debuggerThread.VerifyAccess(); evalInfo.CancellationToken.ThrowIfCancellationRequested(); var tmp = CheckFuncEval(evalInfo); - if (!(tmp is null)) + if (tmp is not null) return tmp.Value; Debug.Assert(!newObj || method.IsConstructor); @@ -232,14 +232,14 @@ internal DbgDotNetValueResult FuncEvalCall_CorDebug(DbgEvaluationInfo evalInfo, if (method is DmdMethodInfo m) declType = m.GetBaseDefinition().DeclaringType!; var val = converter.Convert(obj, declType, out origType); - if (!(val.ErrorMessage is null)) + if (val.ErrorMessage is not null) return DbgDotNetValueResult.CreateError(val.ErrorMessage); args[w++] = BoxIfNeeded(dnEval, appDomain, createdValues, val.CorValue!, declType, origType); } for (int i = 0; i < arguments.Length; i++) { var paramType = paramTypes[i]; var val = converter.Convert(arguments[i], paramType, out origType); - if (!(val.ErrorMessage is null)) + if (val.ErrorMessage is not null) return DbgDotNetValueResult.CreateError(val.ErrorMessage); var valType = origType ?? new ReflectionTypeCreator(this, method.AppDomain).Create(val.CorValue!.ExactType); args[w++] = BoxIfNeeded(dnEval, appDomain, createdValues, val.CorValue!, paramType, valType); @@ -327,7 +327,7 @@ internal DbgDotNetValueResult Box_CorDebug(DbgEvaluationInfo evalInfo, CorAppDom debuggerThread.VerifyAccess(); evalInfo.CancellationToken.ThrowIfCancellationRequested(); var tmp = CheckFuncEval(evalInfo); - if (!(tmp is null)) + if (tmp is not null) return tmp.Value; var dnThread = GetThread(evalInfo.Frame.Thread); @@ -363,7 +363,7 @@ internal DbgDotNetValueResult FuncEvalCreateInstanceNoCtor_CorDebug(DbgEvaluatio debuggerThread.VerifyAccess(); evalInfo.CancellationToken.ThrowIfCancellationRequested(); var tmp = CheckFuncEval(evalInfo); - if (!(tmp is null)) + if (tmp is not null) return tmp.Value; var dnThread = GetThread(evalInfo.Frame.Thread); @@ -406,7 +406,7 @@ internal DbgDotNetValueResult CreateValue_CorDebug(DbgEvaluationInfo evalInfo, I if (value is DbgDotNetValueImpl) return DbgDotNetValueResult.Create((DbgDotNetValueImpl)value); var tmp = CheckFuncEval(evalInfo); - if (!(tmp is null)) + if (tmp is not null) return tmp.Value; var dnThread = GetThread(evalInfo.Frame.Thread); @@ -422,7 +422,7 @@ internal DbgDotNetValueResult CreateValue_CorDebug(DbgEvaluationInfo evalInfo, I var converter = new EvalArgumentConverter(this, dnEval, appDomain, reflectionAppDomain, createdValues); var evalRes = converter.Convert(value, reflectionAppDomain.System_Object, out var newValueType); - if (!(evalRes.ErrorMessage is null)) + if (evalRes.ErrorMessage is not null) return DbgDotNetValueResult.CreateError(evalRes.ErrorMessage); var resultValue = CreateDotNetValue_CorDebug(evalRes.CorValue!, reflectionAppDomain, tryCreateStrongHandle: true); @@ -468,7 +468,7 @@ internal DbgDotNetValueResult CreateValue_CorDebug(DbgEvaluationInfo evalInfo, I evalInfo.CancellationToken.ThrowIfCancellationRequested(); var tmp = CheckFuncEval(evalInfo); - if (!(tmp is null)) + if (tmp is not null) return tmp.Value.ErrorMessage ?? throw new InvalidOperationException(); var dnThread = GetThread(evalInfo.Frame.Thread); @@ -485,7 +485,7 @@ internal DbgDotNetValueResult CreateValue_CorDebug(DbgEvaluationInfo evalInfo, I var converter = new EvalArgumentConverter(this, dnEval, appDomain, reflectionAppDomain, createdValues); var evalRes = converter.Convert(sourceValue, targetType, out var newValueType); - if (!(evalRes.ErrorMessage is null)) + if (evalRes.ErrorMessage is not null) return evalRes.ErrorMessage; var sourceCorValue = evalRes.CorValue!; @@ -609,7 +609,7 @@ static bool IsNoFuncEvalValue(object? value) { static bool RequiresNoFuncEvalToStoreValue(DmdType targetType, object? sourceValue) { // Boxing requires func-eval - if (!(targetType.IsValueType || targetType.IsPointer || targetType.IsFunctionPointer) && !(sourceValue is null)) + if (!(targetType.IsValueType || targetType.IsPointer || targetType.IsFunctionPointer) && sourceValue is not null) return false; // Only primitive value types are supported @@ -625,7 +625,7 @@ static bool RequiresNoFuncEvalToStoreValue(DmdType targetType, object? sourceVal int hr; if (targetType.IsPointer || targetType.IsFunctionPointer) { var sourceValueBytes = TryGetValueBytes(sourceValue); - Debug2.Assert(!(sourceValueBytes is null)); + Debug2.Assert(sourceValueBytes is not null); if (sourceValueBytes is null || targetValue.Size != (uint)sourceValueBytes.Length) return CordbgErrorHelper.InternalError; ulong address = targetValue.Address; @@ -637,7 +637,7 @@ static bool RequiresNoFuncEvalToStoreValue(DmdType targetType, object? sourceVal return null; } else if (!targetType.IsValueType) { - if (!(sourceValue is null)) + if (sourceValue is not null) return CordbgErrorHelper.InternalError; hr = targetValue.SetReferenceAddress(0); if (hr != 0) @@ -656,7 +656,7 @@ static bool RequiresNoFuncEvalToStoreValue(DmdType targetType, object? sourceVal if (!targetValue.IsGeneric || sourceValue is null) return CordbgErrorHelper.InternalError; var sourceValueBytes = TryGetValueBytes(sourceValue); - Debug2.Assert(!(sourceValueBytes is null)); + Debug2.Assert(sourceValueBytes is not null); if (sourceValueBytes is null || targetValue.Size != (uint)sourceValueBytes.Length) return CordbgErrorHelper.InternalError; hr = targetValue.WriteGenericValue(sourceValueBytes, dnThread.Process.CorProcess); @@ -703,7 +703,7 @@ internal DbgDotNetValueResult CreateSZArray_CorDebug(DbgEvaluationInfo evalInfo, debuggerThread.VerifyAccess(); evalInfo.CancellationToken.ThrowIfCancellationRequested(); var tmp = CheckFuncEval(evalInfo); - if (!(tmp is null)) + if (tmp is not null) return tmp.Value; var dnThread = GetThread(evalInfo.Frame.Thread); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.ModuleDef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.ModuleDef.cs index ea6245518c..bd7c2e8fdc 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.ModuleDef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.ModuleDef.cs @@ -32,12 +32,12 @@ sealed class AppDomainModuleState { void DnDebugger_OnCorModuleDefCreated(object? sender, CorModuleDefCreatedEventArgs e) { debuggerThread.VerifyAccess(); var appDomain = TryGetEngineAppDomain(e.Module.AppDomain)?.AppDomain; - Debug2.Assert(!(appDomain is null)); - if (!(appDomain is null)) { + Debug2.Assert(appDomain is not null); + if (appDomain is not null) { var state = appDomain.GetOrCreateData(); if (state.ModuleContext is null) { var reflectionAppDomain = appDomain.GetReflectionAppDomain(); - Debug2.Assert(!(reflectionAppDomain is null)); + Debug2.Assert(reflectionAppDomain is not null); state.ModuleContext = CreateModuleContext(reflectionAppDomain); } e.CorModuleDef.Context = state.ModuleContext; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Threads.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Threads.cs index c8764a1b92..cf16ae730f 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Threads.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.Threads.cs @@ -53,7 +53,7 @@ public DbgThreadData(DnThread dnThread, bool isMainThread) { } DbgThreadData? TryGetThreadData(DbgThread thread) { - if (!(thread is null) && thread.TryGetData(out DbgThreadData? data)) + if (thread is not null && thread.TryGetData(out DbgThreadData? data)) return data; return null; } @@ -131,7 +131,7 @@ string GetThreadKind(DnThread thread, bool isMainThread) { return PredefinedThreadKinds.Main; var s = GetThreadKind_ClrDac(thread); - if (!(s is null)) + if (s is not null) return s; if ((thread.CorThread.UserState & CorDebugUserState.USER_STOPPED) != 0) @@ -164,7 +164,7 @@ string GetThreadKind(DnThread thread, bool isMainThread) { (DbgEngineThread engineThread, DbgEngineThread.UpdateOptions updateOptions, ThreadProperties props)? UpdateThreadProperties_CorDebug(DnThread thread) { debuggerThread.VerifyAccess(); var engineThread = TryGetEngineThread(thread); - Debug2.Assert(!(engineThread is null)); + Debug2.Assert(engineThread is not null); if (engineThread is null) return null; return UpdateThreadProperties_CorDebug(engineThread); @@ -204,14 +204,14 @@ void UpdateThreadProperties_CorDebug() { threadsToUpdate = new List<(DbgEngineThread, DbgEngineThread.UpdateOptions, ThreadProperties)>(); threadsToUpdate.Add(info.Value); } - if (!(threadsToUpdate is null)) { + if (threadsToUpdate is not null) { foreach (var info in threadsToUpdate) NotifyThreadPropertiesChanged_CorDebug(info.engineThread, info.updateOptions, info.props); } } void DnDebugger_OnThreadAdded(object? sender, ThreadDebuggerEventArgs e) { - Debug2.Assert(!(objectFactory is null)); + Debug2.Assert(objectFactory is not null); if (e.Added) { bool isMainThread = IsMainThread(e.Thread); var props = GetThreadProperties_CorDebug(e.Thread, null, isCreateThread: true, forceReadName: false, isMainThread: isMainThread); @@ -228,7 +228,7 @@ void DnDebugger_OnThreadAdded(object? sender, ThreadDebuggerEventArgs e) { if (toEngineThread.TryGetValue(e.Thread, out engineThread)) toEngineThread.Remove(e.Thread); } - if (!(engineThread is null)) { + if (engineThread is not null) { e.ShouldPause = true; engineThread.Remove(GetMessageFlags()); } @@ -253,7 +253,7 @@ bool IsMainThread(DnThread thread) { bool IsNotMainThread(DnThread thread) { var info = clrDac.GetThreadInfo(thread.VolatileThreadId); - if (!(info is null)) { + if (info is not null) { var flags = info.Value.Flags; const ClrDacThreadFlags NotMainThreadFlags = ClrDacThreadFlags.IsFinalizer | @@ -300,10 +300,10 @@ void DetectMainThread() { } } } - if (!(mainThreadInfo.thread is null)) { + if (mainThreadInfo.thread is not null) { mainThreadInfo.data!.IsMainThread = true; var info = UpdateThreadProperties_CorDebug(mainThreadInfo.thread); - if (!(info is null)) + if (info is not null) NotifyThreadPropertiesChanged_CorDebug(info.Value.engineThread, info.Value.updateOptions, info.Value.props); } } @@ -372,7 +372,7 @@ void FreezeThawCore(DbgThread thread, bool freeze) { corThread.State = CorDebugThreadState.THREAD_RUN; } var info = UpdateThreadProperties_CorDebug(threadData.DnThread); - if (!(info is null)) + if (info is not null) NotifyThreadPropertiesChanged_CorDebug(info.Value.engineThread, info.Value.updateOptions, info.Value.props); } @@ -387,7 +387,7 @@ public override DbgEngineStackWalker CreateStackWalker(DbgThread thread) { ICorDebugFrame[]? framesBuffer = new ICorDebugFrame[framesBufferSize]; ICorDebugFrame[] GetFramesBuffer() => Interlocked.Exchange(ref framesBuffer, null) ?? new ICorDebugFrame[framesBufferSize]; internal void ReturnFramesBuffer(ref ICorDebugFrame[]? framesBuffer) { - Debug2.Assert(!(framesBuffer is null)); + Debug2.Assert(framesBuffer is not null); Interlocked.Exchange(ref this.framesBuffer, framesBuffer); framesBuffer = null; } @@ -403,7 +403,7 @@ void SetIP_CorDebug(DbgThread thread, DbgCodeLocation location) { SendMessage(new DbgMessageSetIPComplete(thread, framesInvalidated, messageFlags: GetMessageFlags(), error: error)); return; } - Debug2.Assert(!(corFrame is null)); + Debug2.Assert(corFrame is not null); framesInvalidated = true; bool failed = !corFrame.SetILFrameIP(offset); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.cs index 6936885df0..93ed6632b1 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DbgEngineImpl.cs @@ -160,7 +160,7 @@ void DnDebugger_DebugCallbackEvent(DnDebugger dbg, DebugCallbackEventArgs e) { if (!clrDacInitd) { clrDacInitd = true; var p = dnDebugger.Processes.FirstOrDefault(); - if (!(p is null)) + if (p is not null) clrDac = clrDacProvider.Create(p.ProcessId, dnDebugger.CLRPath, this); } break; @@ -186,7 +186,7 @@ void DnDebugger_DebugCallbackEvent(DnDebugger dbg, DebugCallbackEventArgs e) { var reflectionAppDomain = module?.GetReflectionModule()?.AppDomain; DbgDotNetValueImpl? dnExObj = null; try { - if (!(exObj is null) && !(reflectionAppDomain is null)) + if (exObj is not null && reflectionAppDomain is not null) dnExObj = CreateDotNetValue_CorDebug(exObj, reflectionAppDomain, tryCreateStrongHandle: false) as DbgDotNetValueImpl; objectFactory.CreateException(new DbgExceptionId(PredefinedExceptionCategories.DotNet, TryGetExceptionName(dnExObj) ?? "???"), exFlags, TryGetExceptionMessage(dnExObj), TryGetThread(e2.CorThread), module, GetMessageFlags()); e.AddPauseReason(DebuggerPauseReason.Other); @@ -209,7 +209,7 @@ void DnDebugger_DebugCallbackEvent(DnDebugger dbg, DebugCallbackEventArgs e) { break; var lmsgArgs = (LogMessageDebugCallbackEventArgs)e; msg = lmsgArgs.Message; - if (!(msg is null)) { + if (msg is not null) { e.AddPauseReason(DebuggerPauseReason.Other); var thread = TryGetThread(lmsgArgs.CorThread); SendMessage(new DbgMessageProgramMessage(msg, thread, GetMessageFlags())); @@ -219,16 +219,16 @@ void DnDebugger_DebugCallbackEvent(DnDebugger dbg, DebugCallbackEventArgs e) { case DebugCallbackKind.LoadClass: var lcArgs = (LoadClassDebugCallbackEventArgs)e; var cls = lcArgs.CorClass; - Debug2.Assert(!(cls is null)); - if (!(cls is null)) { + Debug2.Assert(cls is not null); + if (cls is not null) { var dnModule = dbg.TryGetModule(lcArgs.CorAppDomain, cls); if (dnModule!.IsDynamic == true) { UpdateDynamicModuleIds(dnModule); module = TryGetModule(dnModule.CorModule); - Debug2.Assert(!(module is null)); - if (!(module is null)) + Debug2.Assert(module is not null); + if (module is not null) dbgModuleMemoryRefreshedNotifier.RaiseModulesRefreshed(new[] { module }); - if (!(dnModule.CorModuleDef is null) && !(module is null)) { + if (dnModule.CorModuleDef is not null && module is not null) { if (TryGetModuleData(module, out var data)) data.OnLoadClass(); ClassLoaded?.Invoke(this, new ClassLoadedEventArgs(module, cls.Token)); @@ -295,12 +295,12 @@ internal DmdDynamicModuleHelperImpl GetDynamicModuleHelper(DnModule dnModule) { } DbgModule? TryGetModule(CorFrame? frame, CorThread? thread) { - if (frame?.Function is null && !(thread is null)) { + if (frame?.Function is null && thread is not null) { frame = thread.ActiveFrame; if (frame?.Function is null) { // Ignore the first frame(s) that have a null function. This rarely happens (eg. it // happens when debugging dnSpy built for .NET x86) - frame = thread.AllFrames.FirstOrDefault(a => !(a.Function is null)); + frame = thread.AllFrames.FirstOrDefault(a => a.Function is not null); } } return TryGetModule(frame?.Function?.Module); @@ -328,7 +328,7 @@ void HookDnDebuggerEvents() { } void UnhookDnDebuggerEventsAndCloseProcessHandle() { - if (!(dnDebugger is null)) { + if (dnDebugger is not null) { dnDebugger.DebugCallbackEvent -= DnDebugger_DebugCallbackEvent; dnDebugger.OnProcessStateChanged -= DnDebugger_OnProcessStateChanged; dnDebugger.OnNameChanged -= DnDebugger_OnNameChanged; @@ -345,7 +345,7 @@ void UnhookDnDebuggerEventsAndCloseProcessHandle() { void DnDebugger_OnAttachComplete(object? sender, EventArgs e) => DetectMainThread(); void DnDebugger_OnProcessStateChanged(object? sender, DebuggerEventArgs e) { - Debug2.Assert(!(sender is null) && sender == dnDebugger); + Debug2.Assert(sender is not null && sender == dnDebugger); if (dnDebugger.ProcessState == DebuggerProcessState.Terminated) { if (hProcess_debuggee is null || hProcess_debuggee.IsClosed || hProcess_debuggee.IsInvalid || !Native.NativeMethods.GetExitCodeProcess(hProcess_debuggee.DangerousGetHandle(), out int exitCode)) @@ -441,7 +441,7 @@ void DnDebugger_OnNameChanged(object? sender, NameChangedDebuggerEventArgs e) { } void DnDebugger_OnAppDomainAdded(object? sender, AppDomainDebuggerEventArgs e) { - Debug2.Assert(!(objectFactory is null)); + Debug2.Assert(objectFactory is not null); if (e.Added) { e.ShouldPause = true; var appDomain = dmdRuntime.CreateAppDomain(e.AppDomain.Id); @@ -470,7 +470,7 @@ void DnDebugger_OnAppDomainAdded(object? sender, AppDomainDebuggerEventArgs e) { } } } - if (!(engineAppDomain is null)) { + if (engineAppDomain is not null) { e.ShouldPause = true; engineAppDomain.Remove(GetMessageFlags()); } @@ -560,7 +560,7 @@ void UpdateDynamicModuleIds(DnModule dnModule) { if (data.ModuleId == moduleId) continue; data.UpdateModuleId(moduleId); - if (!(dnModule.CorModuleDef is null)) { + if (dnModule.CorModuleDef is not null) { //TODO: This doesn't update the treeview node dnModule.CorModuleDef.Name = moduleId.ModuleName; } @@ -570,7 +570,7 @@ void UpdateDynamicModuleIds(DnModule dnModule) { } } } - if (!(updatedModules is null)) { + if (updatedModules is not null) { foreach (var info in updatedModules) { var mdi = info.dnModule.CorModule.GetMetaDataInterface(); var scopeName = MDAPI.GetModuleName(mdi) ?? string.Empty; @@ -581,7 +581,7 @@ void UpdateDynamicModuleIds(DnModule dnModule) { } void DnDebugger_OnModuleAdded(object? sender, ModuleDebuggerEventArgs e) { - Debug2.Assert(!(objectFactory is null)); + Debug2.Assert(objectFactory is not null); if (e.Added) { e.ShouldPause = true; var appDomain = TryGetEngineAppDomain(e.Module.AppDomain)?.AppDomain; @@ -598,8 +598,8 @@ void DnDebugger_OnModuleAdded(object? sender, ModuleDebuggerEventArgs e) { var reflectionModule = ((DbgCorDebugInternalModuleImpl)engineModule.Module.InternalModule).ReflectionModule!; if (reflectionModule.IsCorLib) { var type = reflectionModule.AppDomain.GetWellKnownType(DmdWellKnownType.System_Diagnostics_Debugger_CrossThreadDependencyNotification, isOptional: true); - Debug2.Assert(!(type is null) || dnDebugger.DebuggeeVersion.StartsWith("v2.")); - if (!(type is null)) + Debug2.Assert(type is not null || dnDebugger.DebuggeeVersion.StartsWith("v2.")); + if (type is not null) dnDebugger.AddCustomNotificationClassToken(e.Module, (uint)type.MetadataToken); } } @@ -617,7 +617,7 @@ void DnDebugger_OnModuleAdded(object? sender, ModuleDebuggerEventArgs e) { ((DbgCorDebugInternalModuleImpl)engineModule.Module.InternalModule).Remove(); } } - if (!(engineModule is null)) { + if (engineModule is not null) { e.ShouldPause = true; engineModule.Remove(GetMessageFlags()); } @@ -692,7 +692,7 @@ void StartCore(CorDebugStartDebuggingOptions options) { BreakProcessKind = GetBreakProcessKind(options.BreakKind), Environment = env.Environment, }; - Debug2.Assert(!(dbgOptions.Filename is null)); + Debug2.Assert(dbgOptions.Filename is not null); dbgOptions.DebugOptions.IgnoreBreakInstructions = false; dbgOptions.DebugOptions.DebugOptionsProvider = new DebugOptionsProviderImpl(debuggerSettings); if (debuggerSettings.RedirectGuiConsoleOutput && PortableExecutableFileHelpers.IsGuiApp(options.Filename)) @@ -717,11 +717,11 @@ void StartCore(CorDebugStartDebuggingOptions options) { throw new InvalidOperationException(); } } - else if (!(cex is null) && cex.ErrorCode == ERROR_NOT_SUPPORTED) + else if (cex is not null && cex.ErrorCode == ERROR_NOT_SUPPORTED) errMsg = string.Format(dnSpy_Debugger_DotNet_CorDebug_Resources.Error_CouldNotStartDebugger, GetIncompatiblePlatformErrorMessage()); - else if (!(cex is null) && cex.ErrorCode == CordbgErrors.CORDBG_E_UNCOMPATIBLE_PLATFORMS) + else if (cex is not null && cex.ErrorCode == CordbgErrors.CORDBG_E_UNCOMPATIBLE_PLATFORMS) errMsg = string.Format(dnSpy_Debugger_DotNet_CorDebug_Resources.Error_CouldNotStartDebugger, GetIncompatiblePlatformErrorMessage()); - else if (!(cex is null) && cex.ErrorCode == unchecked((int)0x800702E4)) { + else if (cex is not null && cex.ErrorCode == unchecked((int)0x800702E4)) { // The x64 CLR debugger doesn't return the correct error code when we try to debug a 32-bit req-admin program. // It doesn't support debugging 32-bit programs, so it should return CORDBG_E_UNCOMPATIBLE_PLATFORMS or ERROR_NOT_SUPPORTED. if (IntPtr.Size == 8 && DotNetAssemblyUtilities.TryGetProgramBitness(options.Filename) == 32) @@ -822,7 +822,7 @@ internal DbgModule[] GetAssemblyModules(DbgModule module) { internal IDbgDotNetRuntime DotNetRuntime => internalRuntime; DbgCorDebugInternalRuntimeImpl internalRuntime; public override DbgInternalRuntime CreateInternalRuntime(DbgRuntime runtime) { - if (!(internalRuntime is null)) + if (internalRuntime is not null) throw new InvalidOperationException(); return internalRuntime = new DbgCorDebugInternalRuntimeImpl(this, runtime, dmdRuntime, CorDebugRuntimeKind, dnDebugger.DebuggeeVersion ?? string.Empty, dnDebugger.CLRPath, dnDebugger.RuntimeDirectory); } @@ -858,7 +858,7 @@ bool HasConnected_DebugThread { debuggerThread.VerifyAccess(); // If it's null, we haven't connected yet (most likely due to timeout, eg. trying to debug // a .NET Framework program with the .NET engine) - return !(dnDebugger is null); + return dnDebugger is not null; } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DebuggerThread.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DebuggerThread.cs index 3e5f05c6a7..2c98613909 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DebuggerThread.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DebuggerThread.cs @@ -78,7 +78,7 @@ void DebuggerThreadProc(AutoResetEvent autoResetEvent) { internal void Terminate() { terminate = true; try { callDispatcherRunEvent?.Set(); } catch (ObjectDisposedException) { } - if (!(Dispatcher is null) && !Dispatcher.HasShutdownStarted && !Dispatcher.HasShutdownFinished) + if (Dispatcher is not null && !Dispatcher.HasShutdownStarted && !Dispatcher.HasShutdownFinished) Dispatcher.BeginInvokeShutdown(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DmdDynamicModuleHelperImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DmdDynamicModuleHelperImpl.cs index 9824d7fe86..45cd4b7a8b 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DmdDynamicModuleHelperImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DmdDynamicModuleHelperImpl.cs @@ -67,7 +67,7 @@ public override void Dispose() { } var ilCode = func?.ILCode; if (ilCode is null) return null; - Debug2.Assert(!(func is null)); + Debug2.Assert(func is not null); ulong addr = ilCode.Address; if (addr == 0) return null; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DnlibAssemblyResolverImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DnlibAssemblyResolverImpl.cs index 6f0f20277e..7764c69271 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DnlibAssemblyResolverImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DnlibAssemblyResolverImpl.cs @@ -40,7 +40,7 @@ public DnlibAssemblyResolverImpl(DbgEngineImpl engine, DmdAppDomain appDomain) { if (dict.TryGetValue(assembly, out res)) return res; res = Lookup_CorDebug(assembly); - if (!(res is null)) { + if (res is not null) { dict[assembly] = res; dict[res] = res; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetDbgEngineImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetDbgEngineImpl.cs index ff5199d43d..6f2a846389 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetDbgEngineImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetDbgEngineImpl.cs @@ -38,7 +38,7 @@ sealed class DotNetDbgEngineImpl : DbgEngineImpl { public override DbgEngineRuntimeInfo RuntimeInfo { get { - Debug2.Assert(!(runtimeInfo is null)); + Debug2.Assert(runtimeInfo is not null); return runtimeInfo; } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetDbgProcessStarter.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetDbgProcessStarter.cs index 9532c44c05..b356cc8bd0 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetDbgProcessStarter.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetDbgProcessStarter.cs @@ -43,7 +43,7 @@ public override bool IsSupported(string filename, out ProcessStarterResult resul public override bool TryStart(string filename, [NotNullWhen(false)] out string? error) { var dotnetExeFilename = GetPathToDotNetExeHost(); - Debug2.Assert(!(dotnetExeFilename is null)); + Debug2.Assert(dotnetExeFilename is not null); var startInfo = new ProcessStartInfo(dotnetExeFilename); startInfo.WorkingDirectory = Path.GetDirectoryName(filename)!; startInfo.Arguments = $"exec \"{filename}\""; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetFrameworkDbgEngineImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetFrameworkDbgEngineImpl.cs index 19048ec0e7..b36a20164d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetFrameworkDbgEngineImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/DotNetFrameworkDbgEngineImpl.cs @@ -35,7 +35,7 @@ sealed class DotNetFrameworkDbgEngineImpl : DbgEngineImpl { public override DbgEngineRuntimeInfo RuntimeInfo { get { - Debug2.Assert(!(runtimeInfo is null)); + Debug2.Assert(runtimeInfo is not null); return runtimeInfo; } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgCorDebugInternalRuntimeImpl.NativeCode.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgCorDebugInternalRuntimeImpl.NativeCode.cs index 83865270b1..21b47be83c 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgCorDebugInternalRuntimeImpl.NativeCode.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgCorDebugInternalRuntimeImpl.NativeCode.cs @@ -250,7 +250,7 @@ bool TryGetNativeCodeCore(CorCode? code, DmdMethodBase? reflectionMethod, out Db } string? methodName = null, shortMethodName = null; - if (!(reflectionMethod is null)) { + if (reflectionMethod is not null) { shortMethodName = reflectionMethod.ToString(); methodName = shortMethodName + " (0x" + reflectionMethod.MetadataToken.ToString("X8") + ")"; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgCorDebugInternalRuntimeImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgCorDebugInternalRuntimeImpl.cs index ed6da3a2db..9f823c2529 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgCorDebugInternalRuntimeImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgCorDebugInternalRuntimeImpl.cs @@ -67,7 +67,7 @@ public DbgCorDebugInternalRuntimeImpl(DbgEngineImpl engine, DbgRuntime runtime, corDebugValueConverter = new CorDebugValueConverterImpl(this); classHooks = new Dictionary(); foreach (var info in ClassHookProvider.Create(this)) { - Debug2.Assert(!(info.Hook is null)); + Debug2.Assert(info.Hook is not null); Debug.Assert(!classHooks.ContainsKey(info.WellKnownType)); classHooks.Add(info.WellKnownType, info.Hook); } @@ -94,7 +94,7 @@ sealed class DynamicModuleMetadataState { public ModuleDefMD? Module; public int LoadClassVersion; public DbgDotNetRawModuleBytes ToDbgDotNetRawModuleBytes() { - if (!(RawBytes is null)) + if (RawBytes is not null) return new DbgDotNetRawModuleBytes(RawBytes, isFileLayout: true); return DbgDotNetRawModuleBytes.None; } @@ -109,7 +109,7 @@ DbgDotNetRawModuleBytes GetRawModuleBytesCore(DbgModule module) { return DbgDotNetRawModuleBytes.None; var state = module.GetOrCreateData(); - if (!(state.RawBytes is null) && state.LoadClassVersion == loadClassVersion) + if (state.RawBytes is not null && state.LoadClassVersion == loadClassVersion) return state.ToDbgDotNetRawModuleBytes(); var md = dnModule.GetOrCreateCorModuleDef(); @@ -172,11 +172,11 @@ bool TryGetMethodTokenCore(DbgModule module, int methodToken, out int metadataMe bool b = module.TryGetData(out state); Debug.Assert(b); } - if (!(state is null)) { + if (state is not null) { if (state.Module is null) state.Module = ModuleDefMD.Load(state.RawBytes); var method = state.Module.ResolveToken(methodToken) as MethodDef; - if (!(method is null)) { + if (method is not null) { metadataMethodToken = method.MDToken.ToInt32(); metadataLocalVarSigTok = (int)(method.Body?.LocalVarSigTok ?? 0); return true; @@ -221,7 +221,7 @@ sealed class GetFrameMethodState { static DmdMethodBase? TryGetMethod(DmdModule? module, int methodMetadataToken, IList genericTypeArguments, IList genericMethodArguments) { var method = module?.ResolveMethod(methodMetadataToken, (IList?)null, null, DmdResolveOptions.None); - if (!(method is null)) { + if (method is not null) { if (genericTypeArguments.Count != 0) { var type = method.ReflectedType!.MakeGenericType(genericTypeArguments); method = type.GetMethod(method.Module, method.MetadataToken, throwOnError: true)!; @@ -405,7 +405,7 @@ DbgDotNetValueResult LoadFieldCore(DbgEvaluationInfo evalInfo, DbgDotNetValue? o static DbgDotNetValueResult CreateSyntheticValue(DmdType type, object? constant) { var dnValue = SyntheticValueFactory.TryCreateSyntheticValue(type, constant); - if (!(dnValue is null)) + if (dnValue is not null) return DbgDotNetValueResult.Create(dnValue); return DbgDotNetValueResult.CreateError(CordbgErrorHelper.InternalError); } @@ -415,13 +415,13 @@ sealed class StaticConstructorInitializedState { } void InitializeStaticConstructor(DbgEvaluationInfo evalInfo, ILDbgEngineStackFrame ilFrame, DmdType type, CorType corType) { - if (!(engine.CheckFuncEval(evalInfo) is null)) + if (engine.CheckFuncEval(evalInfo) is not null) return; var state = type.GetOrCreateData(); if (state.Initialized > 0 || Interlocked.Exchange(ref state.Initialized, 1) != 0) return; var cctor = type.TypeInitializer; - if (!(cctor is null)) { + if (cctor is not null) { foreach (var field in type.DeclaredFields) { if (!field.IsStatic || field.IsLiteral) continue; @@ -429,14 +429,14 @@ void InitializeStaticConstructor(DbgEvaluationInfo evalInfo, ILDbgEngineStackFra var fieldValue = corType.GetStaticFieldValue((uint)field.MetadataToken, ilFrame.CorFrame, out int hr); if (hr == CordbgErrors.CORDBG_E_CLASS_NOT_LOADED || hr == CordbgErrors.CORDBG_E_STATIC_VAR_NOT_AVAILABLE) break; - if (!(fieldValue is null)) { + if (fieldValue is not null) { try { if (fieldValue.IsNull) continue; if (field.FieldType.IsValueType) { var objValue = fieldValue.GetDereferencedValue(out hr)?.GetBoxedValue(out hr); var data = objValue?.ReadGenericValue(); - if (!(data is null) && !IsZero(data)) + if (data is not null && !IsZero(data)) return; } else { @@ -484,7 +484,7 @@ bool RuntimeHelpersRunClassConstructor(DbgEvaluationInfo evalInfo, ILDbgEngineSt try { var reflectionAppDomain = type.AppDomain; var getTypeMethod = objValue.Type.GetMethod(nameof(object.GetType), DmdSignatureCallingConvention.Default | DmdSignatureCallingConvention.HasThis, 0, reflectionAppDomain.System_Type, Array.Empty(), throwOnError: false); - Debug2.Assert(!(getTypeMethod is null)); + Debug2.Assert(getTypeMethod is not null); if (getTypeMethod is null) return false; var corAppDomain = ilFrame.GetCorAppDomain(); @@ -493,11 +493,11 @@ bool RuntimeHelpersRunClassConstructor(DbgEvaluationInfo evalInfo, ILDbgEngineSt return false; var typeObj = getTypeRes.Value; var runtimeTypeHandleType = reflectionAppDomain.GetWellKnownType(DmdWellKnownType.System_RuntimeTypeHandle, isOptional: true); - Debug2.Assert(!(runtimeTypeHandleType is null)); + Debug2.Assert(runtimeTypeHandleType is not null); if (runtimeTypeHandleType is null) return false; var getTypeHandleMethod = typeObj.Type.GetMethod("get_" + nameof(Type.TypeHandle), DmdSignatureCallingConvention.Default | DmdSignatureCallingConvention.HasThis, 0, runtimeTypeHandleType, Array.Empty(), throwOnError: false); - Debug2.Assert(!(getTypeHandleMethod is null)); + Debug2.Assert(getTypeHandleMethod is not null); if (getTypeHandleMethod is null) return false; typeHandleRes = engine.FuncEvalCall_CorDebug(evalInfo, corAppDomain, getTypeHandleMethod, typeObj, Array.Empty(), false); @@ -505,7 +505,7 @@ bool RuntimeHelpersRunClassConstructor(DbgEvaluationInfo evalInfo, ILDbgEngineSt return false; var runtimeHelpersType = reflectionAppDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, isOptional: true); var runClassConstructorMethod = runtimeHelpersType?.GetMethod(nameof(RuntimeHelpers.RunClassConstructor), DmdSignatureCallingConvention.Default, 0, reflectionAppDomain.System_Void, new[] { runtimeTypeHandleType }, throwOnError: false); - Debug2.Assert(!(runClassConstructorMethod is null)); + Debug2.Assert(runClassConstructorMethod is not null); if (runClassConstructorMethod is null) return false; res = engine.FuncEvalCall_CorDebug(evalInfo, corAppDomain, runClassConstructorMethod, null, new[] { typeHandleRes.Value }, false); @@ -574,7 +574,7 @@ DbgDotNetValueResult CallCore(DbgEvaluationInfo evalInfo, DbgDotNetValue? obj, D if (DmdWellKnownTypeUtils.TryGetWellKnownType(typeName, out var wellKnownType)) { if (classHooks.TryGetValue(wellKnownType, out var hook) && type == type.AppDomain.GetWellKnownType(wellKnownType, isOptional: true)) { var res = hook.Call(obj, method, arguments); - if (!(res is null)) + if (res is not null) return DbgDotNetValueResult.Create(res); } } @@ -611,7 +611,7 @@ DbgDotNetValueResult CreateInstanceCore(DbgEvaluationInfo evalInfo, DmdConstruct if (DmdWellKnownTypeUtils.TryGetWellKnownType(typeName, out var wellKnownType)) { if (classHooks.TryGetValue(wellKnownType, out var hook) && type == type.AppDomain.GetWellKnownType(wellKnownType, isOptional: true)) { var res = hook.CreateInstance(ctor, arguments); - if (!(res is null)) + if (res is not null) return DbgDotNetValueResult.Create(res); } } @@ -690,7 +690,7 @@ DbgDotNetValueResult CreateSZArrayCore_Array_CreateInstance(DbgEvaluationInfo ev var res = engine.FuncEvalCall_CorDebug(evalInfo, ilFrame.GetCorAppDomain(), methodGetType, null, new[] { elementType.AssemblyQualifiedName }, false); if (res.HasError || res.ValueIsException) return res; - Debug2.Assert(!(res.Value is null)); + Debug2.Assert(res.Value is not null); typeElementType = res.Value; if (res.Value.IsNull) return DbgDotNetValueResult.CreateError(PredefinedEvaluationErrorMessages.InternalDebuggerError); @@ -768,7 +768,7 @@ DbgDotNetValueResult CreateArrayCore(DbgEvaluationInfo evalInfo, DmdType element var res = engine.FuncEvalCall_CorDebug(evalInfo, ilFrame.GetCorAppDomain(), methodGetType, null, new[] { elementType.AssemblyQualifiedName }, false); if (res.HasError || res.ValueIsException) return res; - Debug2.Assert(!(res.Value is null)); + Debug2.Assert(res.Value is not null); typeElementType = res.Value; if (res.Value.IsNull) return DbgDotNetValueResult.CreateError(PredefinedEvaluationErrorMessages.InternalDebuggerError); @@ -818,15 +818,15 @@ DbgDotNetAliasInfo[] GetAliasesCore(DbgEvaluationInfo evalInfo) { stowedException = GetStowedExceptionCore(evalInfo, DbgDotNetRuntimeConstants.StowedExceptionId); returnValues = GetReturnValuesCore(evalInfo); - int count = (!(exception is null) ? 1 : 0) + (!(stowedException is null) ? 1 : 0) + returnValues.Length + (returnValues.Length != 0 ? 1 : 0); + int count = (exception is not null ? 1 : 0) + (stowedException is not null ? 1 : 0) + returnValues.Length + (returnValues.Length != 0 ? 1 : 0); if (count == 0) return Array.Empty(); var res = new DbgDotNetAliasInfo[count]; int w = 0; - if (!(exception is null)) + if (exception is not null) res[w++] = new DbgDotNetAliasInfo(DbgDotNetAliasInfoKind.Exception, exception.Type, DbgDotNetRuntimeConstants.ExceptionId, Guid.Empty, null); - if (!(stowedException is null)) + if (stowedException is not null) res[w++] = new DbgDotNetAliasInfo(DbgDotNetAliasInfoKind.StowedException, stowedException.Type, DbgDotNetRuntimeConstants.StowedExceptionId, Guid.Empty, null); if (returnValues.Length != 0) { res[w++] = new DbgDotNetAliasInfo(DbgDotNetAliasInfoKind.ReturnValue, returnValues[returnValues.Length - 1].Value.Type, DbgDotNetRuntimeConstants.LastReturnValueId, Guid.Empty, null); @@ -867,14 +867,14 @@ DbgDotNetExceptionInfo[] GetExceptionsCore(DbgEvaluationInfo evalInfo) { try { exception = GetExceptionCore(evalInfo, DbgDotNetRuntimeConstants.ExceptionId); stowedException = GetStowedExceptionCore(evalInfo, DbgDotNetRuntimeConstants.StowedExceptionId); - int count = (!(exception is null) ? 1 : 0) + (!(stowedException is null) ? 1 : 0); + int count = (exception is not null ? 1 : 0) + (stowedException is not null ? 1 : 0); if (count == 0) return Array.Empty(); var res = new DbgDotNetExceptionInfo[count]; int w = 0; - if (!(exception is null)) + if (exception is not null) res[w++] = new DbgDotNetExceptionInfo(exception, DbgDotNetRuntimeConstants.ExceptionId, DbgDotNetExceptionInfoFlags.None); - if (!(stowedException is null)) + if (stowedException is not null) res[w++] = new DbgDotNetExceptionInfo(stowedException, DbgDotNetRuntimeConstants.StowedExceptionId, DbgDotNetExceptionInfoFlags.StowedException); if (w != res.Length) throw new InvalidOperationException(); @@ -1133,10 +1133,10 @@ DbgDotNetValueResult BoxCore(DbgEvaluationInfo evalInfo, object? value) { DbgDotNetValueResult res = default; try { res = CreateValueCore(evalInfo, value); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; var boxedValue = res.Value!.Box(evalInfo); - if (!(boxedValue is null)) + if (boxedValue is not null) return boxedValue.Value; return DbgDotNetValueResult.CreateError(PredefinedEvaluationErrorMessages.InternalDebuggerError); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgDotNetRawValueFactory.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgDotNetRawValueFactory.cs index 9019a95415..898451c7d0 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgDotNetRawValueFactory.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgDotNetRawValueFactory.cs @@ -35,8 +35,8 @@ readonly struct DbgDotNetRawValueFactory { static DbgDotNetRawValueFactory() { var ctor = typeof(DateTime).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(ulong) }, null); - Debug2.Assert(!(ctor is null)); - if (!(ctor is null)) { + Debug2.Assert(ctor is not null); + if (ctor is not null) { var dm = new DynamicMethod("DateTime_ctor_UInt64", typeof(DateTime), new[] { typeof(ulong) }, true); var ilg = dm.GetILGenerator(); ilg.Emit(OpCodes.Ldarg_0); @@ -219,7 +219,7 @@ DbgDotNetRawValue Create(CorValue value, DmdType type, int recursionCounter) { data = v.ReadGenericValue(); if (data is null) break; - if (!(DateTime_ctor_UInt64 is null)) + if (DateTime_ctor_UInt64 is not null) return new DbgDotNetRawValue(DbgSimpleValueType.DateTime, DateTime_ctor_UInt64(BitConverter.ToUInt64(data, 0))); return new DbgDotNetRawValue(DbgSimpleValueType.DateTime, default(DateTime)); @@ -265,7 +265,7 @@ bool GetNullableValue(DmdType nullableType, CorValue nullableValue, out CorValue var info = NullableTypeUtils.TryGetNullableFields(nullableType); if (info.hasValueField is null) return false; - Debug2.Assert(!(info.valueField is null)); + Debug2.Assert(info.valueField is not null); var cls = nullableValue.ExactType?.Class; var hasValueValue = nullableValue.GetFieldValue(cls, (uint)info.hasValueField.MetadataToken); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgDotNetValueImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgDotNetValueImpl.cs index 3e300a5264..9d4e72113c 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgDotNetValueImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DbgDotNetValueImpl.cs @@ -227,7 +227,7 @@ bool GetArrayInfo_CorDebug(out uint elementCount, [NotNullWhen(true)] out DbgDot elementCount = obj.Value.ArrayCount; var baseIndexes = (obj.Value.HasBaseIndicies ? obj.Value.BaseIndicies : null) ?? Array.Empty(); var dimensions = obj.Value.Dimensions; - if (!(dimensions is null)) { + if (dimensions is not null) { var infos = new DbgDotNetArrayDimensionInfo[dimensions.Length]; for (int i = 0; i < infos.Length; i++) infos[i] = new DbgDotNetArrayDimensionInfo((int)(i < baseIndexes.Length ? baseIndexes[i] : 0), dimensions[i]); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DmdEvaluatorImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DmdEvaluatorImpl.cs index 3d04d2618a..dd0934a9e7 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DmdEvaluatorImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/DmdEvaluatorImpl.cs @@ -50,9 +50,9 @@ DbgEvaluationInfo GetEvaluationInfo(object? context) { } object GetValueThrow(DbgDotNetValueResult result) { - if (!(result.ErrorMessage is null)) + if (result.ErrorMessage is not null) throw new DmdEvaluatorException(result.ErrorMessage); - Debug2.Assert(!(result.Value is null)); + Debug2.Assert(result.Value is not null); if (result.ValueIsException) { var msg = "An exception was thrown: " + result.Value.Type.FullName; result.Value.Dispose(); @@ -82,7 +82,7 @@ object GetValueThrow(DbgDotNetValueResult result) { public override void StoreField(object? context, DmdFieldInfo field, object? obj, object? value) { var evalInfo = GetEvaluationInfo(context); var errorMessage = engine.DotNetRuntime.StoreField(evalInfo, GetDotNetValue(obj), field, value); - if (!(errorMessage is null)) + if (errorMessage is not null) throw new DmdEvaluatorException(errorMessage); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/EvalArgumentConverter.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/EvalArgumentConverter.cs index 5409a42667..4318e85143 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/EvalArgumentConverter.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/EvalArgumentConverter.cs @@ -80,7 +80,7 @@ public unsafe EvalArgumentResult Convert(object? value, DmdType defaultType, out if (value is DbgDotNetValueImpl dnValueImpl) { type = dnValueImpl.Type; var corValue = dnValueImpl.TryGetCorValue(); - if (!(corValue is null)) + if (corValue is not null) return new EvalArgumentResult(corValue); return new EvalArgumentResult(PredefinedEvaluationErrorMessages.InternalDebuggerError); } @@ -234,7 +234,7 @@ EvalArgumentResult ConvertSZArray(string[] array, out DmdType type) { continue; var stringValueRes = Convert(s, elementType, out var type2); - if (!(stringValueRes.ErrorMessage is null)) + if (stringValueRes.ErrorMessage is not null) return stringValueRes; if (!stringValueRes.CorValue!.IsReference) return new EvalArgumentResult(PredefinedEvaluationErrorMessages.InternalDebuggerError); @@ -287,7 +287,7 @@ unsafe EvalArgumentResult ConvertSZArray(void* array, int length, int elementSiz CorValue? arrayValue = res.Value.ResultOrException!; if (arrayValue.IsReference) { arrayValue = arrayValue.GetDereferencedValue(out hr); - if (!(arrayValue is null)) + if (arrayValue is not null) return new EvalArgumentResult(CordbgErrorHelper.GetErrorMessage(hr)); } Debug.Assert(arrayValue?.IsArray == true); @@ -315,7 +315,7 @@ unsafe EvalArgumentResult ConvertSZArray(void* array, int length, int elementSiz static bool IsInitialized(T[] array) where T : class { for (int i = 0; i < array.Length; i++) { - if (!(array[i] is null)) + if (array[i] is not null) return true; } return false; @@ -360,9 +360,9 @@ static unsafe bool IsInitialized(void* array, int length) { CorType GetType(DmdType type) => CorDebugTypeCreator.GetType(engine, appDomain, type); CorValue? AddValue(DmdType type, CorValue? value) { - if (!(value is null) && !value.IsNull && !value.IsHandle && value.IsReference && !type.IsPointer && !type.IsFunctionPointer && !type.IsByRef) + if (value is not null && !value.IsNull && !value.IsHandle && value.IsReference && !type.IsPointer && !type.IsFunctionPointer && !type.IsByRef) value = value.GetDereferencedValue(out int hr)?.CreateHandle(CorDebugHandleType.HANDLE_STRONG) ?? value; - if (!(value is null)) { + if (value is not null) { try { createdValues.Add(value); } @@ -378,16 +378,16 @@ EvalArgumentResult CreateNoConstructor(DmdType type) { var res = dnEval.CreateDontCallConstructor(GetType(type), out int hr); var argRes = EvalArgumentResult.Create(res, hr); var value = AddValue(type, argRes.CorValue); - if (!(value is null)) + if (value is not null) return new EvalArgumentResult(value); return argRes; } EvalArgumentResult CreateByte(DmdType type, byte value) { var res = CreateNoConstructor(type); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; - Debug2.Assert(!(res.CorValue!.DereferencedValue is null) && !(res.CorValue.DereferencedValue.BoxedValue is null)); + Debug2.Assert(res.CorValue!.DereferencedValue is not null && res.CorValue.DereferencedValue.BoxedValue is not null); if (value != 0) res.CorValue.DereferencedValue.BoxedValue.WriteGenericValue(new byte[1] { value }); return res; @@ -395,9 +395,9 @@ EvalArgumentResult CreateByte(DmdType type, byte value) { EvalArgumentResult CreateUInt16(DmdType type, ushort value) { var res = CreateNoConstructor(type); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; - Debug2.Assert(!(res.CorValue!.DereferencedValue is null) && !(res.CorValue.DereferencedValue.BoxedValue is null)); + Debug2.Assert(res.CorValue!.DereferencedValue is not null && res.CorValue.DereferencedValue.BoxedValue is not null); if (value != 0) res.CorValue.DereferencedValue.BoxedValue.WriteGenericValue(BitConverter.GetBytes(value)); return res; @@ -405,9 +405,9 @@ EvalArgumentResult CreateUInt16(DmdType type, ushort value) { EvalArgumentResult CreateUInt32(DmdType type, uint value) { var res = CreateNoConstructor(type); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; - Debug2.Assert(!(res.CorValue!.DereferencedValue is null) && !(res.CorValue.DereferencedValue.BoxedValue is null)); + Debug2.Assert(res.CorValue!.DereferencedValue is not null && res.CorValue.DereferencedValue.BoxedValue is not null); if (value != 0) res.CorValue.DereferencedValue.BoxedValue.WriteGenericValue(BitConverter.GetBytes(value)); return res; @@ -415,9 +415,9 @@ EvalArgumentResult CreateUInt32(DmdType type, uint value) { EvalArgumentResult CreateUInt64(DmdType type, ulong value) { var res = CreateNoConstructor(type); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; - Debug2.Assert(!(res.CorValue!.DereferencedValue is null) && !(res.CorValue.DereferencedValue.BoxedValue is null)); + Debug2.Assert(res.CorValue!.DereferencedValue is not null && res.CorValue.DereferencedValue.BoxedValue is not null); if (value != 0) res.CorValue.DereferencedValue.BoxedValue.WriteGenericValue(BitConverter.GetBytes(value)); return res; @@ -425,9 +425,9 @@ EvalArgumentResult CreateUInt64(DmdType type, ulong value) { EvalArgumentResult CreateSingle(float value) { var res = CreateNoConstructor(reflectionAppDomain.System_Single); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; - Debug2.Assert(!(res.CorValue!.DereferencedValue is null) && !(res.CorValue.DereferencedValue.BoxedValue is null)); + Debug2.Assert(res.CorValue!.DereferencedValue is not null && res.CorValue.DereferencedValue.BoxedValue is not null); if (value != 0) res.CorValue.DereferencedValue.BoxedValue.WriteGenericValue(BitConverter.GetBytes(value)); return res; @@ -435,9 +435,9 @@ EvalArgumentResult CreateSingle(float value) { EvalArgumentResult CreateDouble(double value) { var res = CreateNoConstructor(reflectionAppDomain.System_Double); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; - Debug2.Assert(!(res.CorValue!.DereferencedValue is null) && !(res.CorValue.DereferencedValue.BoxedValue is null)); + Debug2.Assert(res.CorValue!.DereferencedValue is not null && res.CorValue.DereferencedValue.BoxedValue is not null); if (value != 0) res.CorValue.DereferencedValue.BoxedValue.WriteGenericValue(BitConverter.GetBytes(value)); return res; @@ -445,9 +445,9 @@ EvalArgumentResult CreateDouble(double value) { EvalArgumentResult CreateDecimal(decimal value) { var res = CreateNoConstructor(reflectionAppDomain.System_Decimal); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; - Debug2.Assert(!(res.CorValue!.DereferencedValue is null) && !(res.CorValue.DereferencedValue.BoxedValue is null)); + Debug2.Assert(res.CorValue!.DereferencedValue is not null && res.CorValue.DereferencedValue.BoxedValue is not null); if (value != 0) res.CorValue.DereferencedValue.BoxedValue.WriteGenericValue(GetBytes(value)); return res; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/Hooks/CorDebugValueConverterImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/Hooks/CorDebugValueConverterImpl.cs index 45e9f66595..fe81f30af9 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/Hooks/CorDebugValueConverterImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/Hooks/CorDebugValueConverterImpl.cs @@ -34,7 +34,7 @@ bool TryGetUInt32(object? value, out uint result) { if (rawValue.HasRawValue) value = rawValue.RawValue; } - if (!(value is null)) { + if (value is not null) { if (value is bool) { result = (bool)value ? 1U : 0; return true; @@ -100,7 +100,7 @@ int ICorDebugValueConverter.ToInt32(object? value) { var type = dnValue.Type; if (type.IsArray && type.GetElementType() == type.AppDomain.System_Char) { var addr = dnValue.GetRawAddressValue(onlyDataAddress: true); - if (!(addr is null)) { + if (addr is not null) { ulong chars = addr.Value.Length / 2; if (chars <= int.MaxValue / 2) { if (chars == 0) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/NullableTypeUtils.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/NullableTypeUtils.cs index d5794f142d..0e9725beae 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/NullableTypeUtils.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/Evaluation/NullableTypeUtils.cs @@ -34,12 +34,12 @@ public static (DmdFieldInfo? hasValueField, DmdFieldInfo? valueField) TryGetNull continue; switch (field.Name) { case KnownMemberNames.Nullable_HasValue_FieldName: - if (!(hasValueField is null)) + if (hasValueField is not null) return (null, null); hasValueField = field; break; case KnownMemberNames.Nullable_Value_FieldName: - if (!(valueField is null)) + if (valueField is not null) return (null, null); valueField = field; break; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/ModuleCreator.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/ModuleCreator.cs index d4c4b1a2e7..6422469902 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/ModuleCreator.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Impl/ModuleCreator.cs @@ -159,7 +159,7 @@ static void InitializeExeFields(DnModule dnModule, string filename, DbgImageLayo Debug.Assert(imageLayout == DbgImageLayout.File, nameof(GetFileVersion) + " assumes file layout"); var bytes = dnModule.Process.CorProcess.ReadMemory(dnModule.Address, (int)dnModule.Size); - if (!(bytes is null)) { + if (bytes is not null) { try { version = GetFileVersion(bytes); using (var peImage = new PEImage(bytes, imageLayout == DbgImageLayout.File ? ImageLayout.File : ImageLayout.Memory, true)) @@ -237,7 +237,7 @@ static string GetFileVersion(byte[] bytes) { } finally { try { - if (!(tempFilename is null)) + if (tempFilename is not null) File.Delete(tempFilename); } catch { } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Metadata/DbgAssemblyInfoProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Metadata/DbgAssemblyInfoProviderImpl.cs index 380fb3c685..606c296d50 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Metadata/DbgAssemblyInfoProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Metadata/DbgAssemblyInfoProviderImpl.cs @@ -27,7 +27,7 @@ namespace dnSpy.Debugger.DotNet.CorDebug.Metadata { sealed class DbgAssemblyInfoProviderFactoryImpl : DbgAssemblyInfoProviderFactory { public override DbgAssemblyInfoProvider? Create(DbgRuntime runtime) { var engine = DbgEngineImpl.TryGetEngine(runtime); - if (!(engine is null)) + if (engine is not null) return new DbgAssemblyInfoProviderImpl(engine); return null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Metadata/DbgDynamicModuleProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Metadata/DbgDynamicModuleProviderImpl.cs index cc19f2d011..0dcbed1ce6 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Metadata/DbgDynamicModuleProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Metadata/DbgDynamicModuleProviderImpl.cs @@ -34,7 +34,7 @@ namespace dnSpy.Debugger.DotNet.CorDebug.Metadata { sealed class DbgDynamicModuleProviderFactoryImpl : DbgDynamicModuleProviderFactory { public override DbgDynamicModuleProvider? Create(DbgRuntime runtime) { var engine = DbgEngineImpl.TryGetEngine(runtime); - if (!(engine is null)) + if (engine is not null) return runtime.GetOrCreateData(() => new DbgDynamicModuleProviderImpl(engine)); return null; @@ -63,15 +63,15 @@ sealed class DynamicModuleData { public override ModuleDef? GetDynamicMetadata(DbgModule module, out ModuleId moduleId) { var data = module.GetOrCreateData(); - if (!(data.Metadata is null)) { + if (data.Metadata is not null) { moduleId = data.ModuleId; return data.Metadata; } var info = Invoke(() => { - if (!(data.Metadata is null)) + if (data.Metadata is not null) return (metadata: data.Metadata, moduleId: data.ModuleId); var info2 = engine.GetDynamicMetadata_EngineThread(module); - if (!(info2.metadata is null)) { + if (info2.metadata is not null) { // DsDotNetDocumentBase sets EnableTypeDefFindCache to true and that property accesses the // Types property. It must be initialized in the correct thread. _ = info2.metadata.Types; @@ -91,7 +91,7 @@ public override void LoadEverything(DbgModule[] modules, bool started) { engine.VerifyCorDebugThread(); foreach (var module in modules) { var md = TryGetDynamicMetadata(module); - if (!(md is null)) + if (md is not null) md.DisableMDAPICalls = !started; } } @@ -193,7 +193,7 @@ public override IEnumerable GetModifiedTypes(DbgModule module) { public override void InitializeNonLoadedClasses(DbgModule module, uint[] nonLoadedTokens) { engine.VerifyCorDebugThread(); var cmod = TryGetDynamicMetadata(module); - Debug2.Assert(!(cmod is null)); + Debug2.Assert(cmod is not null); if (cmod is null) return; foreach (uint token in nonLoadedTokens) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Steppers/DbgDotNetEngineStepperImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Steppers/DbgDotNetEngineStepperImpl.cs index de6cefd421..8d363037d2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Steppers/DbgDotNetEngineStepperImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Steppers/DbgDotNetEngineStepperImpl.cs @@ -66,7 +66,7 @@ public override bool TryGetLocation([NotNullWhen(true)] out DbgModule? module, o token = func?.Token ?? 0; var offs = GetILOffset(CorFrame); offset = offs ?? 0; - return !(module is null) && token != 0 && !(offs is null); + return module is not null && token != 0 && offs is not null; } public override bool Equals(DbgDotNetEngineStepperFrameInfo other) { @@ -122,9 +122,9 @@ public void Hit(ReturnValueState rvState, CorThread? corThread, uint offset) { return; if (!rvState.CorThread.Equals(corThread)) return; - Debug2.Assert(!(corThread is null)); + Debug2.Assert(corThread is not null); var corFrame = corThread.ActiveFrame; - Debug2.Assert(!(corFrame is null)); + Debug2.Assert(corFrame is not null); if (corFrame is null) return; if (rvState.StackStart != corFrame.StackStart || rvState.StackEnd != corFrame.StackEnd || rvState.Token != corFrame.Token) @@ -137,10 +137,10 @@ public void Hit(ReturnValueState rvState, CorThread? corThread, uint offset) { bool error = true; try { corValue = corFrame.GetReturnValueForILOffset(offset); - if (!(corValue is null)) { + if (corValue is not null) { var reflectionModule = engine.TryGetModule(corFrame.Function?.Module)?.GetReflectionModule(); - Debug2.Assert(!(reflectionModule is null)); - if (!(reflectionModule is null)) { + Debug2.Assert(reflectionModule is not null); + if (reflectionModule is not null) { if (ReturnValues.Count >= maxReturnValues) { TooManyReturnValues = true; RemoveAllBreakpointsCore(); @@ -252,7 +252,7 @@ public DbgDotNetEngineStepperImpl(DbgEngineImpl engine, DnDebugger dnDebugger) { public override Task StepOutAsync(DbgDotNetEngineStepperFrameInfo frame) { engine.VerifyCorDebugThread(); - Debug2.Assert(!(session is null)); + Debug2.Assert(session is not null); var frameImpl = (DbgDotNetEngineStepperFrameInfoImpl)frame; Debug.Assert(dnDebugger.ProcessState == DebuggerProcessState.Paused); CorStepper? newCorStepper = null; @@ -261,10 +261,10 @@ public override Task StepOutAsync(DbgDotNetEngineStepperFrameInfo fra if (canceled) tcs.SetCanceled(); else { - Debug2.Assert(!(e is null)); + Debug2.Assert(e is not null); e.AddPauseReason(DebuggerPauseReason.Other); var thread = engine.TryGetThread(e.CorThread); - if (!(thread is null)) + if (thread is not null) tcs.SetResult(thread); else tcs.SetException(new InvalidOperationException()); @@ -277,7 +277,7 @@ public override Task StepOutAsync(DbgDotNetEngineStepperFrameInfo fra public override Task StepIntoAsync(DbgDotNetEngineStepperFrameInfo frame, DbgCodeRange[] ranges) { engine.VerifyCorDebugThread(); - Debug2.Assert(!(session is null)); + Debug2.Assert(session is not null); var frameImpl = (DbgDotNetEngineStepperFrameInfoImpl)frame; Debug.Assert(dnDebugger.ProcessState == DebuggerProcessState.Paused); CorStepper? newCorStepper = null; @@ -287,10 +287,10 @@ public override Task StepIntoAsync(DbgDotNetEngineStepperFrameInfo fr if (canceled) tcs.SetCanceled(); else { - Debug2.Assert(!(e is null)); + Debug2.Assert(e is not null); e.AddPauseReason(DebuggerPauseReason.Other); var thread = engine.TryGetThread(e.CorThread); - if (!(thread is null)) + if (thread is not null) tcs.SetResult(thread); else tcs.SetException(new InvalidOperationException()); @@ -303,7 +303,7 @@ public override Task StepIntoAsync(DbgDotNetEngineStepperFrameInfo fr public override Task StepOverAsync(DbgDotNetEngineStepperFrameInfo frame, DbgCodeRange[] ranges) { engine.VerifyCorDebugThread(); - Debug2.Assert(!(session is null)); + Debug2.Assert(session is not null); var frameImpl = (DbgDotNetEngineStepperFrameInfoImpl)frame; Debug.Assert(dnDebugger.ProcessState == DebuggerProcessState.Paused); CorStepper? newCorStepper = null; @@ -313,10 +313,10 @@ public override Task StepOverAsync(DbgDotNetEngineStepperFrameInfo fr if (canceled) tcs.SetCanceled(); else { - Debug2.Assert(!(e is null)); + Debug2.Assert(e is not null); e.AddPauseReason(DebuggerPauseReason.Other); var thread = engine.TryGetThread(e.CorThread); - if (!(thread is null)) + if (thread is not null) tcs.SetResult(thread); else tcs.SetException(new InvalidOperationException()); @@ -329,14 +329,14 @@ public override Task StepOverAsync(DbgDotNetEngineStepperFrameInfo fr public override void OnStepComplete() { engine.VerifyCorDebugThread(); - Debug2.Assert(!(session is null)); + Debug2.Assert(session is not null); var returnValues = session.TakeOwnershipOfReturnValues() ?? Array.Empty(); engine.SetReturnValues(returnValues); } public override void CollectReturnValues(DbgDotNetEngineStepperFrameInfo frame, DbgILInstruction[][] statementInstructions) { engine.VerifyCorDebugThread(); - Debug2.Assert(!(session is null)); + Debug2.Assert(session is not null); var frameImpl = (DbgDotNetEngineStepperFrameInfoImpl)frame; if (statementInstructions.Length == 0) return; @@ -366,7 +366,7 @@ public override void CollectReturnValues(DbgDotNetEngineStepperFrameInfo frame, if (liveOffsets.Length == 0) continue; var method = GetMethod(frameImpl.CorFrame, (int)instr.Operand, ref reflectionModule, ref genericTypeArguments, ref genericMethodArguments); - Debug2.Assert(!(method is null)); + Debug2.Assert(method is not null); if (method is null) continue; bps.Clear(); @@ -461,7 +461,7 @@ void CancelStepper(SessionBase? session) { var sessionImpl = (SessionImpl)session; var stepper = sessionImpl.CorStepper; sessionImpl.CorStepper = null; - if (!(stepper is null)) + if (stepper is not null) dnDebugger.CancelStep(stepper); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Utilities/DotNetHelpers.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Utilities/DotNetHelpers.cs index 05d883f9a0..0b150a07b4 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Utilities/DotNetHelpers.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/Utilities/DotNetHelpers.cs @@ -101,7 +101,7 @@ static IEnumerable GetDotNetBaseDirCandidates() { static bool TryGetInstallLocationFromRegistry(string regPath, [NotNullWhen(true)] out string? installLocation) { using (var key = Registry.LocalMachine.OpenSubKey(regPath)) { installLocation = key?.GetValue("InstallLocation") as string; - return !(installLocation is null); + return installLocation is not null; } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorDeclSecurity.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorDeclSecurity.cs index e2fa15714f..f9f404219a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorDeclSecurity.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorDeclSecurity.cs @@ -55,7 +55,7 @@ protected override void InitializeSecurityAttributes() { } public override byte[] GetBlob() { - if (!(blob is null)) + if (blob is not null) return blob; var mdi = readerModule.MetaDataImport; uint token = OriginalToken.Raw; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorModuleDef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorModuleDef.cs index c930a7d9aa..2b6ac63305 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorModuleDef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorModuleDef.cs @@ -187,7 +187,7 @@ IAssembly GetCorAssemblyRef() { return corModuleDefHelper.CorLib; var asmRef = TryGetCorLibAssemblyRef(); - if (!(asmRef is null)) + if (asmRef is not null) return asmRef; return corModuleDefHelper.CorLib; @@ -216,7 +216,7 @@ IAssembly GetCorAssemblyRef() { bestNonMscorlib = asmRef; } - if (!(bestMscorlib is null)) + if (bestMscorlib is not null) return bestMscorlib; return bestNonMscorlib; } @@ -319,7 +319,7 @@ CustomAttribute ReadCustomAttribute(uint caToken, GenericParamContext gpContext) var caBlob = MDAPI.GetCustomAttributeBlob(mdi, caToken, out uint typeToken) ?? Array.Empty(); var cat = ResolveToken(typeToken, gpContext) as ICustomAttributeType; var ca = CustomAttributeReader.Read(this, caBlob, cat, gpContext); - Debug2.Assert(!(ca is null)); + Debug2.Assert(ca is not null); return ca; } @@ -399,7 +399,7 @@ string CalculateRuntimeVersion() { if (mdi2 is null) return MDHeaderRuntimeVersion.MS_CLR_10; // Could be .NET 1.0 or 1.1 but choose 1.0 var s = MDAPI.GetModuleVersionString(mdi2); - if (!(s is null)) + if (s is not null) return s; return MDHeaderRuntimeVersion.MS_CLR_20; } @@ -638,7 +638,7 @@ CilBody ReadCilBody(IList parameters, uint rva, uint mdToken, Generic } if (ridToInterfaceImpl.TryGetValue(rid, out cii)) { - if (!(cii is null)) + if (cii is not null) return cii; if (DisableMDAPICalls) return null; @@ -673,7 +673,7 @@ CilBody ReadCilBody(IList parameters, uint rva, uint mdToken, Generic } if (ridToMemberRef.TryGetValue(rid, out cmr)) { - if (!(cmr is null)) + if (cmr is not null) return cmr; if (DisableMDAPICalls) return null; @@ -720,7 +720,7 @@ CilBody ReadCilBody(IList parameters, uint rva, uint mdToken, Generic } if (ridToStandAloneSig.TryGetValue(rid, out cts)) { - if (!(cts is null)) + if (cts is not null) return cts; if (DisableMDAPICalls) return null; @@ -793,7 +793,7 @@ CilBody ReadCilBody(IList parameters, uint rva, uint mdToken, Generic } if (ridToTypeSpec.TryGetValue(rid, out cts)) { - if (!(cts is null)) + if (cts is not null) return cts; if (DisableMDAPICalls) return null; @@ -965,7 +965,7 @@ internal uint[] GetTypeDefNestedClassRids(CorTypeDef ctd) { } void InitializeTypeTables() { - if (!(ridToNested is null)) + if (ridToNested is not null) return; var allTypes = MDAPI.GetTypeDefTokens(mdi); @@ -1096,7 +1096,7 @@ public bool UpdateExportedTypes() { if (!IsValidToken(new MDToken(Table.ExportedType, rid).Raw)) break; var et = ResolveExportedType(rid); - Debug2.Assert(!(et is null)); + Debug2.Assert(et is not null); if (et is null) break; ExportedTypes.Add(et); @@ -1257,7 +1257,7 @@ public void ForceInitializeTypeDef(uint rid) { const bool calledFromLoadClass = false; var ctd = InitializeTypeDef(rid, calledFromLoadClass, out bool created); // If it was created, Initialize() has already been called - if (!created && !(ctd is null) && !ctd.CompletelyLoaded) + if (!created && ctd is not null && !ctd.CompletelyLoaded) Initialize(ctd, created, calledFromLoadClass); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorPropertyDef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorPropertyDef.cs index 48653d3a54..70e49a52b5 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorPropertyDef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorPropertyDef.cs @@ -97,7 +97,7 @@ void InitNameAndAttrs_NoLock() { } protected override void InitializePropertyMethods_NoLock() { - if (!(otherMethods is null)) + if (otherMethods is not null) return; ownerType.InitializeProperty(this, out var newGetMethods, out var newSetMethods, out var newOtherMethods); getMethods = newGetMethods; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorTypeDef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorTypeDef.cs index c15e0e6124..888fcb29d2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorTypeDef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorTypeDef.cs @@ -103,7 +103,7 @@ unsafe Dictionary CalculateFieldOffsets() { var fieldOffsets = MDAPI.GetFieldOffsets(mdi, token); fieldRidToFieldOffset.Clear(); - if (!(fieldOffsets is null)) { + if (fieldOffsets is not null) { foreach (var fo in fieldOffsets) { if (fo.Offset != uint.MaxValue) fieldRidToFieldOffset[fo.FieldToken & 0x00FFFFFF] = fo.Offset; @@ -113,7 +113,7 @@ unsafe Dictionary CalculateFieldOffsets() { } internal uint? GetFieldOffset(CorFieldDef cfd) { - Debug2.Assert(!(fieldRidToFieldOffset is null)); + Debug2.Assert(fieldRidToFieldOffset is not null); if (fieldRidToFieldOffset is null) return null; if (fieldRidToFieldOffset.TryGetValue(cfd.OriginalToken.Rid, out uint fieldOffset)) @@ -276,7 +276,7 @@ protected override void InitializeDeclSecurities() => } } - protected override ModuleDef? GetModule2_NoLock() => !(DeclaringType2_NoLock is null) ? null : readerModule; + protected override ModuleDef? GetModule2_NoLock() => DeclaringType2_NoLock is not null ? null : readerModule; internal void PrepareAutoInsert() { DeclaringType = null; @@ -299,7 +299,7 @@ internal IList GetMethodOverrides(CorMethodDef cmd) { var ovr = overrides[i]; var newMethodBody = readerModule.ResolveToken(ovr.MethodBodyToken, gpContext) as IMethodDefOrRef; var newMethodDeclaration = readerModule.ResolveToken(ovr.MethodDeclarationToken, gpContext) as IMethodDefOrRef; - Debug2.Assert(!(newMethodBody is null) && !(newMethodDeclaration is null)); + Debug2.Assert(newMethodBody is not null && newMethodDeclaration is not null); if (newMethodBody is null || newMethodDeclaration is null) continue; newList.Add(new MethodOverride(newMethodBody, newMethodDeclaration)); @@ -335,7 +335,7 @@ Dictionary> InitializeMethodOverrides() { continue; var cmd = method as CorMethodDef; - uint rid = !(cmd is null) ? cmd.OriginalToken.Rid : method.Rid; + uint rid = cmd is not null ? cmd.OriginalToken.Rid : method.Rid; if (!newMethodRidToOverrides.TryGetValue(rid, out var overrides)) newMethodRidToOverrides[rid] = overrides = new List(); overrides.Add(new MethodOverrideTokens(methodBody.MDToken.Raw, methodDecl.MDToken.Raw)); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorTypeSpec.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorTypeSpec.cs index b903c31c5b..a687f7cb64 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorTypeSpec.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/DotNet/CorTypeSpec.cs @@ -44,7 +44,7 @@ protected override void InitializeCustomAttributes() => var sigData = MDAPI.GetTypeSpecSignatureBlob(mdi, token); var sig = readerModule.ReadTypeSignature(sigData, gpContext, out extraData); - if (!(sig is null)) + if (sig is not null) sig.Rid = origRid; return sig; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/COMObject.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/COMObject.cs index 849228dae5..601e09a558 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/COMObject.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/COMObject.cs @@ -26,11 +26,11 @@ abstract class COMObject : IEquatable?> where T : class { protected readonly T obj; protected COMObject(T obj) { - Debug2.Assert(!(obj is null)); + Debug2.Assert(obj is not null); this.obj = obj ?? throw new ArgumentNullException(nameof(obj)); } - public bool Equals(COMObject? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(COMObject? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as COMObject); public override int GetHashCode() => RawObject.GetHashCode(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorAppDomain.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorAppDomain.cs index cfa6255fce..5ac5e5b41b 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorAppDomain.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorAppDomain.cs @@ -93,7 +93,7 @@ public CorAppDomain(ICorDebugAppDomain appDomain) return res is null ? null : new CorType(res); } - public bool Equals(CorAppDomain? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorAppDomain? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorAppDomain); public override int GetHashCode() => RawObject.GetHashCode(); public override string ToString() => $"[AppDomain] {Id} {Name}"; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorAssembly.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorAssembly.cs index 1e72782090..989eea3ecf 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorAssembly.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorAssembly.cs @@ -54,7 +54,7 @@ public IEnumerable Modules { public string FullName { get { var module = ManifestModule; - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) return Name; return CalculateFullName(module); @@ -104,7 +104,7 @@ public CorAssembly(ICorDebugAssembly assembly) return sb.ToString(); } - public bool Equals(CorAssembly? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorAssembly? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorAssembly); public override int GetHashCode() => RawObject.GetHashCode(); public override string ToString() => $"[Assembly] {Name}"; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorChain.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorChain.cs index 0a091ad0a1..742e6ab13d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorChain.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorChain.cs @@ -106,7 +106,7 @@ public CorChain(ICorDebugChain chain) rangeStart = rangeEnd = 0; } - public bool Equals(CorChain? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorChain? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorChain); public override int GetHashCode() => RawObject.GetHashCode(); public override string ToString() => $"[Chain] Managed={(IsManaged ? 1 : 0)} {StackStart:X8}-{StackEnd:X8} {Reason}"; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorClass.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorClass.cs index 365460c35f..2c8d77fbb7 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorClass.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorClass.cs @@ -49,7 +49,7 @@ public CorClass(ICorDebugClass cls) return hr < 0 || value is null ? null : new CorType(value); } - public bool Equals(CorClass? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorClass? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorClass); public override int GetHashCode() => RawObject.GetHashCode(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorCode.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorCode.cs index f5aff5ab61..00eb1e601a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorCode.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorCode.cs @@ -205,7 +205,7 @@ public unsafe uint[] GetReturnValueLiveOffset(uint ilOffset) { return res; } - public bool Equals(CorCode? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorCode? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorCode); public override int GetHashCode() => RawObject.GetHashCode(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorEval.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorEval.cs index 667b6c4e7d..e7051f1dca 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorEval.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorEval.cs @@ -96,19 +96,19 @@ public int NewParameterizedObjectNoConstructor(CorClass cls, CorType[] typeArgs) } public int NewArray(CorElementType et, CorClass cls, uint[] dims, int[]? lowBounds = null) { - Debug2.Assert(!(dims is null) && (lowBounds is null || lowBounds.Length == dims.Length)); + Debug2.Assert(dims is not null && (lowBounds is null || lowBounds.Length == dims.Length)); return obj.NewArray(et, cls?.RawObject, dims.Length, dims, lowBounds); } public int NewParameterizedArray(CorType type, uint[] dims, int[]? lowBounds = null) { if (eval2 is null) return -1; - Debug2.Assert(!(dims is null) && (lowBounds is null || lowBounds.Length == dims.Length)); + Debug2.Assert(dims is not null && (lowBounds is null || lowBounds.Length == dims.Length)); return eval2.NewParameterizedArray(type.RawObject, dims.Length, dims, lowBounds); } public int NewString(string s) { - if (!(eval2 is null)) + if (eval2 is not null) return eval2.NewStringWithLength(s, s.Length); return obj.NewString(s); } @@ -126,7 +126,7 @@ public int CallParameterizedFunction(CorFunction func, CorType[] typeArgs, CorVa return eval2.CallParameterizedFunction(func.RawObject, typeArgs is null ? 0 : typeArgs.Length, typeArgs.ToCorDebugArray(), args.Length, args.ToCorDebugArray()); } - public bool Equals(CorEval? other) => !(other is null) && + public bool Equals(CorEval? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorEval); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFrame.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFrame.cs index 7ac3088a23..cc94125e77 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFrame.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFrame.cs @@ -221,7 +221,7 @@ public bool GetTypeAndMethodGenericParameters(out CorType[] typeGenArgs, out Cor methGenArgs = Array.Empty(); return false; } - Debug2.Assert(!(func is null)); + Debug2.Assert(func is not null); var mdi = module.GetMetaDataInterface(); var gas = new List(TypeParameters); @@ -250,7 +250,7 @@ public bool GetTypeAndMethodGenericParameters(out CorType[] typeGenArgs, out Cor return hr < 0 || value is null ? null : new CorValue(value); } - public bool Equals(CorFrame? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorFrame? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorFrame); public override int GetHashCode() => RawObject.GetHashCode(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFunction.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFunction.cs index 89e9f43ae7..aec73ba4b2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFunction.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFunction.cs @@ -27,7 +27,7 @@ namespace dndbg.Engine { sealed class CorFunction : COMObject, IEquatable { public CorModule? Module { get { - if (!(module is null)) + if (module is not null) return module; int hr = obj.GetModule(out var mod); return module = hr < 0 || mod is null ? null : new CorModule(mod); @@ -38,13 +38,13 @@ public CorModule? Module { public CorClass? Class { get { int hr = obj.GetClass(out var cls); - if (hr >= 0 && !(cls is null)) + if (hr >= 0 && cls is not null) return new CorClass(cls); // Here if it's an extern method, eg. it's not IL code, but native code var mod = Module; - Debug2.Assert(!(mod is null)); + Debug2.Assert(mod is not null); var mdi = mod?.GetMetaDataInterface(); uint tdOwner = 0x02000000 + MDAPI.GetMethodOwnerRid(mdi, Token); return mod?.GetClassFromToken(tdOwner); @@ -123,7 +123,7 @@ public MethodAttributes GetAttributes() { public string? GetName() => MDAPI.GetMethodName(Module?.GetMetaDataInterface(), Token); - public bool Equals(CorFunction? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorFunction? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorFunction); public override int GetHashCode() => RawObject.GetHashCode(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFunctionBreakpoint.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFunctionBreakpoint.cs index 76a126bf6b..6ee8936902 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFunctionBreakpoint.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorFunctionBreakpoint.cs @@ -49,7 +49,7 @@ public CorFunctionBreakpoint(ICorDebugFunctionBreakpoint functionBreakpoint) offset = 0; } - public bool Equals(CorFunctionBreakpoint? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorFunctionBreakpoint? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorFunctionBreakpoint); public override int GetHashCode() => RawObject.GetHashCode(); public override string ToString() => $"[FunctionBreakpoint] Enabled={(IsActive ? 1 : 0)}, Offset={Offset:X4} Method={Function}"; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorMDA.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorMDA.cs index d17c1fe62c..62107e2db2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorMDA.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorMDA.cs @@ -78,7 +78,7 @@ public CorMDA(ICorDebugMDA code) : base(code) { } - public bool Equals(CorMDA? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorMDA? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorMDA); public override int GetHashCode() => RawObject.GetHashCode(); public override string ToString() => $"MDA: TID={OSThreadId} {Name}"; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorModule.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorModule.cs index 1d8567e0a2..32e2e78255 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorModule.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorModule.cs @@ -47,7 +47,7 @@ public CorAssembly? Assembly { public bool HasAssemblyRow { get { var mdi = GetMetaDataInterface(); - return !(mdi is null) && mdi.IsValidToken(new MDToken(Table.Assembly, 1).Raw); + return mdi is not null && mdi.IsValidToken(new MDToken(Table.Assembly, 1).Raw); } } @@ -192,7 +192,7 @@ public void SetJMCStatus(bool isJustMyCode) { return o as T; } - public bool Equals(CorModule? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorModule? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorModule); public override int GetHashCode() => RawObject.GetHashCode(); public override string ToString() => $"[Module] DYN={(IsDynamic ? 1 : 0)} MEM={(IsInMemory ? 1 : 0)} A={Address:X8} S={Size:X8} {Name}"; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorModuleDefHelper.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorModuleDefHelper.cs index 961e059d1f..7bcb1df0e5 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorModuleDefHelper.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorModuleDefHelper.cs @@ -40,11 +40,11 @@ public CorModuleDefHelper(DnModule module) { public IAssembly CorLib { get { var corAsm = module.AppDomain.Assemblies.FirstOrDefault(); - Debug2.Assert(!(corAsm is null)); + Debug2.Assert(corAsm is not null); if (corAsm is null) return AssemblyRefUser.CreateMscorlibReferenceCLR20(); var corMod = corAsm.Modules.FirstOrDefault(); - Debug2.Assert(!(corMod is null)); + Debug2.Assert(corMod is not null); if (corMod is null) return AssemblyRefUser.CreateMscorlibReferenceCLR20(); return corMod.GetOrCreateCorModuleDef().Assembly; @@ -76,7 +76,7 @@ public bool TryCreateBodyReader(uint bodyRva, uint mdToken, out DataReader reade var ilCode = func?.ILCode; if (ilCode is null) return false; - Debug2.Assert(!(func is null)); + Debug2.Assert(func is not null); ulong addr = ilCode.Address; if (addr == 0) return false; @@ -154,7 +154,7 @@ public bool TryCreateBodyReader(uint bodyRva, uint mdToken, out DataReader reade addr += offs.Value; var data = module.Process.CorProcess.ReadMemory(addr, size); - Debug2.Assert(!(data is null) && data.Length == size); + Debug2.Assert(data is not null && data.Length == size); return data; } @@ -177,7 +177,7 @@ public bool TryCreateBodyReader(uint bodyRva, uint mdToken, out DataReader reade ImageSectionHeader[] GetOrCreateSectionHeaders() { var h = sectionHeaders; - if (!(h is null)) + if (h is not null) return h; try { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorProcess.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorProcess.cs index 44d3b879da..7cb368f937 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorProcess.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorProcess.cs @@ -197,7 +197,7 @@ public bool Detach() { return hr >= 0; } - public bool Equals(CorProcess? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorProcess? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorProcess); public override int GetHashCode() => RawObject.GetHashCode(); public override string ToString() => $"[Process] {ProcessId} CLR v{CLRVersion} Flags={DesiredNGENCompilerFlags}"; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorStepper.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorStepper.cs index 969b01d8b5..49b33719d2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorStepper.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorStepper.cs @@ -76,7 +76,7 @@ public bool SetJMC(bool jmc) { return hr >= 0; } - public bool Equals(CorStepper? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorStepper? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorStepper); public override int GetHashCode() => RawObject.GetHashCode(); public override string ToString() => $"[Stepper] HC={GetHashCode():X8} Active={IsActive}"; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorThread.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorThread.cs index dd8bf0075d..1b8c5c5eae 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorThread.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorThread.cs @@ -157,7 +157,7 @@ public bool InterceptCurrentException(CorFrame frame) { return hr < 0 || eval is null ? null : new CorEval(eval); } - public bool Equals(CorThread? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorThread? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorThread); public override int GetHashCode() => RawObject.GetHashCode(); public override string ToString() => $"[Thread] TID={ThreadId}, VTID={VolatileThreadId} State={State} UserState={UserState}"; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorType.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorType.cs index fbaf548325..c424bfd89f 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorType.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorType.cs @@ -85,7 +85,7 @@ public CorType(ICorDebugType type) return hr < 0 || value is null ? null : new CorValue(value); } - public bool Equals(CorType? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorType? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorType); public override int GetHashCode() => RawObject.GetHashCode(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorValue.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorValue.cs index 1a6ca1ee6b..56c83f7e90 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorValue.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CorValue.cs @@ -322,7 +322,7 @@ public unsafe int WriteGenericValue(byte[]? data, CorProcess? process = null) { // This sometimes fails with CORDBG_E_CLASS_NOT_LOADED (ImmutableArray, debugging VS2017). // If it fails, use process.WriteMemory(). hr = g.SetValue(new IntPtr(p)); - if (hr < 0 && !(process is null)) { + if (hr < 0 && process is not null) { hr = process.WriteMemory(address, data, 0, data.Length, out var sizeWritten); if (sizeWritten != data.Length && hr >= 0) hr = -1; @@ -343,7 +343,7 @@ public unsafe int WriteGenericValue(byte[]? data, CorProcess? process = null) { return hr < 0 ? null : data; } - public bool Equals(CorValue? other) => !(other is null) && RawObject == other.RawObject; + public bool Equals(CorValue? other) => other is not null && RawObject == other.RawObject; public override bool Equals(object? obj) => Equals(obj as CorValue); public override int GetHashCode() => RawObject.GetHashCode(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CoreCLRHelper.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CoreCLRHelper.cs index d36b61700f..24c48f53ba 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CoreCLRHelper.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/CoreCLRHelper.cs @@ -197,7 +197,7 @@ public unsafe static DnDebugger CreateDnDebugger(DebugProcessOptions options, Co IntPtr pHandleArray = IntPtr.Zero, pStringArray = IntPtr.Zero; uint dwArrayLength = 0; - bool useHost = !(info.HostFilename is null); + bool useHost = info.HostFilename is not null; var pi = new PROCESS_INFORMATION(); bool error = true, calledSetEvent = false; try { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebugCallbackEventArgs.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebugCallbackEventArgs.cs index 9d3cc9cf22..3777995d4d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebugCallbackEventArgs.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebugCallbackEventArgs.cs @@ -455,7 +455,7 @@ public NameChangeDebugCallbackEventArgs(ICorDebugAppDomain? pAppDomain, ICorDebu } static ICorDebugAppDomain? GetAppDomain(ICorDebugAppDomain? pAppDomain, ICorDebugThread? pThread) { - if (pAppDomain is null && !(pThread is null)) + if (pAppDomain is null && pThread is not null) pThread.GetAppDomain(out pAppDomain); Debug.WriteLineIf(pAppDomain is null, "GetAppDomain: Could not get AppDomain"); return pAppDomain; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebuggerCollection.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebuggerCollection.cs index eb84d0c1c7..f7629ddcb5 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebuggerCollection.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebuggerCollection.cs @@ -54,7 +54,7 @@ sealed class DebuggerCollection where TKey : class where TValue : return null; var value = TryGet(key); - if (!(value is null)) + if (value is not null) return value; var createdValue = createValue(key); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebuggerState.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebuggerState.cs index 29d4f5fc95..dd6f440ae8 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebuggerState.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DebuggerState.cs @@ -65,11 +65,11 @@ public CorFrame? ILFrame { internal ICorDebugController? Controller { get { ICorDebugController? controller = null; - if (controller is null && !(EventArgs is null)) + if (controller is null && EventArgs is not null) controller = EventArgs.CorDebugController; - if (controller is null && !(AppDomain is null)) + if (controller is null && AppDomain is not null) controller = AppDomain.CorAppDomain.RawObject; - if (controller is null && !(Process is null)) + if (controller is null && Process is not null) controller = Process.CorProcess.RawObject; return controller; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnAssembly.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnAssembly.cs index a468ddccd3..7cc64433ed 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnAssembly.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnAssembly.cs @@ -115,8 +115,8 @@ internal void InitializeAssemblyAndModules() { var modules = this.modules.GetAll(); for (int i = 0; i < modules.Length; i++) { var module = modules[i]; - if (!(module.CorModuleDef is null)) { - Debug2.Assert(!(corAssemblyDef is null)); + if (module.CorModuleDef is not null) { + Debug2.Assert(corAssemblyDef is not null); continue; } module.CorModuleDef = new CorModuleDef(module.CorModule.GetMetaDataInterface(), new CorModuleDefHelper(module)); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnDebugger.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnDebugger.cs index 33751694e4..1c64262797 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnDebugger.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnDebugger.cs @@ -128,7 +128,7 @@ void CallOnProcessStateChanged() => public event EventHandler? OnCorModuleDefCreated; internal void CorModuleDefCreated(DnModule module) { DebugVerifyThread(); - Debug2.Assert(!(module.CorModuleDef is null)); + Debug2.Assert(module.CorModuleDef is not null); OnCorModuleDefCreated?.Invoke(this, new CorModuleDefCreatedEventArgs(module, module.CorModuleDef)); } @@ -375,7 +375,7 @@ bool HasAnyQueuedCallbacks(DebugCallbackEventArgs e) { // and no methods can be called because the CLR debugger could call us before this method // returns. bool Continue(ICorDebugController? controller, bool callOnProcessStateChanged) { - Debug2.Assert(!(controller is null)); + Debug2.Assert(controller is not null); if (controller is null) return false; @@ -417,7 +417,7 @@ public void Continue() { return; var controller = Current.Controller; - Debug2.Assert(!(controller is null)); + Debug2.Assert(controller is not null); if (controller is null) return; @@ -432,7 +432,7 @@ public void Continue() { public bool CanStep(CorFrame? frame) { DebugVerifyThread(); - return ProcessStateInternal == DebuggerProcessState.Paused && !(frame is null); + return ProcessStateInternal == DebuggerProcessState.Paused && frame is not null; } CorStepper? CreateStepper(CorFrame frame) { @@ -487,7 +487,7 @@ enum StepKind { CorStepper? Step(CorFrame? frame, StepKind step, Action? action = null) { if (!CanStep(frame)) return null; - Debug2.Assert(!(frame is null)); + Debug2.Assert(frame is not null); var stepper = CreateStepper(frame); if (stepper is null) @@ -537,7 +537,7 @@ enum StepKind { return Step(frame, stepInto ? StepKind.StepInto : StepKind.StepOver, action); if (!CanStep(frame)) return null; - Debug2.Assert(!(frame is null)); + Debug2.Assert(frame is not null); var stepper = CreateStepper(frame); if (stepper is null) @@ -564,14 +564,14 @@ void SetDefaultCurrentProcess(DebugCallbackEventArgs e) { } void InitializeCurrentDebuggerState(DebugCallbackEventArgs e, ICorDebugProcess? comProcess, ICorDebugAppDomain? comAppDomain, ICorDebugThread? comThread) { - if (!(comThread is null)) { + if (comThread is not null) { if (comProcess is null) comThread.GetProcess(out comProcess); if (comAppDomain is null) comThread.GetAppDomain(out comAppDomain); } - if (!(comAppDomain is null)) { + if (comAppDomain is not null) { if (comProcess is null) comAppDomain.GetProcess(out comProcess); } @@ -579,7 +579,7 @@ void InitializeCurrentDebuggerState(DebugCallbackEventArgs e, ICorDebugProcess? var process = TryGetValidProcess(comProcess); DnAppDomain? appDomain; DnThread? thread; - if (!(process is null)) { + if (process is not null) { appDomain = process.TryGetAppDomain(comAppDomain); thread = process.TryGetThread(comThread); } @@ -588,12 +588,12 @@ void InitializeCurrentDebuggerState(DebugCallbackEventArgs e, ICorDebugProcess? thread = null; } - if (thread is null && appDomain is null && !(process is null)) + if (thread is null && appDomain is null && process is not null) appDomain = process.AppDomains.FirstOrDefault(); if (thread is null) { - if (!(appDomain is null)) + if (appDomain is not null) thread = appDomain.Threads.FirstOrDefault(); - else if (!(process is null)) + else if (process is not null) thread = process.Threads.FirstOrDefault(); } @@ -671,7 +671,7 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { InitializeCurrentDebuggerState(e, null, scArgs.AppDomain, scArgs.Thread); StepInfo? stepInfo; var stepperKey = scArgs.CorStepper; - if (!(stepperKey is null) && stepInfos.TryGetValue(stepperKey, out stepInfo)) { + if (stepperKey is not null && stepInfos.TryGetValue(stepperKey, out stepInfo)) { stepInfos.Remove(stepperKey); stepInfo.OnCompleted?.Invoke(this, scArgs, false); } @@ -701,7 +701,7 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { var cpArgs = (CreateProcessDebugCallbackEventArgs)e; hasReceivedCreateProcessEvent = true; process = TryAdd(cpArgs.Process); - if (!(process is null)) { + if (process is not null) { process.CorProcess.EnableLogMessages(debugOptions.LogMessages); process.CorProcess.DesiredNGENCompilerFlags = debugOptions.DebugOptionsProvider.GetDesiredNGENCompilerFlags(process); process.CorProcess.SetWriteableMetadataUpdateMode(WriteableMetadataUpdateMode.AlwaysShowUpdates); @@ -715,7 +715,7 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { var epArgs = (ExitProcessDebugCallbackEventArgs)e; process = processes.TryGet(epArgs.Process); InitializeCurrentDebuggerState(e, process); - if (!(process is null)) + if (process is not null) process.SetHasExited(); processes.Remove(epArgs.Process); OnProcessTerminated(process); @@ -726,9 +726,9 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { case DebugCallbackKind.CreateThread: var ctArgs = (CreateThreadDebugCallbackEventArgs)e; process = TryGetValidProcess(ctArgs.Thread); - if (!(process is null)) { + if (process is not null) { var dnThread = process.TryAdd(ctArgs.Thread); - if (!(dnThread is null)) { + if (dnThread is not null) { CallOnThreadAdded(dnThread, true, out shouldPause); if (shouldPause) e.AddPauseReason(DebuggerPauseReason.Other); @@ -745,9 +745,9 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { var etArgs = (ExitThreadDebugCallbackEventArgs)e; InitializeCurrentDebuggerState(e, null, etArgs.AppDomain, etArgs.Thread); process = TryGetValidProcess(etArgs.Thread); - if (!(process is null)) { + if (process is not null) { var dnThread = process.ThreadExited(etArgs.Thread); - if (!(dnThread is null)) { + if (dnThread is not null) { CallOnThreadAdded(dnThread, false, out shouldPause); if (shouldPause) e.AddPauseReason(DebuggerPauseReason.Other); @@ -759,7 +759,7 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { var lmArgs = (LoadModuleDebugCallbackEventArgs)e; InitializeCurrentDebuggerState(e, null, lmArgs.AppDomain, null); assembly = TryGetValidAssembly(lmArgs.AppDomain, lmArgs.Module); - if (!(assembly is null)) { + if (assembly is not null) { var module = assembly.TryAdd(lmArgs.Module)!; toDnModule.Add(module.CorModule, module); @@ -782,9 +782,9 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { var umArgs = (UnloadModuleDebugCallbackEventArgs)e; InitializeCurrentDebuggerState(e, null, umArgs.AppDomain, null); assembly = TryGetValidAssembly(umArgs.AppDomain, umArgs.Module); - if (!(assembly is null)) { + if (assembly is not null) { var module = assembly.TryGetModule(umArgs.Module); - if (!(module is null)) { + if (module is not null) { OnModuleUnloaded(module); CallOnModuleAdded(module, false, out shouldPause); if (shouldPause) @@ -798,10 +798,10 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { InitializeCurrentDebuggerState(e, null, lcArgs.AppDomain, null); cls = lcArgs.CorClass; - if (!(cls is null)) { + if (cls is not null) { var module = TryGetModule(lcArgs.CorAppDomain, cls); - if (!(module is null)) { - if (!(module.CorModuleDef is null)) + if (module is not null) { + if (module.CorModuleDef is not null) module.CorModuleDef.LoadClass(cls.Token); if (module.IsDynamic) { foreach (var bp in ilCodeBreakpointList.GetBreakpoints(module.DnModuleId)) @@ -818,9 +818,9 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { InitializeCurrentDebuggerState(e, null, ucArgs.AppDomain, null); cls = ucArgs.CorClass; - if (!(cls is null)) { + if (cls is not null) { var module = TryGetModule(ucArgs.CorAppDomain, cls); - if (!(module is null) && !(module.CorModuleDef is null)) + if (module is not null && module.CorModuleDef is not null) module.CorModuleDef.UnloadClass(cls.Token); } break; @@ -844,14 +844,14 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { var cadArgs = (CreateAppDomainDebugCallbackEventArgs)e; process = TryGetValidProcess(cadArgs.Process); appDomain = null; - if (!(process is null) && !(cadArgs.AppDomain is null)) { + if (process is not null && cadArgs.AppDomain is not null) { b = cadArgs.AppDomain.Attach() >= 0; Debug.WriteLineIf(!b, $"CreateAppDomain: could not attach to AppDomain: {cadArgs.AppDomain.GetHashCode():X8}"); if (b) appDomain = process.TryAdd(cadArgs.AppDomain); } InitializeCurrentDebuggerState(e, cadArgs.Process, cadArgs.AppDomain, null); - if (!(appDomain is null)) { + if (appDomain is not null) { CallOnAppDomainAdded(appDomain, true, out shouldPause); if (shouldPause) e.AddPauseReason(DebuggerPauseReason.Other); @@ -862,10 +862,10 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { var eadArgs = (ExitAppDomainDebugCallbackEventArgs)e; InitializeCurrentDebuggerState(e, eadArgs.Process, eadArgs.AppDomain, null); process = processes.TryGet(eadArgs.Process); - if (!(process is null)) { + if (process is not null) { UpdateCustomNotificationList(eadArgs.CorAppDomain); OnAppDomainUnloaded(appDomain = process.TryGetAppDomain(eadArgs.AppDomain)); - if (!(appDomain is null)) { + if (appDomain is not null) { CallOnAppDomainAdded(appDomain, false, out shouldPause); if (shouldPause) e.AddPauseReason(DebuggerPauseReason.Other); @@ -878,9 +878,9 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { var laArgs = (LoadAssemblyDebugCallbackEventArgs)e; InitializeCurrentDebuggerState(e, null, laArgs.AppDomain, null); appDomain = TryGetValidAppDomain(laArgs.AppDomain); - if (!(appDomain is null)) { + if (appDomain is not null) { assembly = appDomain.TryAdd(laArgs.Assembly); - if (!(assembly is null)) { + if (assembly is not null) { CallOnAssemblyAdded(assembly, true, out shouldPause); if (shouldPause) e.AddPauseReason(DebuggerPauseReason.Other); @@ -892,9 +892,9 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { var uaArgs = (UnloadAssemblyDebugCallbackEventArgs)e; InitializeCurrentDebuggerState(e, null, uaArgs.AppDomain, null); appDomain = TryGetAppDomain(uaArgs.AppDomain); - if (!(appDomain is null)) { + if (appDomain is not null) { OnAssemblyUnloaded(assembly = appDomain.TryGetAssembly(uaArgs.Assembly)); - if (!(assembly is null)) { + if (assembly is not null) { CallOnAssemblyAdded(assembly, false, out shouldPause); if (shouldPause) e.AddPauseReason(DebuggerPauseReason.Other); @@ -912,10 +912,10 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { var ncArgs = (NameChangeDebugCallbackEventArgs)e; InitializeCurrentDebuggerState(e, null, ncArgs.AppDomain, ncArgs.Thread); appDomain = TryGetValidAppDomain(ncArgs.AppDomain); - if (!(appDomain is null)) + if (appDomain is not null) appDomain.NameChanged(); var thread = TryGetValidThread(ncArgs.Thread); - if (!(thread is null)) + if (thread is not null) thread.NameChanged(); CallOnNameChanged(appDomain, thread); break; @@ -934,7 +934,7 @@ void HandleManagedCallback(DebugCallbackEventArgs e) { var bpseArgs = (BreakpointSetErrorDebugCallbackEventArgs)e; InitializeCurrentDebuggerState(e, null, bpseArgs.AppDomain, bpseArgs.Thread); var moduleId = TryGetModuleId(bpseArgs.CorFunctionBreakpoint?.Function?.Module); - if (!(moduleId is null)) { + if (moduleId is not null) { foreach (var bp in ilCodeBreakpointList.GetBreakpoints(moduleId.Value)) { if (bp.IsBreakpoint(bpseArgs.Breakpoint)) bp.SetError(DnCodeBreakpointError.CouldNotCreateBreakpoint); @@ -1004,7 +1004,7 @@ void CheckBreakpoints(DebugCallbackEventArgs e) { return; var type = DnDebugEventBreakpoint.GetDebugEventBreakpointKind(e); - if (!(type is null)) { + if (type is not null) { foreach (var bp in DebugEventBreakpoints) { if (bp.IsEnabled && bp.EventKind == type.Value && bp.Condition(new DebugEventBreakpointConditionContext(this, bp, e))) e.AddPauseState(new DebugEventBreakpointPauseState(bp)); @@ -1114,7 +1114,7 @@ static DnDebugger CreateDnDebuggerCoreCLR(DebugProcessOptions options) { new BreakProcessHelper(dbg, options.BreakProcessKind); cd.DebugActiveProcess((int)pid, 0, out var comProcess); var dnProcess = dbg.TryAdd(comProcess); - if (!(dnProcess is null)) + if (dnProcess is not null) dnProcess.Initialize(options.Filename, options.CurrentDirectory, options.CommandLine); if (options.RedirectConsoleOutput) dbg.ReadPipesAsync(); @@ -1232,7 +1232,7 @@ void CreateProcess(DebugProcessOptions options) { } var process = TryAdd(comProcess); - if (!(process is null)) + if (process is not null) process.Initialize(options.Filename, options.CurrentDirectory, options.CommandLine); } @@ -1246,7 +1246,7 @@ public static DnDebugger Attach(AttachProcessOptions options) { var dbg = new DnDebugger(corDebug, options.DebugOptions, options.DebugMessageDispatcher!, clrPath, debuggeeVersion, otherVersion, isAttach: true); corDebug.DebugActiveProcess(options.ProcessId, 0, out var comProcess); var dnProcess = dbg.TryAdd(comProcess); - if (!(dnProcess is null)) + if (dnProcess is not null) dnProcess.Initialize(filename, string.Empty, string.Empty); return dbg; } @@ -1487,7 +1487,7 @@ public DnNativeCodeBreakpoint CreateNativeBreakpoint(CorCode code, uint offset, } public DnModuleId? TryGetModuleId(CorModule? module) { - if (!(module is null) && toDnModule.TryGetValue(module, out var dnModule)) + if (module is not null && toDnModule.TryGetValue(module, out var dnModule)) return dnModule.DnModuleId; Debug.Fail("Couldn't get module id"); return null; @@ -1662,8 +1662,8 @@ void TerminateAllProcessesInternal() { public void AddCustomNotificationClassToken(DnModule module, uint token) { var cls = module.CorModule.GetClassFromToken(token); - Debug2.Assert(!(cls is null)); - if (!(cls is null)) + Debug2.Assert(cls is not null); + if (cls is not null) customNotificationList.Add((module, cls)); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnEval.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnEval.cs index ce0ab99e8f..a42eefb315 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnEval.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnEval.cs @@ -170,7 +170,7 @@ public void SetThread(DnThread thread) { } void InitializeStartTime() { - if (!(startTime is null)) + if (startTime is not null) return; startTime = DateTime.UtcNow; @@ -233,7 +233,7 @@ public void RestoreThreads() { } EvalResult SyncWait() { - Debug2.Assert(!(startTime is null)); + Debug2.Assert(startTime is not null); var now = DateTime.UtcNow; if (now >= endTime) @@ -254,7 +254,7 @@ EvalResult SyncWait() { AbortEval(timedOut); throw new TimeoutException(); } - Debug2.Assert(!(res is null)); + Debug2.Assert(res is not null); dispResult = (EvalResultKind)res; if (dispResult == EvalResultKind.CustomNotification) { if (!AbortEval(false)) @@ -319,7 +319,7 @@ void Debugger_DebugCallbackEvent(DnDebugger dbg, DebugCallbackEventArgs e) { break; var cne = (CustomNotificationDebugCallbackEventArgs)e; var value = cne.CorThread?.GetCurrentCustomDebuggerNotification(); - if (!(value is null)) { + if (value is not null) { debugMessageDispatcher.CancelDispatchQueue(EvalResultKind.CustomNotification); debugger.DisposeHandle(value); return; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnModule.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnModule.cs index 5970042753..689297c69b 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnModule.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnModule.cs @@ -34,11 +34,11 @@ sealed class DnModule { /// public CorModuleDef GetOrCreateCorModuleDef() { Debugger.DebugVerifyThread(); - if (!(CorModuleDef is null)) + if (CorModuleDef is not null) return CorModuleDef; Assembly.InitializeAssemblyAndModules(); - Debug2.Assert(!(CorModuleDef is null)); + Debug2.Assert(CorModuleDef is not null); return CorModuleDef; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnProcess.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnProcess.cs index 0c7aeaac62..b3ce09d2eb 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnProcess.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.CorDebug/dndbg/Engine/DnProcess.cs @@ -139,7 +139,7 @@ public DnThread[] Threads { internal DnThread? ThreadExited(ICorDebugThread? comThread) { var thread = threads.TryGet(comThread); // Sometimes we don't get a CreateThread message - if (!(thread is null)) { + if (thread is not null) { thread.SetHasExited(); threads.Remove(comThread); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/ILValue.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/ILValue.cs index cd2e4e0f09..13861bec97 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/ILValue.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/ILValue.cs @@ -636,7 +636,7 @@ public sealed class FunctionPointerILValue : NativeIntILValue { /// /// true if it was created by a ldvirtftn instruction, false it was created by a ldftn instruction /// - public bool IsVirtual => !(VirtualThisObject is null); + public bool IsVirtual => VirtualThisObject is not null; /// /// Gets the this value if and only if this was created by a ldvirtftn instruction, otherwise it's null diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Impl/DebuggerILInterpreter.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Impl/DebuggerILInterpreter.cs index b323cd61c4..c4641c4734 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Impl/DebuggerILInterpreter.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Impl/DebuggerILInterpreter.cs @@ -171,7 +171,7 @@ ILValue Convert(ILValue value, DmdType targetType, bool boxIfNeeded = true) { if (GetValue(value, out l)) return debuggerRuntime.PointerSize == 4 ? ConstantNativeIntILValue.Create32(targetType, (int)l) : ConstantNativeIntILValue.Create64(targetType, l); } - if (!(type is null) && (type == type.AppDomain.System_IntPtr || type == type.AppDomain.System_UIntPtr) && (targetType.IsPointer || targetType.IsFunctionPointer)) { + if (type is not null && (type == type.AppDomain.System_IntPtr || type == type.AppDomain.System_UIntPtr) && (targetType.IsPointer || targetType.IsFunctionPointer)) { if (GetValue(value, out l)) return debuggerRuntime.PointerSize == 4 ? ConstantNativeIntILValue.Create32(targetType, (int)l) : ConstantNativeIntILValue.Create64(targetType, l); } @@ -225,10 +225,10 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { var body = state.Body; if (body is null) ThrowInvalidMethodBodyInterpreterException(); - Debug2.Assert(!(body is null)); + Debug2.Assert(body is not null); debuggerRuntime.Initialize(currentMethod, body); var bodyBytes = state.ILBytes; - Debug2.Assert(!(bodyBytes is null)); + Debug2.Assert(bodyBytes is not null); var exceptionHandlingClauses = body.ExceptionHandlingClauses; int methodBodyPos = 0; DmdType? constrainedType = null; @@ -1002,7 +1002,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { args = PopMethodArguments(methodSig); if (methodSig.HasThis) { v1 = Pop1(); - if (!(constrainedType is null)) { + if (constrainedType is not null) { if (i != (int)OpCode.Callvirt) ThrowInvalidMethodBodyInterpreterException(); v1 = FixConstrainedType(constrainedType, method, v1); @@ -1129,7 +1129,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.NativeInt: - if (!((v3 = v2.Add(AddOpCodeKind.Add, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v2.Add(AddOpCodeKind.Add, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is not null) break; else if (v2 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1142,7 +1142,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.ByRef: - if (!((v3 = v2.Add(AddOpCodeKind.Add, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v2.Add(AddOpCodeKind.Add, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is not null) break; throw new InvalidMethodBodyInterpreterException(); @@ -1189,7 +1189,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.NativeInt: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Add(AddOpCodeKind.Add, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Add(AddOpCodeKind.Add, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1202,9 +1202,9 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Add(AddOpCodeKind.Add, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Add(AddOpCodeKind.Add, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; - else if (v1 is ConstantNativeIntILValue && !((v3 = v2.Add(AddOpCodeKind.Add, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is null)) + else if (v1 is ConstantNativeIntILValue && (v3 = v2.Add(AddOpCodeKind.Add, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue && v2 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1217,7 +1217,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.ByRef: - if (v1 is ConstantNativeIntILValue && !((v3 = v2.Add(AddOpCodeKind.Add, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is null)) + if (v1 is ConstantNativeIntILValue && (v3 = v2.Add(AddOpCodeKind.Add, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is not null) break; throw new InvalidMethodBodyInterpreterException(); @@ -1232,12 +1232,12 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.ByRef: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Add(AddOpCodeKind.Add, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Add(AddOpCodeKind.Add, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Add(AddOpCodeKind.Add, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Add(AddOpCodeKind.Add, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; @@ -1267,7 +1267,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.NativeInt: - if (!((v3 = v2.Add(AddOpCodeKind.Add_Ovf, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v2.Add(AddOpCodeKind.Add_Ovf, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is not null) break; else if (v2 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1280,7 +1280,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.ByRef: - if (!((v3 = v2.Add(AddOpCodeKind.Add_Ovf, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v2.Add(AddOpCodeKind.Add_Ovf, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is not null) break; throw new InvalidMethodBodyInterpreterException(); @@ -1327,7 +1327,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.NativeInt: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Add(AddOpCodeKind.Add_Ovf, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Add(AddOpCodeKind.Add_Ovf, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1340,9 +1340,9 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Add(AddOpCodeKind.Add_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Add(AddOpCodeKind.Add_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; - else if (v1 is ConstantNativeIntILValue && !((v3 = v2.Add(AddOpCodeKind.Add_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is null)) + else if (v1 is ConstantNativeIntILValue && (v3 = v2.Add(AddOpCodeKind.Add_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue && v2 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1355,7 +1355,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.ByRef: - if (v1 is ConstantNativeIntILValue && !((v3 = v2.Add(AddOpCodeKind.Add_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is null)) + if (v1 is ConstantNativeIntILValue && (v3 = v2.Add(AddOpCodeKind.Add_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is not null) break; throw new InvalidMethodBodyInterpreterException(); @@ -1370,12 +1370,12 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.ByRef: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Add(AddOpCodeKind.Add_Ovf, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Add(AddOpCodeKind.Add_Ovf, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Add(AddOpCodeKind.Add_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Add(AddOpCodeKind.Add_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; @@ -1405,7 +1405,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.NativeInt: - if (!((v3 = v2.Add(AddOpCodeKind.Add_Ovf_Un, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v2.Add(AddOpCodeKind.Add_Ovf_Un, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is not null) break; else if (v2 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1418,7 +1418,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.ByRef: - if (!((v3 = v2.Add(AddOpCodeKind.Add_Ovf_Un, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v2.Add(AddOpCodeKind.Add_Ovf_Un, ((ConstantInt32ILValue)v1).Value, debuggerRuntime.PointerSize)) is not null) break; throw new InvalidMethodBodyInterpreterException(); @@ -1452,7 +1452,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.NativeInt: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Add(AddOpCodeKind.Add_Ovf_Un, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Add(AddOpCodeKind.Add_Ovf_Un, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1465,9 +1465,9 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Add(AddOpCodeKind.Add_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Add(AddOpCodeKind.Add_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; - else if (v1 is ConstantNativeIntILValue && !((v3 = v2.Add(AddOpCodeKind.Add_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is null)) + else if (v1 is ConstantNativeIntILValue && (v3 = v2.Add(AddOpCodeKind.Add_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue && v2 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1480,7 +1480,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.ByRef: - if (v1 is ConstantNativeIntILValue && !((v3 = v2.Add(AddOpCodeKind.Add_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is null)) + if (v1 is ConstantNativeIntILValue && (v3 = v2.Add(AddOpCodeKind.Add_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v1).Value32 : ((ConstantNativeIntILValue)v1).Value64, debuggerRuntime.PointerSize)) is not null) break; throw new InvalidMethodBodyInterpreterException(); @@ -1495,12 +1495,12 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.ByRef: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Add(AddOpCodeKind.Add_Ovf_Un, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Add(AddOpCodeKind.Add_Ovf_Un, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Add(AddOpCodeKind.Add_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Add(AddOpCodeKind.Add_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; @@ -1522,7 +1522,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case OpCode.Sub: Pop2(out v1, out v2); - if (!((v3 = v1.Sub(SubOpCodeKind.Sub, v2, debuggerRuntime.PointerSize)) is null)) { + if ((v3 = v1.Sub(SubOpCodeKind.Sub, v2, debuggerRuntime.PointerSize)) is not null) { ilValueStack.Add(v3); break; } @@ -1588,7 +1588,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.NativeInt: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Sub(SubOpCodeKind.Sub, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Sub(SubOpCodeKind.Sub, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1601,7 +1601,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Sub(SubOpCodeKind.Sub, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Sub(SubOpCodeKind.Sub, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue && v2 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1625,12 +1625,12 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.ByRef: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Sub(SubOpCodeKind.Sub, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Sub(SubOpCodeKind.Sub, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Sub(SubOpCodeKind.Sub, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Sub(SubOpCodeKind.Sub, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; @@ -1652,7 +1652,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case OpCode.Sub_Ovf: Pop2(out v1, out v2); - if (!((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf, v2, debuggerRuntime.PointerSize)) is null)) { + if ((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf, v2, debuggerRuntime.PointerSize)) is not null) { ilValueStack.Add(v3); break; } @@ -1718,7 +1718,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.NativeInt: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1731,7 +1731,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Sub(SubOpCodeKind.Sub_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue && v2 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1755,12 +1755,12 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.ByRef: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Sub(SubOpCodeKind.Sub_Ovf, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; @@ -1782,7 +1782,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case OpCode.Sub_Ovf_Un: Pop2(out v1, out v2); - if (!((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf_Un, v2, debuggerRuntime.PointerSize)) is null)) { + if ((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf_Un, v2, debuggerRuntime.PointerSize)) is not null) { ilValueStack.Add(v3); break; } @@ -1835,7 +1835,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.NativeInt: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf_Un, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf_Un, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1848,7 +1848,7 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { break; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Sub(SubOpCodeKind.Sub_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; else if (v1 is ConstantNativeIntILValue && v2 is ConstantNativeIntILValue) { if (debuggerRuntime.PointerSize == 4) @@ -1872,12 +1872,12 @@ ILValue ExecuteLoop(ILVMExecuteStateImpl state) { case ILValueKind.ByRef: switch (v2.Kind) { case ILValueKind.Int32: - if (!((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf_Un, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is null)) + if ((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf_Un, ((ConstantInt32ILValue)v2).Value, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; case ILValueKind.NativeInt: - if (v2 is ConstantNativeIntILValue && !((v3 = v1.Sub(SubOpCodeKind.Sub_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is null)) + if (v2 is ConstantNativeIntILValue && (v3 = v1.Sub(SubOpCodeKind.Sub_Ovf_Un, debuggerRuntime.PointerSize == 4 ? ((ConstantNativeIntILValue)v2).Value32 : ((ConstantNativeIntILValue)v2).Value64, debuggerRuntime.PointerSize)) is not null) break; goto case ILValueKind.ByRef; @@ -4453,7 +4453,7 @@ bool CompareEquals(ILValue v1, ILValue v2) { } var res = debuggerRuntime.Equals(v1, v2); - if (!(res is null)) + if (res is not null) return res.Value; throw new InvalidMethodBodyInterpreterException(); @@ -4464,7 +4464,7 @@ int CompareSigned(ILValue v1, ILValue v2) { return 0; var res = debuggerRuntime.CompareSigned(v1, v2); - if (!(res is null)) + if (res is not null) return res.Value; var v1z = IsIntegerZeroOrNull(v1); @@ -4562,7 +4562,7 @@ int CompareUnsigned(ILValue v1, ILValue v2) { return 0; var res = debuggerRuntime.CompareUnsigned(v1, v2); - if (!(res is null)) + if (res is not null) return res.Value; var v1z = IsIntegerZeroOrNull(v1); @@ -4751,7 +4751,7 @@ long GetInt64ForSwitch(ILValue v) { case ILValueKind.NativeInt: var cv = v as ConstantNativeIntILValue; - if (!(cv is null)) { + if (cv is not null) { if (debuggerRuntime.PointerSize == 4) return cv.Value32; return cv.Value64; @@ -4773,11 +4773,11 @@ byte GetByte(ILValue v) { } ILValue? FixConstrainedType(DmdType constrainedType, DmdMethodBase method, ILValue v1) { - Debug2.Assert(!(constrainedType is null)); - Debug2.Assert(!(method is null)); + Debug2.Assert(constrainedType is not null); + Debug2.Assert(method is not null); if (v1 is null) ThrowInvalidMethodBodyInterpreterException(); - Debug2.Assert(!(v1 is null)); + Debug2.Assert(v1 is not null); if (constrainedType.IsValueType) { if (ImplementsMethod(constrainedType, method.Name, method.GetMethodSignature())) return v1; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Tests/FakeDebuggerRuntime.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Tests/FakeDebuggerRuntime.cs index ac5f189868..e8befb2b43 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Tests/FakeDebuggerRuntime.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Tests/FakeDebuggerRuntime.cs @@ -344,7 +344,7 @@ public override bool StoreLocal(int index, DmdType type, ILValue value) { } static void InitializeValue(ref ILValue value, DmdType valueType) { - if (!(value is null)) + if (value is not null) return; if (!valueType.IsValueType) { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Tests/InterpreterTest.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Tests/InterpreterTest.cs index afc582133a..d40729c36b 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Tests/InterpreterTest.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Interpreter/Tests/InterpreterTest.cs @@ -3812,7 +3812,7 @@ void TestMethod(string methodName, params object[] args) { ex2 = ex; res2 = null; } - if (!(ex1 is null) || !(ex2 is null)) + if (ex1 is not null || ex2 is not null) Verify(ex1?.GetType().FullName == ex2?.GetType().FullName); else Verify(m1.ReturnType, res1, res2); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/CustomAttributesHelper.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/CustomAttributesHelper.cs index 24f71ce0a3..443fe41294 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/CustomAttributesHelper.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/CustomAttributesHelper.cs @@ -42,7 +42,7 @@ public static bool IsDefined(ReadOnlyCollection customAt } public static bool IsDefined(DmdType type, string attributeTypeFullName, bool inherit) { - for (DmdType? currentType = type; !(currentType is null); currentType = currentType.BaseType) { + for (DmdType? currentType = type; currentType is not null; currentType = currentType.BaseType) { var customAttributes = currentType.GetCustomAttributesData(); for (int i = 0; i < customAttributes.Count; i++) { var ca = customAttributes[i]; @@ -58,7 +58,7 @@ public static bool IsDefined(DmdType type, string attributeTypeFullName, bool in } public static bool IsDefined(DmdType type, DmdType? attributeType, bool inherit) { - for (DmdType? currentType = type; !(currentType is null); currentType = currentType.BaseType) { + for (DmdType? currentType = type; currentType is not null; currentType = currentType.BaseType) { var customAttributes = currentType.GetCustomAttributesData(); for (int i = 0; i < customAttributes.Count; i++) { var ca = customAttributes[i]; @@ -74,7 +74,7 @@ public static bool IsDefined(DmdType type, DmdType? attributeType, bool inherit) } public static bool IsDefined(DmdMethodInfo method, string attributeTypeFullName, bool inherit) { - for (DmdMethodInfo? currentMethod = method; !(currentMethod is null); currentMethod = currentMethod.GetParentDefinition()) { + for (DmdMethodInfo? currentMethod = method; currentMethod is not null; currentMethod = currentMethod.GetParentDefinition()) { var customAttributes = currentMethod.GetCustomAttributesData(); for (int i = 0; i < customAttributes.Count; i++) { var ca = customAttributes[i]; @@ -90,7 +90,7 @@ public static bool IsDefined(DmdMethodInfo method, string attributeTypeFullName, } public static bool IsDefined(DmdMethodInfo method, DmdType? attributeType, bool inherit) { - for (DmdMethodInfo? currentMethod = method; !(currentMethod is null); currentMethod = currentMethod.GetParentDefinition()) { + for (DmdMethodInfo? currentMethod = method; currentMethod is not null; currentMethod = currentMethod.GetParentDefinition()) { var customAttributes = currentMethod.GetCustomAttributesData(); for (int i = 0; i < customAttributes.Count; i++) { var ca = customAttributes[i]; @@ -124,7 +124,7 @@ public static bool IsDefined(DmdMethodInfo method, DmdType? attributeType, bool } public static DmdCustomAttributeData? Find(DmdType type, string attributeTypeFullName, bool inherit) { - for (DmdType? currentType = type; !(currentType is null); currentType = currentType.BaseType) { + for (DmdType? currentType = type; currentType is not null; currentType = currentType.BaseType) { var customAttributes = currentType.GetCustomAttributesData(); for (int i = 0; i < customAttributes.Count; i++) { var ca = customAttributes[i]; @@ -140,7 +140,7 @@ public static bool IsDefined(DmdMethodInfo method, DmdType? attributeType, bool } public static DmdCustomAttributeData? Find(DmdType type, DmdType? attributeType, bool inherit) { - for (DmdType? currentType = type; !(currentType is null); currentType = currentType.BaseType) { + for (DmdType? currentType = type; currentType is not null; currentType = currentType.BaseType) { var customAttributes = currentType.GetCustomAttributesData(); for (int i = 0; i < customAttributes.Count; i++) { var ca = customAttributes[i]; @@ -156,7 +156,7 @@ public static bool IsDefined(DmdMethodInfo method, DmdType? attributeType, bool } public static DmdCustomAttributeData? Find(DmdMethodInfo method, string attributeTypeFullName, bool inherit) { - for (DmdMethodInfo? currentMethod = method; !(currentMethod is null); currentMethod = currentMethod.GetParentDefinition()) { + for (DmdMethodInfo? currentMethod = method; currentMethod is not null; currentMethod = currentMethod.GetParentDefinition()) { var customAttributes = currentMethod.GetCustomAttributesData(); for (int i = 0; i < customAttributes.Count; i++) { var ca = customAttributes[i]; @@ -172,7 +172,7 @@ public static bool IsDefined(DmdMethodInfo method, DmdType? attributeType, bool } public static DmdCustomAttributeData? Find(DmdMethodInfo method, DmdType? attributeType, bool inherit) { - for (DmdMethodInfo? currentMethod = method; !(currentMethod is null); currentMethod = currentMethod.GetParentDefinition()) { + for (DmdMethodInfo? currentMethod = method; currentMethod is not null; currentMethod = currentMethod.GetParentDefinition()) { var customAttributes = currentMethod.GetCustomAttributesData(); for (int i = 0; i < customAttributes.Count; i++) { var ca = customAttributes[i]; @@ -205,14 +205,14 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index, ReadOnly } readonly struct SerializableAttributeInfo { - public int Count => !(ctor is null) ? 1 : 0; + public int Count => ctor is not null ? 1 : 0; readonly DmdConstructorInfo? ctor; public SerializableAttributeInfo(DmdType type) { if ((type.Attributes & DmdTypeAttributes.Serializable) != 0) { var caType = type.AppDomain.GetWellKnownType(DmdWellKnownType.System_SerializableAttribute, isOptional: true); ctor = caType?.GetConstructor(Array.Empty()); - Debug2.Assert(caType is null || !(ctor is null)); + Debug2.Assert(caType is null || ctor is not null); } else ctor = null; @@ -226,14 +226,14 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index) { } readonly struct ComImportAttributeInfo { - public int Count => !(ctor is null) ? 1 : 0; + public int Count => ctor is not null ? 1 : 0; readonly DmdConstructorInfo? ctor; public ComImportAttributeInfo(DmdType type) { if (type.IsImport) { var caType = type.AppDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_InteropServices_ComImportAttribute, isOptional: true); ctor = caType?.GetConstructor(Array.Empty()); - Debug2.Assert(caType is null || !(ctor is null)); + Debug2.Assert(caType is null || ctor is not null); } else ctor = null; @@ -247,7 +247,7 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index) { } readonly struct MarshalAsAttributeInfo { - public int Count => !(ctor is null) ? 1 : 0; + public int Count => ctor is not null ? 1 : 0; readonly DmdConstructorInfo? ctor; public MarshalAsAttributeInfo(DmdFieldInfo field, DmdMarshalType? marshalType) => ctor = Initialize(field.AppDomain, marshalType); @@ -262,7 +262,7 @@ readonly struct MarshalAsAttributeInfo { if (caType is null || unmanagedTypeType is null || varEnumType is null) return null; var ctor = caType.GetConstructor(new[] { unmanagedTypeType }); - Debug2.Assert(!(ctor is null)); + Debug2.Assert(ctor is not null); return ctor; } @@ -270,13 +270,13 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index, DmdMarsh if (Count == 0) return; int argsCount = 5; - if (!(marshalType!.MarshalType is null)) + if (marshalType!.MarshalType is not null) argsCount++; - if (!(marshalType.MarshalTypeRef is null)) + if (marshalType.MarshalTypeRef is not null) argsCount++; - if (!(marshalType.MarshalCookie is null)) + if (marshalType.MarshalCookie is not null) argsCount++; - if (!(marshalType.SafeArrayUserDefinedSubType is null)) + if (marshalType.SafeArrayUserDefinedSubType is not null) argsCount++; var type = ctor!.ReflectedType!; var appDomain = type.AppDomain; @@ -289,13 +289,13 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index, DmdMarsh namedArgs[w++] = new DmdCustomAttributeNamedArgument(type.GetField("SizeConst"), new DmdCustomAttributeTypedArgument(appDomain.System_Int32, marshalType.SizeConst)); namedArgs[w++] = new DmdCustomAttributeNamedArgument(type.GetField("IidParameterIndex"), new DmdCustomAttributeTypedArgument(appDomain.System_Int32, marshalType.IidParameterIndex)); namedArgs[w++] = new DmdCustomAttributeNamedArgument(type.GetField("SafeArraySubType"), new DmdCustomAttributeTypedArgument(varEnumType, (int)marshalType.SafeArraySubType)); - if (!(marshalType.MarshalType is null)) + if (marshalType.MarshalType is not null) namedArgs[w++] = new DmdCustomAttributeNamedArgument(type.GetField("MarshalType"), new DmdCustomAttributeTypedArgument(appDomain.System_String, marshalType.MarshalType)); - if (!(marshalType.MarshalTypeRef is null)) + if (marshalType.MarshalTypeRef is not null) namedArgs[w++] = new DmdCustomAttributeNamedArgument(type.GetField("MarshalTypeRef"), new DmdCustomAttributeTypedArgument(appDomain.System_Type, marshalType.MarshalTypeRef)); - if (!(marshalType.MarshalCookie is null)) + if (marshalType.MarshalCookie is not null) namedArgs[w++] = new DmdCustomAttributeNamedArgument(type.GetField("MarshalCookie"), new DmdCustomAttributeTypedArgument(appDomain.System_String, marshalType.MarshalCookie)); - if (!(marshalType.SafeArrayUserDefinedSubType is null)) + if (marshalType.SafeArrayUserDefinedSubType is not null) namedArgs[w++] = new DmdCustomAttributeNamedArgument(type.GetField("SafeArrayUserDefinedSubType"), new DmdCustomAttributeTypedArgument(appDomain.System_Type, marshalType.SafeArrayUserDefinedSubType)); if (namedArgs.Length != w) throw new InvalidOperationException(); @@ -305,16 +305,16 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index, DmdMarsh } readonly struct FieldOffsetAttributeInfo { - public int Count => !(ctor is null) ? 1 : 0; + public int Count => ctor is not null ? 1 : 0; readonly DmdConstructorInfo? ctor; readonly int offset; public FieldOffsetAttributeInfo(DmdFieldInfo field, uint? offset) { - if (!(offset is null)) { + if (offset is not null) { this.offset = (int)offset.Value; var caType = field.AppDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_InteropServices_FieldOffsetAttribute, isOptional: true); ctor = caType?.GetConstructor(new[] { field.AppDomain.System_Int32 }); - Debug2.Assert(caType is null || !(ctor is null)); + Debug2.Assert(caType is null || ctor is not null); } else { ctor = null; @@ -331,14 +331,14 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index) { } readonly struct NonSerializedAttributeInfo { - public int Count => !(ctor is null) ? 1 : 0; + public int Count => ctor is not null ? 1 : 0; readonly DmdConstructorInfo? ctor; public NonSerializedAttributeInfo(DmdFieldInfo field) { if ((field.Attributes & DmdFieldAttributes.NotSerialized) != 0) { var caType = field.AppDomain.GetWellKnownType(DmdWellKnownType.System_NonSerializedAttribute, isOptional: true); ctor = caType?.GetConstructor(Array.Empty()); - Debug2.Assert(caType is null || !(ctor is null)); + Debug2.Assert(caType is null || ctor is not null); } else ctor = null; @@ -352,11 +352,11 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index) { } readonly struct DllImportAttributeInfo { - public int Count => !(ctor is null) ? 1 : 0; + public int Count => ctor is not null ? 1 : 0; readonly DmdConstructorInfo? ctor; public DllImportAttributeInfo(DmdMethodInfo method, in DmdImplMap? implMap) { - if (!(implMap is null)) { + if (implMap is not null) { var appDomain = method.AppDomain; var caType = appDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_InteropServices_DllImportAttribute, isOptional: true); var charSetType = appDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_InteropServices_CharSet, isOptional: true); @@ -365,7 +365,7 @@ public DllImportAttributeInfo(DmdMethodInfo method, in DmdImplMap? implMap) { ctor = null; else { ctor = caType.GetConstructor(DmdBindingFlags.Public | DmdBindingFlags.NonPublic | DmdBindingFlags.Instance, new[] { appDomain.System_String }); - Debug2.Assert(!(ctor is null)); + Debug2.Assert(ctor is not null); } } else @@ -418,14 +418,14 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index, DmdMetho } readonly struct PreserveSigAttributeInfo { - public int Count => !(ctor is null) ? 1 : 0; + public int Count => ctor is not null ? 1 : 0; readonly DmdConstructorInfo? ctor; public PreserveSigAttributeInfo(DmdMethodInfo method) { if ((method.MethodImplementationFlags & DmdMethodImplAttributes.PreserveSig) != 0) { var caType = method.AppDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_InteropServices_PreserveSigAttribute, isOptional: true); ctor = caType?.GetConstructor(Array.Empty()); - Debug2.Assert(caType is null || !(ctor is null)); + Debug2.Assert(caType is null || ctor is not null); } else ctor = null; @@ -439,14 +439,14 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index) { } readonly struct InAttributeInfo { - public int Count => !(ctor is null) ? 1 : 0; + public int Count => ctor is not null ? 1 : 0; readonly DmdConstructorInfo? ctor; public InAttributeInfo(DmdParameterInfo parameter) { if (parameter.IsIn) { var caType = parameter.Member.AppDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_InteropServices_InAttribute, isOptional: true); ctor = caType?.GetConstructor(Array.Empty()); - Debug2.Assert(caType is null || !(ctor is null)); + Debug2.Assert(caType is null || ctor is not null); } else ctor = null; @@ -460,14 +460,14 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index) { } readonly struct OutAttributeInfo { - public int Count => !(ctor is null) ? 1 : 0; + public int Count => ctor is not null ? 1 : 0; readonly DmdConstructorInfo? ctor; public OutAttributeInfo(DmdParameterInfo parameter) { if (parameter.IsOut) { var caType = parameter.Member.AppDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_InteropServices_OutAttribute, isOptional: true); ctor = caType?.GetConstructor(Array.Empty()); - Debug2.Assert(caType is null || !(ctor is null)); + Debug2.Assert(caType is null || ctor is not null); } else ctor = null; @@ -481,14 +481,14 @@ public void CopyTo(DmdCustomAttributeData[] destination, ref int index) { } readonly struct OptionalAttributeInfo { - public int Count => !(ctor is null) ? 1 : 0; + public int Count => ctor is not null ? 1 : 0; readonly DmdConstructorInfo? ctor; public OptionalAttributeInfo(DmdParameterInfo parameter) { if (parameter.IsOptional) { var caType = parameter.Member.AppDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_InteropServices_OptionalAttribute, isOptional: true); ctor = caType?.GetConstructor(Array.Empty()); - Debug2.Assert(caType is null || !(ctor is null)); + Debug2.Assert(caType is null || ctor is not null); } else ctor = null; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAppDomain.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAppDomain.cs index f9d8629655..561e487c26 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAppDomain.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAppDomain.cs @@ -339,7 +339,7 @@ internal TemporaryAssemblyDisposable(DmdAssembly assembly) { /// /// Well known type /// - public bool HasWellKnownType(DmdWellKnownType wellKnownType) => !(GetWellKnownType(wellKnownType, isOptional: true) is null); + public bool HasWellKnownType(DmdWellKnownType wellKnownType) => GetWellKnownType(wellKnownType, isOptional: true) is not null; /// /// Gets a well known type diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssembly.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssembly.cs index 4f8b737415..aea6e8882c 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssembly.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssembly.cs @@ -305,20 +305,20 @@ public DmdType[] GetTypes() { /// public object? CreateInstance(object? context, string typeName, bool ignoreCase, DmdBindingFlags bindingAttr, object?[]? args, IList? argTypes) { args ??= Array.Empty(); - if (!(argTypes is null) && args.Length != argTypes.Count) + if (argTypes is not null && args.Length != argTypes.Count) throw new ArgumentException(); var type = GetType(typeName, false, ignoreCase); if (type is null) return null; DmdConstructorInfo? ctor; - if (!(argTypes is null)) + if (argTypes is not null) ctor = type.GetConstructor(bindingAttr, argTypes); else { ctor = null; foreach (var c in type.GetConstructors(bindingAttr)) { if (c.GetMethodSignature().GetParameterTypes().Count != args.Length) continue; - if (!(ctor is null)) + if (ctor is not null) return null; ctor = c; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssemblyName.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssemblyName.cs index dbe2e643cd..0e131b854b 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssemblyName.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssemblyName.cs @@ -93,7 +93,7 @@ public void SetPublicKey(byte[]? publicKey) { /// /// public byte[]? GetPublicKeyToken() { - if (publicKeyToken is null && !(publicKey is null)) { + if (publicKeyToken is null && publicKey is not null) { try { publicKeyToken = AssemblyHasher.CreatePublicKeyToken(publicKey); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssemblyNameFormatter.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssemblyNameFormatter.cs index e912dea3d1..396d9320bf 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssemblyNameFormatter.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdAssemblyNameFormatter.cs @@ -38,17 +38,17 @@ public static void Format(StringBuilder sb, string? name, Version? version, stri sb.Append(c); } - if (!(version is null)) { + if (version is not null) { sb.Append(", Version="); sb.Append(version.ToString()); } - if (!(culture is null)) { + if (culture is not null) { sb.Append(", Culture="); sb.Append(string.IsNullOrEmpty(culture) ? "neutral" : culture); } - if (!(publicKeyOrToken is null)) { + if (publicKeyOrToken is not null) { sb.Append(isPublicKeyToken ? ", PublicKeyToken=" : ", PublicKey="); if (publicKeyOrToken.Length == 0) sb.Append("null"); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdMemberFormatter.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdMemberFormatter.cs index bf0cc29672..84eb4297d4 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdMemberFormatter.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdMemberFormatter.cs @@ -57,7 +57,7 @@ static bool IsGenericTypeDefinition(DmdType type) { return type.IsGenericTypeDefinition; // It's a TypeRef, make sure it won't throw if it can't resolve the type var resolvedType = type.ResolveNoThrow(); - if (!(resolvedType is null)) + if (resolvedType is not null) return resolvedType.IsGenericTypeDefinition; // Guess based on name return type is Impl.DmdTypeRef && type.MetadataName!.LastIndexOf('`') >= 0; @@ -68,7 +68,7 @@ static bool ContainsGenericParameters(DmdType type) { return type.ContainsGenericParameters; // It's a TypeRef, make sure it won't throw if it can't resolve the type var resolvedType = type.ResolveNoThrow(); - if (!(resolvedType is null)) + if (resolvedType is not null) return resolvedType.ContainsGenericParameters; if (type is Impl.DmdTypeRef) return type.MetadataName!.LastIndexOf('`') >= 0; @@ -87,7 +87,7 @@ static void WriteAssemblyFullName(StringBuilder sb, DmdType type) { } var nonNested = Impl.DmdTypeUtilities.GetNonNestedType(type); - if (!(nonNested is null)) { + if (nonNested is not null) { var typeScope = nonNested.TypeScope; switch (typeScope.Kind) { default: @@ -115,7 +115,7 @@ static void WriteAssemblyFullName(StringBuilder sb, DmdType type) { return type.GetGenericTypeDefinition(); var resolvedType = type.ResolveNoThrow(); - if (!(resolvedType is null)) + if (resolvedType is not null) return resolvedType.GetGenericTypeDefinition(); if (type is Impl.DmdGenericInstanceTypeRef) @@ -130,7 +130,7 @@ static ReadOnlyCollection GetGenericArguments(DmdType type) { return type.GetGenericArguments(); var resolvedType = type.ResolveNoThrow(); - if (!(resolvedType is null)) + if (resolvedType is not null) return resolvedType.GetGenericArguments(); if (type is Impl.DmdGenericInstanceTypeRef) @@ -145,7 +145,7 @@ static IList GetGenericArguments(DmdMethodBase method) { return method.GetGenericArguments(); var resolvedMethod = method.ResolveMethodBaseNoThrow(); - if (!(resolvedMethod is null)) + if (resolvedMethod is not null) return resolvedMethod.GetGenericArguments(); return Array.Empty(); @@ -490,7 +490,7 @@ void WriteMethod(string? name, DmdMethodSignature sig, IList? genericAr FormatTypeName(sig.ReturnType, flags); writer.Append(' '); writer.Append(name); - if (!(genericArguments is null)) + if (genericArguments is not null) WriteMethodGenericArguments(genericArguments, flags); if (isMethod || sig.GetParameterTypes().Count != 0 || sig.GetVarArgsParameterTypes().Count != 0) { if (!isMethod) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdObject.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdObject.cs index 2e672f0450..f11727ac95 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdObject.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdObject.cs @@ -62,7 +62,7 @@ public abstract class DmdObject { /// public bool TryGetData([NotNullWhen(true)] out T? value) where T : class { lock (lockObj) { - if (!(dataList is null)) { + if (dataList is not null) { var type = typeof(T).TypeHandle; foreach (var kv in dataList) { if (kv.key.Equals(type)) { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdPropertyInfo.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdPropertyInfo.cs index 3e4052c365..1152209456 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdPropertyInfo.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdPropertyInfo.cs @@ -54,12 +54,12 @@ public abstract class DmdPropertyInfo : DmdMemberInfo, IEquatable /// true if the property can be read /// - public bool CanRead => !(GetMethod is null); + public bool CanRead => GetMethod is not null; /// /// true if the property can be written to /// - public bool CanWrite => !(SetMethod is null); + public bool CanWrite => SetMethod is not null; /// /// Resolves a property reference diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdReadOnlyAssemblyName.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdReadOnlyAssemblyName.cs index 4115b87e66..c8587d5360 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdReadOnlyAssemblyName.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdReadOnlyAssemblyName.cs @@ -72,7 +72,7 @@ public sealed class DmdReadOnlyAssemblyName : IDmdAssemblyName { /// /// public byte[]? GetPublicKeyToken() { - if (publicKeyToken is null && !(publicKey is null)) { + if (publicKeyToken is null && publicKey is not null) { try { publicKeyToken = AssemblyHasher.CreatePublicKeyToken(publicKey); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdSigComparer.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdSigComparer.cs index efb2dcb0ab..3f08c07599 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdSigComparer.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdSigComparer.cs @@ -208,7 +208,7 @@ public bool Equals(DmdType? a, DmdType? b) { // resolve them and then compare again. var ra = a.ResolveNoThrow(); var rb = ra is null ? null : b.ResolveNoThrow(); - result = !(ra is null) && !(rb is null) && TypeScopeEquals(ra, rb); + result = ra is not null && rb is not null && TypeScopeEquals(ra, rb); if (!result && CheckTypeEquivalence) result = TIAHelper.Equivalent(ra, rb); } @@ -442,7 +442,7 @@ bool Equals(ReadOnlyCollection? a, ReadOnlyCollection? b) { } bool TypeScopeEquals(DmdType a, DmdType b) { - Debug2.Assert(!(a is null) && !(b is null) && !a.HasElementType && !b.HasElementType); + Debug2.Assert(a is not null && b is not null && !a.HasElementType && !b.HasElementType); if (DontCompareTypeScope) return true; if ((object?)a == b) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdType.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdType.cs index 6bda076e21..7ccb647de9 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdType.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdType.cs @@ -37,7 +37,7 @@ public abstract partial class DmdType : DmdMemberInfo, IEquatable { /// /// Gets the member type /// - public sealed override DmdMemberTypes MemberType => (TypeSignatureKind == DmdTypeSignatureKind.Type || TypeSignatureKind == DmdTypeSignatureKind.GenericInstance) && !(DeclaringType is null) ? DmdMemberTypes.NestedType : DmdMemberTypes.TypeInfo; + public sealed override DmdMemberTypes MemberType => (TypeSignatureKind == DmdTypeSignatureKind.Type || TypeSignatureKind == DmdTypeSignatureKind.GenericInstance) && DeclaringType is not null ? DmdMemberTypes.NestedType : DmdMemberTypes.TypeInfo; /// /// Gets the type signature kind @@ -113,7 +113,7 @@ public abstract partial class DmdType : DmdMemberInfo, IEquatable { /// /// true if it's a nested type /// - public bool IsNested => !(DeclaringType is null); + public bool IsNested => DeclaringType is not null; /// /// Gets the generic parameter attributes @@ -225,7 +225,7 @@ public bool IsSerializable { return true; var systemDelegate = AppDomain.System_Delegate; var systemEnum = AppDomain.System_Enum; - for (DmdType? type = this; !(type is null); type = type.BaseType) { + for (DmdType? type = this; type is not null; type = type.BaseType) { if (type == systemDelegate || type == systemEnum) return true; } @@ -1276,7 +1276,7 @@ public bool IsSubclassOf(DmdType type) { throw new ArgumentNullException(nameof(type)); if (this == type) return false; - for (var t = BaseType; !(t is null); t = t.BaseType) { + for (var t = BaseType; t is not null; t = t.BaseType) { if (t == type) return true; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdTypeName.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdTypeName.cs index 39ad2cee4b..67cfaa9f63 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdTypeName.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdTypeName.cs @@ -73,11 +73,11 @@ public DmdTypeName(string? @namespace, string name, string extra) { /// public static DmdTypeName Create(DmdType type) { if (type.TypeSignatureKind == DmdTypeSignatureKind.Type) { - Debug2.Assert(!(type.MetadataName is null)); + Debug2.Assert(type.MetadataName is not null); var declType = type.DeclaringType; if (declType is null) return new DmdTypeName(type.MetadataNamespace, type.MetadataName); - Debug2.Assert(!(declType.MetadataName is null)); + Debug2.Assert(declType.MetadataName is not null); if (declType.DeclaringType is null) return new DmdTypeName(declType.MetadataNamespace, declType.MetadataName, type.MetadataName); @@ -89,7 +89,7 @@ public static DmdTypeName Create(DmdType type) { list.Add(type); type = type.DeclaringType; } - Debug2.Assert(!(type.MetadataName is null)); + Debug2.Assert(type.MetadataName is not null); StringBuilder? sb = ObjectCache.AllocStringBuilder(); for (int i = list.Count - 1; i >= 0; i--) { if (i != list.Count - 1) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdWellKnownTypeUtils.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdWellKnownTypeUtils.cs index 456670922f..7003287442 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdWellKnownTypeUtils.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/DmdWellKnownTypeUtils.cs @@ -372,7 +372,7 @@ static DmdWellKnownTypeUtils() { Debug.Assert(toWellKnownType.Count == WellKnownTypesCount); #if DEBUG foreach (var name in toWellKnownTypeName) - Debug2.Assert(!(name.Name is null)); + Debug2.Assert(name.Name is not null); #endif } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdComMetadataReader.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdComMetadataReader.cs index bf21e3be5c..c1e8d70f22 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdComMetadataReader.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdComMetadataReader.cs @@ -198,7 +198,7 @@ T COMThread(Func action) { internal uint GetEnclosingTypeDefRid_COMThread(uint typeDefRid) { dispatcher.VerifyAccess(); InitializeTypeTables_COMThread(); - Debug2.Assert(!(ridToEnclosing is null)); + Debug2.Assert(ridToEnclosing is not null); bool b = ridToEnclosing.TryGetValue(typeDefRid, out uint enclTypeRid); Debug.Assert(b); return enclTypeRid; @@ -207,7 +207,7 @@ internal uint GetEnclosingTypeDefRid_COMThread(uint typeDefRid) { internal uint[] GetTypeDefNestedClassRids_COMThread(uint typeDefRid) { dispatcher.VerifyAccess(); InitializeTypeTables_COMThread(); - Debug2.Assert(!(ridToNested is null)); + Debug2.Assert(ridToNested is not null); bool b = ridToNested.TryGetValue(typeDefRid, out var list); Debug.Assert(b); return list is null || list.Count == 0 ? Array.Empty() : list.ToArray(); @@ -215,7 +215,7 @@ internal uint[] GetTypeDefNestedClassRids_COMThread(uint typeDefRid) { void InitializeTypeTables_COMThread() { dispatcher.VerifyAccess(); - if (!(ridToNested is null)) + if (ridToNested is not null) return; var allTypes = MDAPI.GetTypeDefTokens(MetaDataImport); @@ -227,8 +227,8 @@ void InitializeTypeTables_COMThread() { void UpdateTypeTables_COMThread(uint[] tokens) { dispatcher.VerifyAccess(); - Debug2.Assert(!(ridToNested is null)); - Debug2.Assert(!(ridToEnclosing is null)); + Debug2.Assert(ridToNested is not null); + Debug2.Assert(ridToEnclosing is not null); Array.Sort(tokens); foreach (uint token in tokens) { uint rid = token & 0x00FFFFFF; @@ -269,7 +269,7 @@ void DmdDynamicModuleHelper_TypeLoaded_COMThread(object? sender, DmdTypeLoadedEv uint typeToken = (uint)e.MetadataToken; uint[] newTokens; - if (!(ridToNested is null)) + if (ridToNested is not null) newTokens = UpdateTypeTables_COMThread(typeToken); else newTokens = GetNewTokens_COMThread(typeToken); @@ -283,11 +283,11 @@ void DmdDynamicModuleHelper_TypeLoaded_COMThread(object? sender, DmdTypeLoadedEv uint[] UpdateTypeTables_COMThread(uint typeToken) { dispatcher.VerifyAccess(); uint typeRid = typeToken & 0x00FFFFFF; - bool b = !(ridToEnclosing is null) && !ridToEnclosing.ContainsKey(typeRid); + bool b = ridToEnclosing is not null && !ridToEnclosing.ContainsKey(typeRid); Debug.Assert(b); if (!b) return new[] { typeToken }; - Debug2.Assert(!(ridToEnclosing is null)); + Debug2.Assert(ridToEnclosing is not null); var tokens = GetNewTokens_COMThread(typeRid); UpdateTypeTables_COMThread(tokens); @@ -295,7 +295,7 @@ uint[] UpdateTypeTables_COMThread(uint typeToken) { foreach (var token in tokens) { uint rid = token & 0x00FFFFFF; if (token != typeToken) { - b = !(typeDefList.TryGet(rid) is null); + b = typeDefList.TryGet(rid) is not null; Debug.Assert(!b); if (b) continue; @@ -370,7 +370,7 @@ DmdFieldDefCOMD CreateFieldDefCore_COMThread(uint rid, DmdType declaringType, Dm internal DmdType ReadFieldType_COMThread((IntPtr addr, uint size) signature, IList genericTypeArguments) { dispatcher.VerifyAccess(); if (fieldTypeCache.TryGetValue(signature.addr, out var fieldType)) { - if (!(fieldType is null)) + if (fieldType is not null) return fieldType; var info = ReadFieldTypeCore_COMThread(signature, genericTypeArguments); Debug.Assert(info.containedGenericParams); @@ -427,7 +427,7 @@ DmdMethodBase CreateMethodDefCore_COMThread(uint rid, DmdType declaringType, Dmd internal DmdMethodSignature ReadMethodSignature_COMThread((IntPtr addr, uint size) signature, IList? genericTypeArguments, IList? genericMethodArguments, bool isProperty) { dispatcher.VerifyAccess(); if (methodSignatureCache.TryGetValue(signature.addr, out var methodSignature)) { - if (!(methodSignature is null)) + if (methodSignature is not null) return methodSignature; var info = ReadMethodSignatureCore_COMThread(signature, genericTypeArguments, genericMethodArguments, isProperty); Debug.Assert(info.containedGenericParams); @@ -567,12 +567,12 @@ DmdPropertyDef CreatePropertyDefCore_COMThread(uint rid, DmdType declaringType, if ((classToken >> 24) == 0x1B) containedGenericParams = true; - if (!(info.fieldType is null)) { + if (info.fieldType is not null) { var fieldRef = new DmdFieldRef(reflectedTypeRef, name, rawInfo.fieldType!, info.fieldType); return (fieldRef, containedGenericParams); } else { - Debug2.Assert(!(info.methodSignature is null)); + Debug2.Assert(info.methodSignature is not null); if (name == DmdConstructorInfo.ConstructorName || name == DmdConstructorInfo.TypeConstructorName) { var ctorRef = new DmdConstructorRef(reflectedTypeRef, name, rawInfo.methodSignature!, info.methodSignature); return (ctorRef, containedGenericParams); @@ -611,7 +611,7 @@ DmdType GetMemberRefParent_COMThread(uint classToken, IList? genericTyp (DmdType? fieldType, DmdMethodSignature? methodSignature, bool containedGenericParams) ReadMethodSignatureOrFieldType_COMThread((IntPtr addr, uint size) signature, IList? genericTypeArguments, IList? genericMethodArguments) { dispatcher.VerifyAccess(); if (methodSignatureCache.TryGetValue(signature.addr, out var methodSignature)) { - if (!(methodSignature is null)) + if (methodSignature is not null) return (null, methodSignature, false); var info = ReadMethodSignatureCore_COMThread(signature, genericTypeArguments, genericMethodArguments, isProperty: false); if (info.methodSignature is null) @@ -620,7 +620,7 @@ DmdType GetMemberRefParent_COMThread(uint classToken, IList? genericTyp return (null, info.methodSignature, info.containedGenericParams); } else if (fieldTypeCache.TryGetValue(signature.addr, out var fieldType)) { - if (!(fieldType is null)) + if (fieldType is not null) return (fieldType, null, false); var info = ReadFieldTypeCore_COMThread(signature, genericTypeArguments); if (info.fieldType is null) @@ -630,7 +630,7 @@ DmdType GetMemberRefParent_COMThread(uint classToken, IList? genericTyp } else { var info = DmdSignatureReader.ReadMethodSignatureOrFieldType(module, new DmdPointerDataStream(signature), genericTypeArguments, genericMethodArguments, resolveTypes); - if (!(info.fieldType is null)) { + if (info.fieldType is not null) { if (info.containedGenericParams) fieldTypeCache.Add(signature.addr, null); else @@ -638,7 +638,7 @@ DmdType GetMemberRefParent_COMThread(uint classToken, IList? genericTyp return (info.fieldType, null, info.containedGenericParams); } else { - Debug2.Assert(!(info.methodSignature is null)); + Debug2.Assert(info.methodSignature is not null); if (info.containedGenericParams) methodSignatureCache.Add(signature.addr, null); else @@ -674,7 +674,7 @@ DmdType GetMemberRefParent_COMThread(uint classToken, IList? genericTyp return null; using (bodyStream) { var body = DmdMethodBodyReader.Create(this, bodyStream, genericTypeArguments, genericMethodArguments); - Debug2.Assert(!(body is null)); + Debug2.Assert(body is not null); return body; } } @@ -1000,13 +1000,13 @@ public override void GetPEKind(out DmdPortableExecutableKinds peKind, out DmdIma public override DmdReadOnlyAssemblyName GetName() { if (assemblyName is null) InitializeAssemblyName(); - Debug2.Assert(!(assemblyName is null)); + Debug2.Assert(assemblyName is not null); return assemblyName; } DmdReadOnlyAssemblyName? assemblyName; void InitializeAssemblyName() { - if (!(assemblyName is null)) + if (assemblyName is not null) return; if (IsCOMThread) InitializeAssemblyName_COMThread(); @@ -1016,7 +1016,7 @@ void InitializeAssemblyName() { void InitializeAssemblyName_COMThread() { dispatcher.VerifyAccess(); - if (!(assemblyName is null)) + if (assemblyName is not null) return; const uint token = 0x20000001; @@ -1148,7 +1148,7 @@ internal DmdCustomAttributeData[] ReadSecurityAttributesCore_COMThread(uint toke res.Add((cas, action)); } } - if (!(firstCas is null)) + if (firstCas is not null) return firstCas; if (res is null) return Array.Empty(); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdEventDefCOMD.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdEventDefCOMD.cs index 7ff5cae008..1324f84326 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdEventDefCOMD.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdEventDefCOMD.cs @@ -71,7 +71,7 @@ protected override void GetMethods(out DmdMethodInfo? addMethod, out DmdMethodIn if ((token >> 24) != 0x06 || (token & 0x00FFFFFF) == 0) return null; var method = ReflectedType!.GetMethod(Module, (int)token) as DmdMethodInfo; - Debug2.Assert(!(method is null)); + Debug2.Assert(method is not null); return method; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdGenericParameterTypeCOMD.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdGenericParameterTypeCOMD.cs index 9168e8ecd0..0a915eef41 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdGenericParameterTypeCOMD.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdGenericParameterTypeCOMD.cs @@ -45,7 +45,7 @@ public DmdGenericParameterTypeCOMD(DmdComMetadataReader reader, uint rid, DmdMet IList genericTypeArguments; IList? genericMethodArguments; - if (!(DeclaringMethod is null)) { + if (DeclaringMethod is not null) { genericTypeArguments = DeclaringMethod.DeclaringType!.GetGenericArguments(); genericMethodArguments = DeclaringMethod.GetGenericArguments(); } @@ -66,7 +66,7 @@ public DmdGenericParameterTypeCOMD(DmdComMetadataReader reader, uint rid, DmdMet } DmdGenericParameterTypeCOMD Clone(IList? customModifiers) => - !(DeclaringMethod is null) ? + DeclaringMethod is not null ? new DmdGenericParameterTypeCOMD(reader, Rid, DeclaringMethod, MetadataName, GenericParameterPosition, GenericParameterAttributes, customModifiers) : new DmdGenericParameterTypeCOMD(reader, Rid, (DmdTypeBase)DeclaringType!, MetadataName, GenericParameterPosition, GenericParameterAttributes, customModifiers); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdPropertyDefCOMD.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdPropertyDefCOMD.cs index aa8138e265..5bf6ce7b84 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdPropertyDefCOMD.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/DmdPropertyDefCOMD.cs @@ -73,7 +73,7 @@ protected override void GetMethods(out DmdMethodInfo? getMethod, out DmdMethodIn if ((token >> 24) != 0x06 || (token & 0x00FFFFFF) == 0) return null; var method = ReflectedType!.GetMethod(Module, (int)token) as DmdMethodInfo; - Debug2.Assert(!(method is null)); + Debug2.Assert(method is not null); return method; } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/LazyList.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/LazyList.cs index 512d7f9de6..b6128f1653 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/LazyList.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/COMD/LazyList.cs @@ -31,7 +31,7 @@ public T? this[uint index] { if (dict.TryGetValue(index, out elem)) return elem; elem = readElementByRID(index + 1); - if (!(elem is null)) + if (elem is not null) dict[index] = elem; return elem; } @@ -58,7 +58,7 @@ sealed class LazyList where TValue : class { if (dict.TryGetValue(index, out elem)) return elem; elem = readElementByRID(index + 1, arg); - if (!(elem is null)) + if (elem is not null) dict[index] = elem; return elem; } @@ -80,7 +80,7 @@ sealed class LazyList2 where TValue : class { if (dict.TryGetValue(index, out elem)) return elem; var info = readElementByRID(index + 1, arg1, arg2); - if (!((elem = info.elem) is null) && !info.containedGenericParams) + if ((elem = info.elem) is not null && !info.containedGenericParams) dict[index] = elem; return elem; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdAppDomainImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdAppDomainImpl.cs index a06e3601ab..e88ede4aa7 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdAppDomainImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdAppDomainImpl.cs @@ -258,7 +258,7 @@ public override DmdAssembly[] GetAssemblies(bool includeSyntheticAssemblies) { DmdAssemblyImpl[] assembliesCopy; lock (assembliesLockObj) { - if (!(name is null)) { + if (name is not null) { if (assemblyNameToAssembly.TryGetValue(name, out var cached)) return cached; } @@ -272,9 +272,9 @@ public override DmdAssembly[] GetAssemblies(bool includeSyntheticAssemblies) { var assembly = GetAssemblySlowCore(assembliesCopy, simpleName, name); - if (!(assembly is null)) { + if (assembly is not null) { lock (assembliesLockObj) { - if (!(name is null)) { + if (name is not null) { if (assemblyNameToAssembly.TryGetValue(name, out var cached)) return cached; assemblyNameToAssembly[name.AsReadOnly()] = assembly; @@ -400,7 +400,7 @@ void RemoveAssemblyLoadedListener(AssemblyLoadedListener listener) { if (name is null) throw new ArgumentNullException(nameof(name)); var asm = GetAssembly(name); - if (!(asm is null)) + if (asm is not null) return asm; var assemblyType = GetWellKnownType(DmdWellKnownType.System_Reflection_Assembly); @@ -433,7 +433,7 @@ void RemoveAssemblyLoadedListener(AssemblyLoadedListener listener) { if (path is null) throw new ArgumentNullException(nameof(path)); var asm = GetAssemblyByPath(path); - if (!(asm is null)) + if (asm is not null) return asm; var assemblyType = GetWellKnownType(DmdWellKnownType.System_Reflection_Assembly); @@ -447,7 +447,7 @@ void RemoveAssemblyLoadedListener(AssemblyLoadedListener listener) { throw new ArgumentNullException(nameof(assemblyFile)); var name = new DmdReadOnlyAssemblyName(assemblyFile); var asm = GetAssembly(name) ?? GetAssemblyByPath(assemblyFile); - if (!(asm is null)) + if (asm is not null) return asm; var assemblyType = GetWellKnownType(DmdWellKnownType.System_Reflection_Assembly); @@ -490,7 +490,7 @@ public override DmdType MakePointerType(DmdType elementType, IList var et = elementType as DmdTypeBase; if (et is null) throw new ArgumentException(); - if (!(customModifiers is null)) { + if (customModifiers is not null) { for (int i = 0; i < customModifiers.Count; i++) { if (customModifiers[i].Type.AppDomain != this) throw new ArgumentException(); @@ -612,7 +612,7 @@ public override DmdType MakeGenericType(DmdType genericTypeDefinition, IList? dict1 = null, dict2 = null; toModuleTypeDictIgnoreCase?.TryGetValue(module, out dict1); toModuleTypeDict?.TryGetValue(module, out dict2); - Debug2.Assert(!(dict1 is null) || !(dict2 is null)); + Debug2.Assert(dict1 is not null || dict2 is not null); foreach (var type in types) { if (type is null) continue; - if (!(dict1 is null)) + if (dict1 is not null) dict1[type] = type; - if (!(dict2 is null)) + if (dict2 is not null) dict2[type] = type; } } @@ -1079,7 +1079,7 @@ void DmdMetadataReader_TypesUpdated(DmdModule module, DmdTypesUpdatedEventArgs e internal DmdType[] GetSZArrayInterfaces(DmdType elementType) { var ifaces = defaultExistingWellKnownSZArrayInterfaces; if (ifaces is null) { - Debug2.Assert(!(CorLib is null), "CorLib hasn't been loaded yet!"); + Debug2.Assert(CorLib is not null, "CorLib hasn't been loaded yet!"); if (CorLib is null) return Array.Empty(); List? list = ObjectPools.AllocListOfType(); @@ -1088,7 +1088,7 @@ internal DmdType[] GetSZArrayInterfaces(DmdType elementType) { // They're not always present so if we fail to find a type in the corlib, we don't // want to search the remaining assemblies (could be hundreds of assemblies). var iface = GetWellKnownType(wellKnownType, isOptional: true, onlyCorLib: true); - if (!(iface is null)) + if (iface is not null) list.Add(iface); } Interlocked.CompareExchange(ref defaultExistingWellKnownSZArrayInterfaces, ObjectPools.FreeAndToArray(ref list), null); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdAssemblyImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdAssemblyImpl.cs index 6751336ed0..4d780045b3 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdAssemblyImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdAssemblyImpl.cs @@ -231,7 +231,7 @@ public TypeDefResolver(DmdAssemblyImpl assembly, bool ignoreCase) { return null; DmdAssemblyImpl? targetAssembly = assembly; - if (!(assemblyName is null) && !assembly.AppDomainImpl.AssemblyNameEqualityComparer.Equals(targetAssembly.GetName(), assemblyName)) { + if (assemblyName is not null && !assembly.AppDomainImpl.AssemblyNameEqualityComparer.Equals(targetAssembly.GetName(), assemblyName)) { targetAssembly = (DmdAssemblyImpl?)targetAssembly.AppDomain.GetAssembly(assemblyName); if (targetAssembly is null) return null; @@ -266,7 +266,7 @@ public TypeDefResolver(DmdAssemblyImpl assembly, bool ignoreCase) { var resolver = new TypeDefResolver(this, (options & DmdGetTypeOptions.IgnoreCase) != 0); var type = DmdTypeNameParser.Parse(resolver, typeName); - if (!(type is null)) + if (type is not null) return appDomain.Intern(type, DmdMakeTypeOptions.NoResolve); if ((options & DmdGetTypeOptions.ThrowOnError) != 0) @@ -275,7 +275,7 @@ public TypeDefResolver(DmdAssemblyImpl assembly, bool ignoreCase) { } public override ReadOnlyCollection GetSecurityAttributesData() { - if (!(securityAttributes is null)) + if (securityAttributes is not null) return securityAttributes; var cas = metadataReader.ReadSecurityAttributes(0x20000001); Interlocked.CompareExchange(ref securityAttributes, ReadOnlyCollectionHelpers.Create(cas), null); @@ -284,7 +284,7 @@ public override ReadOnlyCollection GetSecurityAttributes volatile ReadOnlyCollection? securityAttributes; public override ReadOnlyCollection GetCustomAttributesData() { - if (!(customAttributes is null)) + if (customAttributes is not null) return customAttributes; var cas = metadataReader.ReadCustomAttributes(0x20000001); var newCAs = CustomAttributesHelper.AddPseudoCustomAttributes(this, cas, GetSecurityAttributesData()); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdByRefType.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdByRefType.cs index cbe047413b..759ff4d213 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdByRefType.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdByRefType.cs @@ -54,7 +54,7 @@ public DmdByRefType(DmdTypeBase elementType, IList? customMod if (!IsMetadataReference) return this; var newElementType = elementType.ResolveNoThrow(); - if (!(newElementType is null)) + if (newElementType is not null) return AppDomain.MakeByRefType(newElementType, GetCustomModifiers()); return null; } @@ -64,7 +64,7 @@ public DmdByRefType(DmdTypeBase elementType, IList? customMod if (IsFullyResolved) return this; var et = elementType.FullResolve(); - if (!(et is null)) + if (et is not null) return (DmdTypeBase)AppDomain.MakeByRefType(et, GetCustomModifiers()); return null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdConstructorDef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdConstructorDef.cs index b583941129..8a37f93a6e 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdConstructorDef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdConstructorDef.cs @@ -46,7 +46,7 @@ protected DmdConstructorDef(uint rid, DmdType declaringType, DmdType reflectedTy protected abstract DmdType[]? CreateGenericParameters(); public sealed override ReadOnlyCollection GetGenericArguments() { var f = ExtraFields; - if (!(f.__genericParameters_DONT_USE is null)) + if (f.__genericParameters_DONT_USE is not null) return f.__genericParameters_DONT_USE; var res = CreateGenericParameters(); Interlocked.CompareExchange(ref f.__genericParameters_DONT_USE, ReadOnlyCollectionHelpers.Create(res), null); @@ -55,7 +55,7 @@ public sealed override ReadOnlyCollection GetGenericArguments() { public sealed override ReadOnlyCollection GetParameters() { var f = ExtraFields; - if (!(f.__parameters_DONT_USE is null)) + if (f.__parameters_DONT_USE is not null) return f.__parameters_DONT_USE; var info = CreateParameters(); Debug.Assert(info.Length == GetMethodSignature().GetParameterTypes().Count); @@ -73,7 +73,7 @@ public sealed override ReadOnlyCollection GetCustomAttri void InitializeCustomAttributes() { var f = ExtraFields; - if (!(f.__customAttributes_DONT_USE is null)) + if (f.__customAttributes_DONT_USE is not null) return; var info = CreateCustomAttributes(); var newSAs = ReadOnlyCollectionHelpers.Create(info.sas); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdConstructorRef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdConstructorRef.cs index f0bd22b13b..93a9f0d134 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdConstructorRef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdConstructorRef.cs @@ -39,22 +39,22 @@ sealed class DmdConstructorRef : DmdConstructorInfoBase { DmdConstructorDef ResolvedConstructor => GetResolvedConstructor(throwOnError: true)!; DmdConstructorDef? GetResolvedConstructor(bool throwOnError) { - if (!(__resolvedConstructor_DONT_USE is null)) + if (__resolvedConstructor_DONT_USE is not null) return __resolvedConstructor_DONT_USE; DmdConstructorDef? newResolvedCtor = null; var declType = declaringTypeRef.Resolve(throwOnError); - if (!(declType is null)) { + if (declType is not null) { var nonGenericInstDeclType = declType.IsGenericType ? declType.GetGenericTypeDefinition() : declType; var nonGenericInstDeclTypeMethod = nonGenericInstDeclType?.GetMethod(Name, rawMethodSignature, throwOnError: false) as DmdConstructorDef; - if (!(nonGenericInstDeclTypeMethod is null)) { + if (nonGenericInstDeclTypeMethod is not null) { newResolvedCtor = (object?)nonGenericInstDeclTypeMethod.DeclaringType == declType ? nonGenericInstDeclTypeMethod : declType.GetMethod(nonGenericInstDeclTypeMethod.Module, nonGenericInstDeclTypeMethod.MetadataToken) as DmdConstructorDef; - Debug2.Assert(!(newResolvedCtor is null)); + Debug2.Assert(newResolvedCtor is not null); } } - if (!(newResolvedCtor is null)) { + if (newResolvedCtor is not null) { Interlocked.CompareExchange(ref __resolvedConstructor_DONT_USE, newResolvedCtor, null); Debug.Assert(DmdMemberInfoEqualityComparer.DefaultMember.Equals(__resolvedConstructor_DONT_USE!.ReflectedType, declaringTypeRef)); return __resolvedConstructor_DONT_USE; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdCustomAttributeReader.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdCustomAttributeReader.cs index 1f16ae5a31..8a81165afd 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdCustomAttributeReader.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdCustomAttributeReader.cs @@ -348,7 +348,7 @@ static SerializationType ToSerializationType(TypeCode typeCode) { } object? ReadEnumValue(DmdType? underlyingType) { - if (!(underlyingType is null)) { + if (underlyingType is not null) { var typeCode = DmdType.GetTypeCode(underlyingType); if (typeCode < TypeCode.Boolean || typeCode > TypeCode.UInt64) throw new CABlobParserException("Invalid enum underlying type"); @@ -363,7 +363,7 @@ static ReadOnlyCollection GetGenericArguments(DmdType type) { return type.GetGenericArguments(); var resolvedType = type.ResolveNoThrow(); - if (!(resolvedType is null)) + if (resolvedType is not null) return resolvedType.GetGenericArguments(); return ReadOnlyCollectionHelpers.Empty(); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdDeclSecurityReader.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdDeclSecurityReader.cs index 47ad763a35..801fb3d975 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdDeclSecurityReader.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdDeclSecurityReader.cs @@ -82,7 +82,7 @@ DmdCustomAttributeData[] ReadBinaryFormat(SecurityAction action) { if (namedArgs is null) throw new IOException(); var (ctor, ctorArguments) = GetConstructor(type, action); - Debug2.Assert(!(ctor is null)); + Debug2.Assert(ctor is not null); if (ctor is null) continue; res[w++] = new DmdCustomAttributeData(ctor, ctorArguments, namedArgs, isPseudoCustomAttribute: false); @@ -103,8 +103,8 @@ DmdCustomAttributeData[] ReadXmlFormat(SecurityAction action) { var type = module.AppDomain.GetWellKnownType(DmdWellKnownType.System_Security_Permissions_PermissionSetAttribute); var (ctor, ctorArguments) = GetConstructor(type, action); var xmlProp = type.GetProperty("XML", module.AppDomain.System_String, Array.Empty()); - Debug2.Assert(!(ctor is null)); - Debug2.Assert(!(xmlProp is null)); + Debug2.Assert(ctor is not null); + Debug2.Assert(xmlProp is not null); if (ctor is null || xmlProp is null) return Array.Empty(); var namedArguments = new[] { new DmdCustomAttributeNamedArgument(xmlProp, new DmdCustomAttributeTypedArgument(module.AppDomain.System_String, xml)) }; @@ -115,13 +115,13 @@ DmdCustomAttributeData[] ReadXmlFormat(SecurityAction action) { var appDomain = type.AppDomain; var securityActionType = appDomain.GetWellKnownType(DmdWellKnownType.System_Security_Permissions_SecurityAction); var ctor = type.GetConstructor(new[] { securityActionType }); - if (!(ctor is null)) { + if (ctor is not null) { var ctorArgs = new[] { new DmdCustomAttributeTypedArgument(securityActionType, (int)action) }; return (ctor, ctorArgs); } ctor = type.GetConstructor(Array.Empty()) ?? type.GetConstructors().FirstOrDefault(); - Debug2.Assert(!(ctor is null)); + Debug2.Assert(ctor is not null); return (ctor, null); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdEventDef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdEventDef.cs index 5ce7d71e1b..1d7a9ee366 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdEventDef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdEventDef.cs @@ -53,7 +53,7 @@ public sealed override DmdMethodInfo[] GetOtherMethods(DmdGetAccessorOptions opt var list = new List(otherMethods.Count); foreach (var method in otherMethods) { var accessor = AccessorUtils.FilterAccessor(options, method); - if (!(accessor is null)) + if (accessor is not null) list.Add(accessor); } return list.Count == 0 ? Array.Empty() : list.ToArray(); @@ -82,7 +82,7 @@ public sealed override DmdMethodInfo[] GetOtherMethods(DmdGetAccessorOptions opt void InitializeEventMethods() { var f = ExtraFields; - if (!(f.__otherMethods_DONT_USE is null)) + if (f.__otherMethods_DONT_USE is not null) return; GetMethods(out var addMethod, out var removeMethod, out var raiseMethod, out var otherMethods); lock (LockObject) { @@ -98,7 +98,7 @@ void InitializeEventMethods() { public sealed override ReadOnlyCollection GetCustomAttributesData() { var f = ExtraFields; - if (!(f.__customAttributes_DONT_USE is null)) + if (f.__customAttributes_DONT_USE is not null) return f.__customAttributes_DONT_USE; var info = CreateCustomAttributes(); var newCAs = CustomAttributesHelper.AddPseudoCustomAttributes(this, info); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdFieldDef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdFieldDef.cs index 5a70d8572c..f4fff51a76 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdFieldDef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdFieldDef.cs @@ -40,7 +40,7 @@ protected DmdFieldDef(uint rid, DmdType declaringType, DmdType reflectedType) { public sealed override DmdFieldInfo? Resolve(bool throwOnError) => this; public sealed override ReadOnlyCollection GetCustomAttributesData() { - if (!(__customAttributes_DONT_USE is null)) + if (__customAttributes_DONT_USE is not null) return __customAttributes_DONT_USE; var info = CreateCustomAttributes(); var newCAs = CustomAttributesHelper.AddPseudoCustomAttributes(this, info.cas, info.fieldOffset, info.marshalType); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdFieldRef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdFieldRef.cs index 410e68dd32..42f1608551 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdFieldRef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdFieldRef.cs @@ -36,22 +36,22 @@ sealed class DmdFieldRef : DmdFieldInfoBase { DmdFieldDef ResolvedField => GetResolvedField(throwOnError: true)!; DmdFieldDef? GetResolvedField(bool throwOnError) { - if (!(__resolvedField_DONT_USE is null)) + if (__resolvedField_DONT_USE is not null) return __resolvedField_DONT_USE; DmdFieldDef? newResolvedField = null; var declType = declaringTypeRef.Resolve(throwOnError); - if (!(declType is null)) { + if (declType is not null) { var nonGenericInstDeclType = declType.IsGenericType ? declType.GetGenericTypeDefinition() : declType; var nonGenericInstDeclTypeField = (DmdFieldDef?)nonGenericInstDeclType?.GetField(Name, rawFieldType, throwOnError: false); - if (!(nonGenericInstDeclTypeField is null)) { + if (nonGenericInstDeclTypeField is not null) { newResolvedField = (object?)nonGenericInstDeclTypeField.DeclaringType == declType ? nonGenericInstDeclTypeField : (DmdFieldDef?)declType.GetField(nonGenericInstDeclTypeField.Module, nonGenericInstDeclTypeField.MetadataToken); - Debug2.Assert(!(newResolvedField is null)); + Debug2.Assert(newResolvedField is not null); } } - if (!(newResolvedField is null)) { + if (newResolvedField is not null) { Interlocked.CompareExchange(ref __resolvedField_DONT_USE, newResolvedField, null); Debug.Assert(DmdMemberInfoEqualityComparer.DefaultMember.Equals(__resolvedField_DONT_USE!.ReflectedType, declaringTypeRef)); return __resolvedField_DONT_USE; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericInstanceType.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericInstanceType.cs index bac26d7029..9b67c64403 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericInstanceType.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericInstanceType.cs @@ -109,7 +109,7 @@ public DmdGenericInstanceType(DmdTypeDef genericTypeDefinition, IList t if (IsFullyResolved) return this; var newTypeArguments = DmdTypeUtilities.FullResolve(typeArguments); - if (!(newTypeArguments is null)) + if (newTypeArguments is not null) return (DmdTypeBase)AppDomain.MakeGenericType(genericTypeDefinition, newTypeArguments, GetCustomModifiers()); return null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericInstanceTypeRef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericInstanceTypeRef.cs index f0e5b6b410..4c93f3ce99 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericInstanceTypeRef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericInstanceTypeRef.cs @@ -41,7 +41,7 @@ sealed class DmdGenericInstanceTypeRef : DmdTypeBase { DmdGenericInstanceType ResolvedType => GetResolvedType(throwOnError: true)!; DmdGenericInstanceType? GetResolvedType(bool throwOnError) { - if (!(__resolvedType_DONT_USE is null)) + if (__resolvedType_DONT_USE is not null) return __resolvedType_DONT_USE; var typeDef = genericTypeRef.GetResolvedType(throwOnError); var newRT = (DmdGenericInstanceType?)typeDef?.AppDomain.MakeGenericType(typeDef, typeArguments, GetCustomModifiers()); @@ -68,7 +68,7 @@ public DmdGenericInstanceTypeRef(DmdTypeRef genericTypeRef, IList typeA public override DmdType GetGenericTypeDefinition() { var resolvedType = GetResolvedType(throwOnError: false); - if (!(resolvedType is null)) + if (resolvedType is not null) return resolvedType.GetGenericTypeDefinition(); return genericTypeRef; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericParameterType.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericParameterType.cs index 7bea6f81a2..a929b4f830 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericParameterType.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericParameterType.cs @@ -25,7 +25,7 @@ You should have received a copy of the GNU General Public License namespace dnSpy.Debugger.DotNet.Metadata.Impl { abstract class DmdGenericParameterType : DmdTypeBase { - public override DmdTypeSignatureKind TypeSignatureKind => !(declaringType is null) ? DmdTypeSignatureKind.TypeGenericParameter : DmdTypeSignatureKind.MethodGenericParameter; + public override DmdTypeSignatureKind TypeSignatureKind => declaringType is not null ? DmdTypeSignatureKind.TypeGenericParameter : DmdTypeSignatureKind.MethodGenericParameter; public sealed override DmdTypeScope TypeScope => new DmdTypeScope(Module); public sealed override DmdMethodBase? DeclaringMethod => declaringMethod; public sealed override DmdType? DeclaringType => declaringType; @@ -92,7 +92,7 @@ protected DmdGenericParameterType(int position, IList? custom } public sealed override ReadOnlyCollection GetGenericParameterConstraints() { - if (!(__genericParameterConstraints_DONT_USE is null)) + if (__genericParameterConstraints_DONT_USE is not null) return __genericParameterConstraints_DONT_USE; var res = CreateGenericParameterConstraints(); Interlocked.CompareExchange(ref __genericParameterConstraints_DONT_USE, ReadOnlyCollectionHelpers.Create(res), null); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericParameterTypeImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericParameterTypeImpl.cs index af8bbe304c..3a2fc216db 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericParameterTypeImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdGenericParameterTypeImpl.cs @@ -33,7 +33,7 @@ public DmdGenericParameterTypeImpl(DmdAppDomain appDomain, DmdMethodBase declari protected override DmdType[]? CreateGenericParameterConstraints() => Array.Empty(); DmdGenericParameterTypeImpl Clone(IList? customModifiers) => - !(DeclaringMethod is null) ? + DeclaringMethod is not null ? new DmdGenericParameterTypeImpl(AppDomain, DeclaringMethod, MetadataName, GenericParameterPosition, GenericParameterAttributes, customModifiers) : new DmdGenericParameterTypeImpl(AppDomain, (DmdTypeBase)DeclaringType!, MetadataName, GenericParameterPosition, GenericParameterAttributes, customModifiers); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdLazyMetadataReader.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdLazyMetadataReader.cs index 17fa3db330..c03f36d2be 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdLazyMetadataReader.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdLazyMetadataReader.cs @@ -38,7 +38,7 @@ public DmdLazyMetadataReader(Func getMetadata, Func sizes, IList if (!IsMetadataReference) return this; var newElementType = elementType.ResolveNoThrow(); - if (!(newElementType is null)) + if (newElementType is not null) return AppDomain.MakeArrayType(newElementType, rank, sizes, lowerBounds, GetCustomModifiers()); return null; } @@ -80,7 +80,7 @@ public DmdMDArrayType(DmdTypeBase elementType, int rank, IList sizes, IList if (IsFullyResolved) return this; var et = elementType.FullResolve(); - if (!(et is null)) + if (et is not null) return (DmdTypeBase)AppDomain.MakeArrayType(et, rank, sizes, lowerBounds, GetCustomModifiers()); return null; } @@ -106,7 +106,7 @@ DmdType[] CreateParameterTypes(DmdType? lastType) { var int32Type = AppDomain.System_Int32; for (int i = 0; i < types.Length; i++) types[i] = int32Type; - if (!(lastType is null)) + if (lastType is not null) types[types.Length - 1] = lastType; return types; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMemberInfoComparer.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMemberInfoComparer.cs index b7b4cba92a..2b05e29399 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMemberInfoComparer.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMemberInfoComparer.cs @@ -91,7 +91,7 @@ public static bool IsMatch(DmdEventInfo @event, DmdBindingFlags bindingAttr) { attr |= DmdBindingFlags.Instance; if ((object)@event.ReflectedType! != @event.DeclaringType) { var method = @event.AddMethod; - if (!(method is null)) { + if (method is not null) { if (method.IsStatic) { if (method.IsPrivate) return false; @@ -118,7 +118,7 @@ public static bool IsMatch(DmdPropertyInfo property, DmdBindingFlags bindingAttr attr |= DmdBindingFlags.Instance; if ((object)property.ReflectedType! != property.DeclaringType) { var method = property.GetMethod; - if (!(method is null)) { + if (method is not null) { if (method.IsStatic) { if (method.IsPrivate) return false; @@ -160,7 +160,7 @@ static bool IsMatch(IList p, IList types) { } public static bool IsMatch(DmdPropertyInfo property, DmdType returnType) { - if (!(returnType is null)) { + if (returnType is not null) { var comparer = new DmdSigComparer(DmdSigComparerOptions.CheckTypeEquivalence | DmdMemberInfoEqualityComparer.DefaultTypeOptions); if (!comparer.Equals(property.PropertyType, returnType)) return false; @@ -179,7 +179,7 @@ public static bool IsMatch(DmdMemberInfo member, string name, DmdBindingFlags bi public static bool IsMatch(DmdType type, string? @namespace, string name, DmdBindingFlags bindingAttr) { // Namespace comparison is exact - if (!(@namespace is null) && type.Namespace != @namespace) + if (@namespace is not null && type.Namespace != @namespace) return false; if ((bindingAttr & DmdBindingFlags.IgnoreCase) != 0) return StringComparer.OrdinalIgnoreCase.Equals(type.Name, name); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMetadataReaderBase.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMetadataReaderBase.cs index 452655929e..3013ce4a5e 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMetadataReaderBase.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMetadataReaderBase.cs @@ -34,13 +34,13 @@ abstract class DmdMetadataReaderBase : DmdMetadataReader { switch ((uint)metadataToken >> 24) { case 0x06: var method = ResolveMethodDef(rid); - if (!(method is null)) + if (method is not null) return method; break; case 0x0A: var mr = ResolveMemberRef(rid, genericTypeArguments, genericMethodArguments); - if (!(mr is null)) { + if (mr is not null) { if (mr is DmdMethodBase methodRef) return TryResolve(methodRef, options); if ((options & DmdResolveOptions.ThrowOnError) != 0) @@ -50,7 +50,7 @@ abstract class DmdMetadataReaderBase : DmdMetadataReader { case 0x2B: var methodSpec = ResolveMethodSpec(rid, genericTypeArguments, genericMethodArguments); - if (!(methodSpec is null)) + if (methodSpec is not null) return TryResolve(methodSpec, options); break; } @@ -65,13 +65,13 @@ abstract class DmdMetadataReaderBase : DmdMetadataReader { switch ((uint)metadataToken >> 24) { case 0x04: var field = ResolveFieldDef(rid); - if (!(field is null)) + if (field is not null) return field; break; case 0x0A: var memberRef = ResolveMemberRef(rid, genericTypeArguments, genericMethodArguments); - if (!(memberRef is null)) { + if (memberRef is not null) { if (memberRef is DmdFieldInfo fieldRef) return TryResolve(fieldRef, options); if ((options & DmdResolveOptions.ThrowOnError) != 0) @@ -90,25 +90,25 @@ abstract class DmdMetadataReaderBase : DmdMetadataReader { switch ((uint)metadataToken >> 24) { case 0x01: var typeRef = ResolveTypeRef(rid); - if (!(typeRef is null)) + if (typeRef is not null) return TryResolve(typeRef, options); break; case 0x02: var typeDef = ResolveTypeDef(rid); - if (!(typeDef is null)) + if (typeDef is not null) return typeDef; break; case 0x1B: var typeSpec = ResolveTypeSpec(rid, genericTypeArguments, genericMethodArguments); - if (!(typeSpec is null)) + if (typeSpec is not null) return TryResolve(typeSpec, options); break; case 0x27: var exportedType = ResolveExportedType(rid); - if (!(exportedType is null)) + if (exportedType is not null) return exportedType;// Don't try to resolve it, callers want the actual reference break; } @@ -123,49 +123,49 @@ abstract class DmdMetadataReaderBase : DmdMetadataReader { switch ((uint)metadataToken >> 24) { case 0x01: var typeRef = ResolveTypeRef(rid); - if (!(typeRef is null)) + if (typeRef is not null) return TryResolve(typeRef, options); break; case 0x02: var typeDef = ResolveTypeDef(rid); - if (!(typeDef is null)) + if (typeDef is not null) return typeDef; break; case 0x04: var field = ResolveFieldDef(rid); - if (!(field is null)) + if (field is not null) return field; break; case 0x06: var method = ResolveMethodDef(rid); - if (!(method is null)) + if (method is not null) return method; break; case 0x0A: var memberRef = ResolveMemberRef(rid, genericTypeArguments, genericMethodArguments); - if (!(memberRef is null)) + if (memberRef is not null) return TryResolve(memberRef, options); break; case 0x1B: var typeSpec = ResolveTypeSpec(rid, genericTypeArguments, genericMethodArguments); - if (!(typeSpec is null)) + if (typeSpec is not null) return TryResolve(typeSpec, options); break; case 0x27: var exportedType = ResolveExportedType(rid); - if (!(exportedType is null)) + if (exportedType is not null) return exportedType;// Don't try to resolve it, callers want the actual reference break; case 0x2B: var methodSpec = ResolveMethodSpec(rid, genericTypeArguments, genericMethodArguments); - if (!(methodSpec is null)) + if (methodSpec is not null) return TryResolve(methodSpec, options); break; } @@ -180,7 +180,7 @@ abstract class DmdMetadataReaderBase : DmdMetadataReader { switch ((uint)metadataToken >> 24) { case 0x11: var methodSig = ResolveMethodSignature(rid, genericTypeArguments, genericMethodArguments); - if (!(methodSig is null)) + if (methodSig is not null) return methodSig; break; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodDef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodDef.cs index 0ad4345cd1..b1886909e2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodDef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodDef.cs @@ -56,7 +56,7 @@ protected DmdMethodDef(uint rid, DmdType declaringType, DmdType reflectedType) { protected abstract DmdType[]? CreateGenericParameters(); public sealed override ReadOnlyCollection GetGenericArguments() { var f = ExtraFields; - if (!(f.__genericParameters_DONT_USE is null)) + if (f.__genericParameters_DONT_USE is not null) return f.__genericParameters_DONT_USE; var res = CreateGenericParameters(); Interlocked.CompareExchange(ref f.__genericParameters_DONT_USE, ReadOnlyCollectionHelpers.Create(res), null); @@ -71,7 +71,7 @@ public sealed override ReadOnlyCollection GetParameters() { } void InitializeParameters() { var f = ExtraFields; - if (!(f.__parameters_DONT_USE is null)) + if (f.__parameters_DONT_USE is not null) return; var info = CreateParameters(); Debug.Assert(info.parameters.Length == GetMethodSignature().GetParameterTypes().Count); @@ -113,7 +113,7 @@ public sealed override ReadOnlyCollection GetCustomAttri void InitializeCustomAttributes() { var f = ExtraFields; - if (!(f.__customAttributes_DONT_USE is null)) + if (f.__customAttributes_DONT_USE is not null) return; var info = CreateCustomAttributes(); var newSAs = ReadOnlyCollectionHelpers.Create(info.sas); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodRef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodRef.cs index 57479c177a..f45b2bfad9 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodRef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodRef.cs @@ -39,22 +39,22 @@ abstract class DmdMethodRef : DmdMethodInfoBase { DmdMethodDef ResolvedMethod => GetResolvedMethod(throwOnError: true)!; DmdMethodDef? GetResolvedMethod(bool throwOnError) { - if (!(__resolvedMethod_DONT_USE is null)) + if (__resolvedMethod_DONT_USE is not null) return __resolvedMethod_DONT_USE; DmdMethodDef? newResolvedMethod = null; var declType = declaringTypeRef.Resolve(throwOnError); - if (!(declType is null)) { + if (declType is not null) { var nonGenericInstDeclType = declType.IsGenericType ? declType.GetGenericTypeDefinition() : declType; var nonGenericInstDeclTypeMethod = nonGenericInstDeclType?.GetMethod(Name, rawMethodSignature, throwOnError: false) as DmdMethodDef; - if (!(nonGenericInstDeclTypeMethod is null)) { + if (nonGenericInstDeclTypeMethod is not null) { newResolvedMethod = (object?)nonGenericInstDeclTypeMethod.DeclaringType == declType ? nonGenericInstDeclTypeMethod : declType.GetMethod(nonGenericInstDeclTypeMethod.Module, nonGenericInstDeclTypeMethod.MetadataToken) as DmdMethodDef; - Debug2.Assert(!(newResolvedMethod is null)); + Debug2.Assert(newResolvedMethod is not null); } } - if (!(newResolvedMethod is null)) { + if (newResolvedMethod is not null) { Interlocked.CompareExchange(ref __resolvedMethod_DONT_USE, newResolvedMethod, null); Debug.Assert(DmdMemberInfoEqualityComparer.DefaultMember.Equals(__resolvedMethod_DONT_USE!.ReflectedType, declaringTypeRef)); return __resolvedMethod_DONT_USE; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodSpec.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodSpec.cs index 1c7444ae2a..1f8af4a597 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodSpec.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodSpec.cs @@ -75,7 +75,7 @@ public override ReadOnlyCollection GetParameters() { } void InitializeParameters() { - if (!(__parameters_DONT_USE is null)) + if (__parameters_DONT_USE is not null) return; var newRP = new DmdCreatedParameterInfo(this, genericMethodDefinition.ReturnParameter, methodSignature.ReturnType); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodSpecRef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodSpecRef.cs index fead17fdc4..0ce12bbace 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodSpecRef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdMethodSpecRef.cs @@ -47,13 +47,13 @@ public DmdMethodSpecRef(DmdMethodRef genericMethodRef, IList genericArg } public override DmdMethodInfo? Resolve(bool throwOnError) { - if (!(__resolvedMethod_DONT_USE is null)) + if (__resolvedMethod_DONT_USE is not null) return __resolvedMethod_DONT_USE; var genericMethodDef = (DmdMethodDef?)genericMethodRef.Resolve(throwOnError); - if (!(genericMethodDef is null)) { + if (genericMethodDef is not null) { var newResolvedMethod = (DmdMethodSpec)AppDomain.MakeGenericMethod(genericMethodDef, genericArguments, DmdMakeTypeOptions.None); - if (!(newResolvedMethod is null)) { + if (newResolvedMethod is not null) { Interlocked.CompareExchange(ref __resolvedMethod_DONT_USE, newResolvedMethod, null); return __resolvedMethod_DONT_USE!; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdModuleImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdModuleImpl.cs index 98e9318fa2..ef71047dd3 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdModuleImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdModuleImpl.cs @@ -84,7 +84,7 @@ public TypeDefResolver(DmdModuleImpl module, bool ignoreCase) { DmdModuleImpl? targetModule = module; DmdAssemblyImpl? targetAssembly = targetModule.assembly; - if (!(assemblyName is null) && !module.assembly.AppDomainImpl.AssemblyNameEqualityComparer.Equals(targetAssembly.GetName(), assemblyName)) { + if (assemblyName is not null && !module.assembly.AppDomainImpl.AssemblyNameEqualityComparer.Equals(targetAssembly.GetName(), assemblyName)) { targetAssembly = (DmdAssemblyImpl?)targetAssembly.AppDomain.GetAssembly(assemblyName); targetModule = (DmdModuleImpl?)targetAssembly?.ManifestModule; if (targetModule is null) @@ -117,7 +117,7 @@ public TypeDefResolver(DmdModuleImpl module, bool ignoreCase) { var resolver = new TypeDefResolver(this, (options & DmdGetTypeOptions.IgnoreCase) != 0); var type = DmdTypeNameParser.Parse(resolver, typeName); - if (!(type is null)) + if (type is not null) return AppDomain.Intern(type, DmdMakeTypeOptions.NoResolve); if ((options & DmdGetTypeOptions.ThrowOnError) != 0) @@ -128,7 +128,7 @@ public TypeDefResolver(DmdModuleImpl module, bool ignoreCase) { DmdTypeDef? GetType(DmdTypeRef typeRef, bool ignoreCase) => assembly.AppDomainImpl.TryLookup(this, typeRef, ignoreCase); public override ReadOnlyCollection GetCustomAttributesData() { - if (!(customAttributes is null)) + if (customAttributes is not null) return customAttributes; var cas = metadataReader.ReadCustomAttributes(0x00000001); var newCAs = CustomAttributesHelper.AddPseudoCustomAttributes(this, cas); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdParameterDef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdParameterDef.cs index f4d06fce5f..929645f22c 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdParameterDef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdParameterDef.cs @@ -72,7 +72,7 @@ void InitializeDefaultValue() { protected abstract (object? rawDefaultValue, bool hasDefaultValue) CreateDefaultValue(); public sealed override ReadOnlyCollection GetCustomAttributesData() { - if (!(__customAttributes_DONT_USE is null)) + if (__customAttributes_DONT_USE is not null) return __customAttributes_DONT_USE; var info = CreateCustomAttributes(); var newCAs = CustomAttributesHelper.AddPseudoCustomAttributes(this, info.cas, info.marshalType); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdPointerType.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdPointerType.cs index e2a72db199..ee57fbad21 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdPointerType.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdPointerType.cs @@ -54,7 +54,7 @@ public DmdPointerType(DmdTypeBase elementType, IList? customM if (!IsMetadataReference) return this; var newElementType = elementType.ResolveNoThrow(); - if (!(newElementType is null)) + if (newElementType is not null) return AppDomain.MakePointerType(newElementType, GetCustomModifiers()); return null; } @@ -64,7 +64,7 @@ public DmdPointerType(DmdTypeBase elementType, IList? customM if (IsFullyResolved) return this; var et = elementType.FullResolve(); - if (!(et is null)) + if (et is not null) return (DmdTypeBase)AppDomain.MakePointerType(et, GetCustomModifiers()); return null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdPropertyDef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdPropertyDef.cs index b5f373f02f..f901510de0 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdPropertyDef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdPropertyDef.cs @@ -47,14 +47,14 @@ public sealed override DmdMethodInfo[] GetAccessors(DmdGetAccessorOptions option InitializePropertyMethods(); var list = new List(); var accessor = AccessorUtils.FilterAccessor(options, f.__getMethod_DONT_USE!); - if (!(accessor is null)) + if (accessor is not null) list.Add(accessor); accessor = AccessorUtils.FilterAccessor(options, f.__setMethod_DONT_USE!); - if (!(accessor is null)) + if (accessor is not null) list.Add(accessor); foreach (var method in f.__otherMethods_DONT_USE!) { accessor = AccessorUtils.FilterAccessor(options, method); - if (!(accessor is null)) + if (accessor is not null) list.Add(accessor); } return list.ToArray(); @@ -76,7 +76,7 @@ public sealed override DmdMethodInfo[] GetAccessors(DmdGetAccessorOptions option void InitializePropertyMethods() { var f = ExtraFields; - if (!(f.__otherMethods_DONT_USE is null)) + if (f.__otherMethods_DONT_USE is not null) return; GetMethods(out var getMethod, out var setMethod, out var otherMethods); lock (LockObject) { @@ -98,7 +98,7 @@ public sealed override ReadOnlyCollection GetIndexParameters() void InitializeIndexParameters() { var f = ExtraFields; - if (!(f.__indexParameters_DONT_USE is null)) + if (f.__indexParameters_DONT_USE is not null) return; var info = CreateIndexParameters(); Interlocked.CompareExchange(ref f.__indexParameters_DONT_USE, ReadOnlyCollectionHelpers.Create(info), null); @@ -132,7 +132,7 @@ DmdParameterInfo[] CreateIndexParameters() { public sealed override ReadOnlyCollection GetCustomAttributesData() { var f = ExtraFields; - if (!(f.__customAttributes_DONT_USE is null)) + if (f.__customAttributes_DONT_USE is not null) return f.__customAttributes_DONT_USE; var info = CreateCustomAttributes(); var newCAs = CustomAttributesHelper.AddPseudoCustomAttributes(this, info); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdSZArrayType.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdSZArrayType.cs index 38f8e8baff..8b75bee0b0 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdSZArrayType.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdSZArrayType.cs @@ -57,7 +57,7 @@ public DmdSZArrayType(DmdTypeBase elementType, IList? customM if (!IsMetadataReference) return this; var newElementType = elementType.ResolveNoThrow(); - if (!(newElementType is null)) + if (newElementType is not null) return AppDomain.MakeArrayType(newElementType, GetCustomModifiers()); return null; } @@ -67,7 +67,7 @@ public DmdSZArrayType(DmdTypeBase elementType, IList? customM if (IsFullyResolved) return this; var et = elementType.FullResolve(); - if (!(et is null)) + if (et is not null) return (DmdTypeBase)AppDomain.MakeArrayType(et, GetCustomModifiers()); return null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeBase.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeBase.cs index 4912c15d0a..b4e197d112 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeBase.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeBase.cs @@ -34,7 +34,7 @@ abstract class DmdTypeBase : DmdType { protected DmdTypeBase(IList? customModifiers) => this.customModifiers = ReadOnlyCollectionHelpers.Create(customModifiers); protected IList? VerifyCustomModifiers(IList? customModifiers) { - if (!(customModifiers is null)) { + if (customModifiers is not null) { for (int i = 0; i < customModifiers.Count; i++) { if (customModifiers[i].Type.AppDomain != AppDomain) throw new ArgumentException(); @@ -70,7 +70,7 @@ protected DmdTypeBase(IList? customModifiers) => public override DmdMethodBase? DeclaringMethod => throw new InvalidOperationException(); public sealed override DmdAssembly Assembly => Module.Assembly; - public sealed override bool HasElementType => !(GetElementType() is null); + public sealed override bool HasElementType => GetElementType() is not null; public override DmdGenericParameterAttributes GenericParameterAttributes => throw new InvalidOperationException(); public override bool IsGenericType => false; public override bool IsGenericTypeDefinition => false; @@ -140,12 +140,12 @@ public sealed override DmdConstructorInfo[] GetConstructors(DmdBindingFlags bind continue; if (!DmdMemberInfoComparer.IsMatch(method, bindingAttr, callConvention)) continue; - if (!(types is null) && DmdMemberInfoComparer.IsMatch(method, types)) + if (types is not null && DmdMemberInfoComparer.IsMatch(method, types)) return method; foundMethod = method; counter++; } - if (!(foundMethod is null) && types is null) { + if (foundMethod is not null && types is null) { if (counter == 1) return foundMethod; throw new System.Reflection.AmbiguousMatchException(); @@ -219,16 +219,16 @@ public sealed override DmdEventInfo[] GetEvents(DmdBindingFlags bindingAttr) { continue; if (!DmdMemberInfoComparer.IsMatch(property, bindingAttr)) continue; - if (!(returnType is null) && !DmdMemberInfoComparer.IsMatch(property, returnType)) + if (returnType is not null && !DmdMemberInfoComparer.IsMatch(property, returnType)) continue; - if (!(types is null) && !DmdMemberInfoComparer.IsMatch(property, types)) + if (types is not null && !DmdMemberInfoComparer.IsMatch(property, types)) continue; - if (!(returnType is null) && !(types is null)) + if (returnType is not null && types is not null) return property; foundProperty = property; counter++; } - if (!(foundProperty is null) && types is null) { + if (foundProperty is not null && types is null) { if (counter == 1) return foundProperty; if (returnType is null) @@ -371,7 +371,7 @@ public sealed override DmdType[] GetNestedTypes(DmdBindingFlags bindingAttr) { public sealed override ReadOnlyCollection GetInterfaces() { var f = ExtraFields; - if (!(f.__implementedInterfaces_DONT_USE is null)) + if (f.__implementedInterfaces_DONT_USE is not null) return f.__implementedInterfaces_DONT_USE; var implIfaces = CreateInterfaces(this); @@ -467,7 +467,7 @@ public sealed override ReadOnlyCollection GetCustomAttri } void InitializeCustomAttributes(ExtraFieldsImpl f) { - if (!(f.__customAttributes_DONT_USE is null)) + if (f.__customAttributes_DONT_USE is not null) return; var info = CreateCustomAttributes(); var newSAs = ReadOnlyCollectionHelpers.Create(info.sas); @@ -501,7 +501,7 @@ public sealed override ReadOnlyCollection GetSecurityAtt public sealed override ReadOnlyCollection DeclaredFields { get { var f = ExtraFields; - if (!(f.__declaredFields_DONT_USE is null)) + if (f.__declaredFields_DONT_USE is not null) return f.__declaredFields_DONT_USE; var res = CreateDeclaredFields(this); Interlocked.CompareExchange(ref f.__declaredFields_DONT_USE, ReadOnlyCollectionHelpers.Create(res), null); @@ -512,7 +512,7 @@ public sealed override ReadOnlyCollection DeclaredFields { public sealed override ReadOnlyCollection DeclaredMethods { get { var f = ExtraFields; - if (!(f.__declaredMethods_DONT_USE is null)) + if (f.__declaredMethods_DONT_USE is not null) return f.__declaredMethods_DONT_USE; var res = CreateDeclaredMethods(this); Interlocked.CompareExchange(ref f.__declaredMethods_DONT_USE, ReadOnlyCollectionHelpers.Create(res), null); @@ -523,7 +523,7 @@ public sealed override ReadOnlyCollection DeclaredMethods { public sealed override ReadOnlyCollection DeclaredProperties { get { var f = ExtraFields; - if (!(f.__declaredProperties_DONT_USE is null)) + if (f.__declaredProperties_DONT_USE is not null) return f.__declaredProperties_DONT_USE; var res = CreateDeclaredProperties(this); Interlocked.CompareExchange(ref f.__declaredProperties_DONT_USE, ReadOnlyCollectionHelpers.Create(res), null); @@ -534,7 +534,7 @@ public sealed override ReadOnlyCollection DeclaredProperties { public sealed override ReadOnlyCollection DeclaredEvents { get { var f = ExtraFields; - if (!(f.__declaredEvents_DONT_USE is null)) + if (f.__declaredEvents_DONT_USE is not null) return f.__declaredEvents_DONT_USE; var res = CreateDeclaredEvents(this); Interlocked.CompareExchange(ref f.__declaredEvents_DONT_USE, ReadOnlyCollectionHelpers.Create(res), null); @@ -549,7 +549,7 @@ protected ReadOnlyCollection NestedTypesCore { for (;;) { var f = ExtraFields; var nestedTypes = f.__nestedTypes_DONT_USE; - if (!(nestedTypes is null)) + if (nestedTypes is not null) return nestedTypes; var res = CreateNestedTypes(); Interlocked.CompareExchange(ref f.__nestedTypes_DONT_USE, ReadOnlyCollectionHelpers.Create(res), null); @@ -583,7 +583,7 @@ internal void DynamicType_InvalidateCachedMembers() { internal ReadOnlyCollection DeclaredInterfaces { get { var f = ExtraFields; - if (!(f.__declaredInterfaces_DONT_USE is null)) + if (f.__declaredInterfaces_DONT_USE is not null) return f.__declaredInterfaces_DONT_USE; var res = ReadDeclaredInterfaces(); Interlocked.CompareExchange(ref f.__declaredInterfaces_DONT_USE, ReadOnlyCollectionHelpers.Create(res), null); @@ -596,7 +596,7 @@ ExtraFieldsImpl ExtraFields { // We loop here because the field could be cleared if it's a dynamic type for (;;) { var f = __extraFields_DONT_USE; - if (!(f is null)) + if (f is not null) return f; Interlocked.CompareExchange(ref __extraFields_DONT_USE, new ExtraFieldsImpl(), null); } @@ -661,7 +661,7 @@ public MemberInfo GetNext(ref int index) { protected void InitializeAllCore() { lock (lockObj) { int index = members.Count; - while (!(GetNext(ref index).Member is null)) + while (GetNext(ref index).Member is not null) index = members.Count; } } @@ -920,7 +920,7 @@ bool IsAccessible(DmdEventInfo @event) { DmdFieldReader BaseFieldsReader { get { var f = ExtraFields; - if (!(f.__baseFields_DONT_USE is null)) + if (f.__baseFields_DONT_USE is not null) return f.__baseFields_DONT_USE; Interlocked.CompareExchange(ref f.__baseFields_DONT_USE, new DmdFieldReader(this), null); return f.__baseFields_DONT_USE!; @@ -930,7 +930,7 @@ DmdFieldReader BaseFieldsReader { DmdMethodReader BaseMethodsReader { get { var f = ExtraFields; - if (!(f.__baseMethods_DONT_USE is null)) + if (f.__baseMethods_DONT_USE is not null) return f.__baseMethods_DONT_USE; Interlocked.CompareExchange(ref f.__baseMethods_DONT_USE, new DmdMethodReader(this), null); return f.__baseMethods_DONT_USE!; @@ -940,7 +940,7 @@ DmdMethodReader BaseMethodsReader { DmdPropertyReader BasePropertiesReader { get { var f = ExtraFields; - if (!(f.__baseProperties_DONT_USE is null)) + if (f.__baseProperties_DONT_USE is not null) return f.__baseProperties_DONT_USE; Interlocked.CompareExchange(ref f.__baseProperties_DONT_USE, new DmdPropertyReader(this), null); return f.__baseProperties_DONT_USE!; @@ -950,7 +950,7 @@ DmdPropertyReader BasePropertiesReader { DmdEventReader BaseEventsReader { get { var f = ExtraFields; - if (!(f.__baseEvents_DONT_USE is null)) + if (f.__baseEvents_DONT_USE is not null) return f.__baseEvents_DONT_USE; Interlocked.CompareExchange(ref f.__baseEvents_DONT_USE, new DmdEventReader(this), null); return f.__baseEvents_DONT_USE!; @@ -1155,7 +1155,7 @@ IEnumerable GetEvents(GetMemberOptions options) { continue; if (sig.GenericParameterCount != genericParameterCount) continue; - if (!(returnType is null)) { + if (returnType is not null) { if (!DmdMemberInfoEqualityComparer.DefaultMember.Equals(returnType, sig.ReturnType)) continue; } @@ -1214,7 +1214,7 @@ IEnumerable GetEvents(GetMemberOptions options) { continue; if (sig.GenericParameterCount != genericParameterCount) continue; - if (!(returnType is null)) { + if (returnType is not null) { if (!DmdMemberInfoEqualityComparer.DefaultMember.Equals(returnType, sig.ReturnType)) continue; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeDef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeDef.cs index 33e2416cb9..cc3bc22084 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeDef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeDef.cs @@ -173,7 +173,7 @@ protected override ReadOnlyCollection GetGenericArgumentsCore() { // We loop here because the field could be cleared if it's a dynamic type for (;;) { var gps = f.__genericParameters_DONT_USE; - if (!(gps is null)) + if (gps is not null) return gps; var res = CreateGenericParameters(); Interlocked.CompareExchange(ref f.__genericParameters_DONT_USE, ReadOnlyCollectionHelpers.Create(res), null); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeNameParser.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeNameParser.cs index d699189607..30b449152a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeNameParser.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeNameParser.cs @@ -216,7 +216,7 @@ DmdParsedTypeRef CreateTypeRefNoAssembly(string fullName, DmdParsedTypeRef? decl IDmdAssemblyName FindAssemblyRef(DmdParsedTypeRef? nonNestedTypeRef) { IDmdAssemblyName? asmRef = null; - if (!(nonNestedTypeRef is null)) + if (nonNestedTypeRef is not null) asmRef = FindAssemblyRefCore(nonNestedTypeRef); return asmRef ?? ownerModule!.Assembly.GetName(); } @@ -224,13 +224,13 @@ IDmdAssemblyName FindAssemblyRef(DmdParsedTypeRef? nonNestedTypeRef) { IDmdAssemblyName FindAssemblyRefCore(DmdParsedTypeRef nonNestedTypeRef) { var modAsm = (DmdAssemblyImpl)ownerModule!.Assembly; var type = modAsm.GetType(nonNestedTypeRef, ignoreCase: false); - if (!(type is null)) + if (type is not null) return modAsm.GetName(); var corLibAsm = (DmdAssemblyImpl?)ownerModule.AppDomain.CorLib; - if (!(corLibAsm is null)) { + if (corLibAsm is not null) { type = corLibAsm.GetType(nonNestedTypeRef, ignoreCase: false); - if (!(type is null)) + if (type is not null) return corLibAsm.GetName(); } @@ -338,7 +338,7 @@ DmdType ReadType(bool readAssemblyReference) { IDmdAssemblyName? asmRef; if (typeDefResolver is null) { - Debug2.Assert(!(ownerModule is null)); + Debug2.Assert(ownerModule is not null); var typeRef = CreateTypeRef(typeNames); var nonNestedTypeRef = (DmdParsedTypeRef)DmdTypeUtilities.GetNonNestedType(typeRef)!; if (readAssemblyReference) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeRef.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeRef.cs index 1043e930fe..4f070ffce5 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeRef.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/DmdTypeRef.cs @@ -67,11 +67,11 @@ public virtual DmdTypeRef? DeclaringTypeRef { internal DmdTypeDef ResolvedType => GetResolvedType(throwOnError: true)!; internal DmdTypeDef? GetResolvedType(bool throwOnError) { - if (!(__resolvedType_DONT_USE is null)) + if (__resolvedType_DONT_USE is not null) return __resolvedType_DONT_USE; var appDomain = (DmdAppDomainImpl)ownerModule.AppDomain; var type = appDomain.Resolve(this, throwOnError, ignoreCase: false); - if (!(type is null) && GetCustomModifiers().Count != 0) + if (type is not null && GetCustomModifiers().Count != 0) type = (DmdTypeDef)appDomain.Intern(type.WithCustomModifiers(GetCustomModifiers()), DmdMakeTypeOptions.None); Interlocked.CompareExchange(ref __resolvedType_DONT_USE, type, null); return __resolvedType_DONT_USE; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/MD/DmdEcma335MetadataReader.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/MD/DmdEcma335MetadataReader.cs index b93c94041a..ac0c243ddd 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/MD/DmdEcma335MetadataReader.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/MD/DmdEcma335MetadataReader.cs @@ -134,7 +134,7 @@ DmdFieldDefMD CreateFieldDefCore(uint rid, DmdType declaringType, DmdType reflec internal DmdType ReadFieldType(uint signature, IList genericTypeArguments) { lock (signatureLock) { if (fieldTypeCache.TryGetValue(signature, out var fieldType)) { - if (!(fieldType is null)) + if (fieldType is not null) return fieldType; var info = ReadFieldTypeCore(signature, genericTypeArguments); Debug.Assert(info.containedGenericParams); @@ -183,7 +183,7 @@ DmdMethodBase CreateMethodDefCore(uint rid, DmdType declaringType, DmdType refle internal DmdMethodSignature ReadMethodSignature(uint signature, IList? genericTypeArguments, IList? genericMethodArguments, bool isProperty) { lock (signatureLock) { if (methodSignatureCache.TryGetValue(signature, out var methodSignature)) { - if (!(methodSignature is null)) + if (methodSignature is not null) return methodSignature; var info = ReadMethodSignatureCore(signature, genericTypeArguments, genericMethodArguments, isProperty); Debug.Assert(info.containedGenericParams); @@ -303,12 +303,12 @@ DmdPropertyDef CreatePropertyDefCore(uint rid, DmdType declaringType, DmdType re if ((classToken >> 24) == 0x1B) containedGenericParams = true; - if (!(info.fieldType is null)) { + if (info.fieldType is not null) { var fieldRef = new DmdFieldRef(reflectedTypeRef, name, rawInfo.fieldType!, info.fieldType); return (fieldRef, containedGenericParams); } else { - Debug2.Assert(!(info.methodSignature is null)); + Debug2.Assert(info.methodSignature is not null); if (name == DmdConstructorInfo.ConstructorName || name == DmdConstructorInfo.TypeConstructorName) { var ctorRef = new DmdConstructorRef(reflectedTypeRef, name, rawInfo.methodSignature!, info.methodSignature); return (ctorRef, containedGenericParams); @@ -347,7 +347,7 @@ DmdType GetMemberRefParent(uint classToken, IList? genericTypeArguments (DmdType? fieldType, DmdMethodSignature? methodSignature, bool containedGenericParams) ReadMethodSignatureOrFieldType(uint signature, IList? genericTypeArguments, IList? genericMethodArguments) { lock (signatureLock) { if (methodSignatureCache.TryGetValue(signature, out var methodSignature)) { - if (!(methodSignature is null)) + if (methodSignature is not null) return (null, methodSignature, false); var info = ReadMethodSignatureCore(signature, genericTypeArguments, genericMethodArguments, isProperty: false); if (info.methodSignature is null) @@ -356,7 +356,7 @@ DmdType GetMemberRefParent(uint classToken, IList? genericTypeArguments return (null, info.methodSignature, info.containedGenericParams); } else if (fieldTypeCache.TryGetValue(signature, out var fieldType)) { - if (!(fieldType is null)) + if (fieldType is not null) return (fieldType, null, false); var info = ReadFieldTypeCore(signature, genericTypeArguments); if (info.fieldType is null) @@ -367,7 +367,7 @@ DmdType GetMemberRefParent(uint classToken, IList? genericTypeArguments else { var reader = BlobStream.CreateReader(signature); var info = DmdSignatureReader.ReadMethodSignatureOrFieldType(module, new DmdDataStreamImpl(ref reader), genericTypeArguments, genericMethodArguments, resolveTypes); - if (!(info.fieldType is null)) { + if (info.fieldType is not null) { if (info.containedGenericParams) fieldTypeCache.Add(signature, null); else @@ -375,7 +375,7 @@ DmdType GetMemberRefParent(uint classToken, IList? genericTypeArguments return (info.fieldType, null, info.containedGenericParams); } else { - Debug2.Assert(!(info.methodSignature is null)); + Debug2.Assert(info.methodSignature is not null); if (info.containedGenericParams) methodSignatureCache.Add(signature, null); else @@ -397,7 +397,7 @@ DmdType GetMemberRefParent(uint classToken, IList? genericTypeArguments var reader = Metadata.PEImage.CreateReader(); reader.Position = (uint)Metadata.PEImage.ToFileOffset((RVA)row.RVA); var body = DmdMethodBodyReader.Create(this, new DmdDataStreamImpl(ref reader), genericTypeArguments, genericMethodArguments); - Debug2.Assert(!(body is null)); + Debug2.Assert(body is not null); return body; } @@ -652,7 +652,7 @@ DmdCustomAttributeData[] ReadSecurityAttributesCore(Table table, uint rid) { res.Add((cas, action)); } } - if (!(firstCas is null)) + if (firstCas is not null) return firstCas; if (res is null) return Array.Empty(); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/MD/DmdGenericParameterTypeMD.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/MD/DmdGenericParameterTypeMD.cs index 6edc2d1309..acd6fcbe2d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/MD/DmdGenericParameterTypeMD.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/MD/DmdGenericParameterTypeMD.cs @@ -42,7 +42,7 @@ public DmdGenericParameterTypeMD(DmdEcma335MetadataReader reader, uint rid, DmdM IList genericTypeArguments; IList? genericMethodArguments; - if (!(DeclaringMethod is null)) { + if (DeclaringMethod is not null) { genericTypeArguments = DeclaringMethod.DeclaringType!.GetGenericArguments(); genericMethodArguments = DeclaringMethod.GetGenericArguments(); } @@ -67,7 +67,7 @@ public DmdGenericParameterTypeMD(DmdEcma335MetadataReader reader, uint rid, DmdM } DmdGenericParameterTypeMD Clone(IList? customModifiers) => - !(DeclaringMethod is null) ? + DeclaringMethod is not null ? new DmdGenericParameterTypeMD(reader, Rid, DeclaringMethod, MetadataName, GenericParameterPosition, GenericParameterAttributes, customModifiers) : new DmdGenericParameterTypeMD(reader, Rid, (DmdTypeBase)DeclaringType!, MetadataName, GenericParameterPosition, GenericParameterAttributes, customModifiers); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/ReflectionTests.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/ReflectionTests.cs index 9319ea1674..382e699755 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/ReflectionTests.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Metadata/Impl/ReflectionTests.cs @@ -370,7 +370,7 @@ static void Test(DmdAssembly asm1, Assembly asm2) { catch (ArgumentException) { continue; } - Verify((!(t1 is null)) == (!(t2 is null))); + Verify((t1 is not null) == (t2 is not null)); if (t1 is null) break; TestTypes(t1, t2); @@ -481,7 +481,7 @@ static void Test(IList t1, Type[] t2) { return; for (int i = 0; i < t2.Length; i++) { var t2t = t2[i]; - if (!(t2t is null)) + if (t2t is not null) SimpleTest(t1[i], t2t); } } @@ -506,15 +506,15 @@ static void TestMember(DmdMemberInfo m1, MemberInfo m2) { Verify(m1.Name == m2.Name); bool isGlobal = (m2.MemberType == MemberTypes.Field || m2.MemberType == MemberTypes.Method) && m2.DeclaringType is null; if (isGlobal) { - Verify((!(m1.DeclaringType is null)) == (m2.DeclaringType is null)); - Verify((!(m1.ReflectedType is null)) == (m2.ReflectedType is null)); + Verify((m1.DeclaringType is not null) == (m2.DeclaringType is null)); + Verify((m1.ReflectedType is not null) == (m2.ReflectedType is null)); } else { - Verify((!(m1.DeclaringType is null)) == (!(m2.DeclaringType is null))); - if (!(m1.DeclaringType is null)) + Verify((m1.DeclaringType is not null) == (m2.DeclaringType is not null)); + if (m1.DeclaringType is not null) SimpleTest(m1.DeclaringType, m2.DeclaringType); - Verify((!(m1.ReflectedType is null)) == (!(m2.ReflectedType is null))); - if (!(m1.ReflectedType is null)) + Verify((m1.ReflectedType is not null) == (m2.ReflectedType is not null)); + if (m1.ReflectedType is not null) SimpleTest(m1.ReflectedType, m2.ReflectedType); } Verify(m1.MetadataToken == m2.MetadataToken); @@ -545,8 +545,8 @@ static void TestSameException(Func func1, Func func2, Func= 2) { if (tia.ConstructorArguments[0].ArgumentType != td.AppDomain.System_String) return null; @@ -88,9 +88,9 @@ public Info(string? scope, string? identifier) { } static bool CheckEquivalent(DmdType td) { - Debug2.Assert(!(td is null)); + Debug2.Assert(td is not null); - for (int i = 0; !(td is null) && i < 1000; i++) { + for (int i = 0; td is not null && i < 1000; i++) { if (i != 0) { var info = GetInfo(td); if (info is null) @@ -120,7 +120,7 @@ static bool CheckEquivalent(DmdType td) { } public static bool IsTypeDefEquivalent(DmdType td) { - Debug2.Assert(!(td is null)); + Debug2.Assert(td is not null); if (GetInfo(td) is null) return false; return CheckEquivalent(td); @@ -132,11 +132,11 @@ public static bool Equivalent(DmdType? td1, DmdType? td2) { var info1 = GetInfo(td1); if (info1 is null) return false; - Debug2.Assert(!(td1 is null)); + Debug2.Assert(td1 is not null); var info2 = GetInfo(td2); if (info2 is null) return false; - Debug2.Assert(!(td2 is null)); + Debug2.Assert(td2 is not null); if (!CheckEquivalent(td1) || !CheckEquivalent(td2)) return false; if (!info1.Value.Equals(info2.Value)) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/AntiAntiDebug/DisableAntiAntiDebugCode.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/AntiAntiDebug/DisableAntiAntiDebugCode.cs index 08fbf76234..2ada5d37bb 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/AntiAntiDebug/DisableAntiAntiDebugCode.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/AntiAntiDebug/DisableAntiAntiDebugCode.cs @@ -30,12 +30,12 @@ abstract class DisableAntiAntiDebugCode : IDbgNativeFunctionHook { static bool TryGetInternalRuntime(DbgProcess process, [NotNullWhen(true)] out DbgMonoDebugInternalRuntime? runtime) { runtime = null; var dbgRuntime = process.Runtimes.FirstOrDefault(); - Debug2.Assert(!(dbgRuntime is null)); + Debug2.Assert(dbgRuntime is not null); if (dbgRuntime is null) return false; runtime = dbgRuntime.InternalRuntime as DbgMonoDebugInternalRuntime; - return !(runtime is null); + return runtime is not null; } public bool IsEnabled(DbgNativeFunctionHookContext context) => TryGetInternalRuntime(context.Process, out _); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/CallStack/DbgEngineStackWalkerImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/CallStack/DbgEngineStackWalkerImpl.cs index 9e289f0f26..48ab68d44c 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/CallStack/DbgEngineStackWalkerImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/CallStack/DbgEngineStackWalkerImpl.cs @@ -99,7 +99,7 @@ DbgEngineStackFrame CreateEngineStackFrame(MDS.StackFrame monoFrame, int frameIn } else { var module = engine.TryGetModule(method.DeclaringType.Module); - if (!(module is null)) + if (module is not null) return new ILDbgEngineStackFrame(engine, module, monoThread, monoFrame, frameIndex, dbgDotNetCodeLocationFactory); Debug.Fail("Creating an error stack frame"); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/AttachToProcess/ProcessUtils.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/AttachToProcess/ProcessUtils.cs index 1bb6a78268..a3f7f6fcfb 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/AttachToProcess/ProcessUtils.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/AttachToProcess/ProcessUtils.cs @@ -27,7 +27,7 @@ public static bool IsValidProcess(AttachProgramOptionsProviderContext context, i if (context.ProcessIds.Length != 0 && Array.IndexOf(context.ProcessIds, pid) < 0) return false; - if (!(context.IsValidProcess is null)) { + if (context.IsValidProcess is not null) { Process? processToDispose = null; try { if (process is null) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/AttachToProcess/UnityDataReceiver.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/AttachToProcess/UnityDataReceiver.cs index 53212c6dac..49bed906d7 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/AttachToProcess/UnityDataReceiver.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/AttachToProcess/UnityDataReceiver.cs @@ -123,7 +123,7 @@ public void Start() { catch (ObjectDisposedException) { } - if (!(data is null)) + if (data is not null) return data; conn.Dispose(); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/DebugProgram/MonoStartDebuggingOptionsPageBase.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/DebugProgram/MonoStartDebuggingOptionsPageBase.cs index 291fcef6bb..e50e0ae174 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/DebugProgram/MonoStartDebuggingOptionsPageBase.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Dialogs/DebugProgram/MonoStartDebuggingOptionsPageBase.cs @@ -39,7 +39,7 @@ public string Filename { OnPropertyChanged(nameof(Filename)); UpdateIsValid(); var path = GetPath(filename); - if (!(path is null)) + if (path is not null) WorkingDirectory = path; } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Breakpoints.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Breakpoints.cs index 99f7ad55db..a0780e8708 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Breakpoints.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Breakpoints.cs @@ -49,7 +49,7 @@ public BoundBreakpointData(DbgEngineImpl engine, ModuleId module) { bool SendCodeBreakpointHitMessage_MonoDebug(BreakpointEventRequest breakpoint, DbgThread? thread) { debuggerThread.VerifyAccess(); if (breakpoint.Tag is BoundBreakpointData bpData) { - if (!(bpData is null)) + if (bpData is not null) SendMessage(new DbgMessageBreakpoint(bpData.EngineBoundCodeBreakpoint!.BoundCodeBreakpoint, thread, GetMessageFlags())); else SendMessage(new DbgMessageBreak(thread, GetMessageFlags())); @@ -169,7 +169,7 @@ void EnableBreakpoints(ModuleMirror monoModule, DbgModule module, List OnFuncEvalComplete(a, context), monoThread, context.FuncEvalTimeout, suspendOtherThreads: (context.Options & DbgEvaluationContextOptions.RunAllThreads) == 0, cancellationToken: cancellationToken); FuncEval CreateFuncEval2(DbgEvaluationContext? contextOpt, ThreadMirror monoThread, CancellationToken cancellationToken) { - if (!(contextOpt is null)) + if (contextOpt is not null) return CreateFuncEval(contextOpt, monoThread, cancellationToken); return funcEvalFactory.CreateFuncEval(a => OnFuncEvalComplete(a), monoThread, DbgLanguage.DefaultFuncEvalTimeout, suspendOtherThreads: true, cancellationToken: cancellationToken); } @@ -230,7 +230,7 @@ internal DbgDotNetValueResult FuncEvalCall_MonoDebug(DbgEvaluationInfo evalInfo, debuggerThread.VerifyAccess(); evalInfo.CancellationToken.ThrowIfCancellationRequested(); var tmp = CheckFuncEval(evalInfo.Context); - if (!(tmp is null)) + if (tmp is not null) return tmp.Value; return FuncEvalCallCore_MonoDebug(evalInfo.Context, evalInfo.Frame, evalInfo.Frame.Thread, method, obj, arguments, invokeOptions, newObj, evalInfo.CancellationToken); } @@ -252,7 +252,7 @@ DbgDotNetValueResult FuncEvalCallCore_MonoDebug(DbgEvaluationContext? contextOpt if (res.IsNormalResult) { try { var error = objImpl.ValueLocation.Store(((DbgDotNetValueImpl)res.Value!).Value); - if (!(error is null)) { + if (error is not null) { res.Value?.Dispose(); return DbgDotNetValueResult.CreateError(error); } @@ -312,7 +312,7 @@ DbgDotNetValueResult FuncEvalCallCoreReal_MonoDebug(DbgEvaluationContext? contex if (method is DmdMethodInfo m) declType = m.GetBaseDefinition().DeclaringType!; var val = converter.Convert(obj, declType, out origType); - if (!(val.ErrorMessage is null)) + if (val.ErrorMessage is not null) return DbgDotNetValueResult.CreateError(val.ErrorMessage); // Don't box it if it's a value type and it implements the method, eg. 1.ToString() fails without this check if (origType.IsValueType && method.DeclaringType == origType) { @@ -327,7 +327,7 @@ DbgDotNetValueResult FuncEvalCallCoreReal_MonoDebug(DbgEvaluationContext? contex funcEvalOptions |= FuncEvalOptions.ReturnOutThis; } else if (newObj && method.ReflectedType!.IsValueType) { - if (!(contextOpt is null) && !(frameOpt is null)) { + if (contextOpt is not null && frameOpt is not null) { //TODO: The Mono fork Unity uses doesn't support this, it returns nothing var evalInfo = new DbgEvaluationInfo(contextOpt, frameOpt, cancellationToken); hiddenThisValue = CreateValueType(evalInfo, method.ReflectedType, 0); @@ -344,7 +344,7 @@ DbgDotNetValueResult FuncEvalCallCoreReal_MonoDebug(DbgEvaluationContext? contex for (int i = 0; i < arguments.Length; i++) { var paramType = paramTypes[i]; var val = converter.Convert(arguments[i], paramType, out origType); - if (!(val.ErrorMessage is null)) + if (val.ErrorMessage is not null) return DbgDotNetValueResult.CreateError(val.ErrorMessage); var valType = origType ?? MonoValueTypeCreator.CreateType(this, val.Value!, paramType); args[i] = BoxIfNeeded(monoThread.Domain, val.Value!, paramType, valType); @@ -357,13 +357,13 @@ DbgDotNetValueResult FuncEvalCallCoreReal_MonoDebug(DbgEvaluationContext? contex return DbgDotNetValueResult.CreateError(PredefinedEvaluationErrorMessages.InternalDebuggerError); if ((funcEvalOptions & FuncEvalOptions.ReturnOutThis) != 0 && res.OutThis is StructMirror outStructMirror) { var error = (obj as DbgDotNetValueImpl)?.ValueLocation.Store(outStructMirror); - if (!(error is null)) + if (error is not null) return DbgDotNetValueResult.CreateError(error); } var returnType = (method as DmdMethodInfo)?.ReturnType ?? method.ReflectedType!; var returnValue = res.Exception ?? res.Result ?? createdResultValue ?? new PrimitiveValue(vm, ElementType.Object, null); var valueLocation = new NoValueLocation(returnType, returnValue); - if (!(res.Exception is null)) + if (res.Exception is not null) return DbgDotNetValueResult.CreateException(CreateDotNetValue_MonoDebug(valueLocation)); return DbgDotNetValueResult.Create(CreateDotNetValue_MonoDebug(valueLocation)); } @@ -398,7 +398,7 @@ internal DbgDotNetValueResult Box_MonoDebug(DbgEvaluationInfo evalInfo, Value va debuggerThread.VerifyAccess(); evalInfo.CancellationToken.ThrowIfCancellationRequested(); var tmp = CheckFuncEval(evalInfo.Context); - if (!(tmp is null)) + if (tmp is not null) return tmp.Value; var monoThread = GetThread(evalInfo.Frame.Thread); @@ -428,7 +428,7 @@ internal DbgDotNetValueResult CreateValue_MonoDebug(DbgEvaluationInfo evalInfo, if (value is DbgDotNetValueImpl) return DbgDotNetValueResult.Create((DbgDotNetValueImpl)value); var tmp = CheckFuncEval(evalInfo.Context); - if (!(tmp is null)) + if (tmp is not null) return tmp.Value; var monoThread = GetThread(evalInfo.Frame.Thread); @@ -437,7 +437,7 @@ internal DbgDotNetValueResult CreateValue_MonoDebug(DbgEvaluationInfo evalInfo, using (var funcEval = CreateFuncEval(evalInfo.Context, monoThread, evalInfo.CancellationToken)) { var converter = new EvalArgumentConverter(this, funcEval, monoThread.Domain, reflectionAppDomain); var evalRes = converter.Convert(value, reflectionAppDomain.System_Object, out var newValueType); - if (!(evalRes.ErrorMessage is null)) + if (evalRes.ErrorMessage is not null) return DbgDotNetValueResult.CreateError(evalRes.ErrorMessage); var resultValue = CreateDotNetValue_MonoDebug(reflectionAppDomain, evalRes.Value!, newValueType); @@ -461,7 +461,7 @@ internal DbgCreateMonoValueResult CreateMonoValue_MonoDebug(DbgEvaluationInfo ev if (value is DbgDotNetValueImpl) return new DbgCreateMonoValueResult(((DbgDotNetValueImpl)value).Value); var tmp = CheckFuncEval(evalInfo.Context); - if (!(tmp is null)) + if (tmp is not null) return new DbgCreateMonoValueResult(tmp.Value.ErrorMessage ?? throw new InvalidOperationException()); var monoThread = GetThread(evalInfo.Frame.Thread); @@ -470,7 +470,7 @@ internal DbgCreateMonoValueResult CreateMonoValue_MonoDebug(DbgEvaluationInfo ev using (var funcEval = CreateFuncEval(evalInfo.Context, monoThread, evalInfo.CancellationToken)) { var converter = new EvalArgumentConverter(this, funcEval, monoThread.Domain, reflectionAppDomain); var evalRes = converter.Convert(value, targetType, out var newValueType); - if (!(evalRes.ErrorMessage is null)) + if (evalRes.ErrorMessage is not null) return new DbgCreateMonoValueResult(evalRes.ErrorMessage); var newValue = evalRes.Value!; if (targetType.IsEnum && !(newValue is EnumMirror)) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Steppers.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Steppers.cs index 7616c32f56..a3a8c50631 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Steppers.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Steppers.cs @@ -66,7 +66,7 @@ bool OnStep(StepEventRequest? stepReq) { internal void CancelStepper(StepEventRequest stepReq) { debuggerThread.VerifyAccess(); - if (!(stepReq is null)) { + if (stepReq is not null) { try { using (TempBreak()) stepReq.Disable(); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Threads.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Threads.cs index fcc1ebbe2c..b603654194 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Threads.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.Threads.cs @@ -59,7 +59,7 @@ public DbgThreadData(ThreadMirror monoThread, bool isMainThread, bool isFinalize } DbgThreadData? TryGetThreadData(DbgThread thread) { - if (!(thread is null) && thread.TryGetData(out DbgThreadData? data)) + if (thread is not null && thread.TryGetData(out DbgThreadData? data)) return data; return null; } @@ -125,18 +125,18 @@ sealed class GetManagedIdState { return null; var appDomain = TryGetEngineAppDomain(thread.Domain)?.AppDomain; - if (!(appDomain is null)) { + if (appDomain is not null) { try { var state = appDomain.GetOrCreateData(); if (state.ManagedIdGetter is null) { var threadType = thread.Domain.Corlib.GetType("System.Threading.Thread", false, false); - Debug2.Assert(!(threadType is null)); + Debug2.Assert(threadType is not null); state.ManagedIdGetter = threadType?.GetMethod("get_" + nameof(ST.Thread.ManagedThreadId)); } - if (!(state.ManagedIdGetter is null)) { + if (state.ManagedIdGetter is not null) { if (!TryGetManagedId(thread, thread, state.ManagedIdGetter, out ulong? managedId)) return null; - if (!(managedId is null)) + if (managedId is not null) return managedId; foreach (var t in thread.VirtualMachine.GetThreads()) { @@ -144,7 +144,7 @@ sealed class GetManagedIdState { continue; if (!TryGetManagedId(t, thread, state.ManagedIdGetter, out managedId)) return null; - if (!(managedId is null)) + if (managedId is not null) return managedId; } } @@ -247,7 +247,7 @@ void UpdateThreadProperties_MonoDebug() { threadsToUpdate = new List<(DbgEngineThread, DbgEngineThread.UpdateOptions, ThreadProperties)>(); threadsToUpdate.Add(info.Value); } - if (!(threadsToUpdate is null)) { + if (threadsToUpdate is not null) { foreach (var info in threadsToUpdate) NotifyThreadPropertiesChanged_MonoDebug(info.engineThread, info.updateOptions, info.props); } @@ -283,7 +283,7 @@ void DestroyThread(ThreadMirror? monoThread) { if (toEngineThread.TryGetValue(monoThread, out engineThread)) toEngineThread.Remove(monoThread); } - if (!(engineThread is null)) + if (engineThread is not null) engineThread.Remove(GetMessageFlags() | DbgEngineMessageFlags.Running); } @@ -402,7 +402,7 @@ bool VerifySetIPLocation(DbgThreadData threadData, IDbgDotNetCodeLocation locati if (module is null) return false; - if (!(location.DbgModule is null)) { + if (location.DbgModule is not null) { if (location.DbgModule != module) return false; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.cs index fb5e05f179..cb62a19319 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DbgEngineImpl.cs @@ -174,7 +174,7 @@ internal DbgEngineMessageFlags GetMessageFlags(bool pause = false) { bool HasConnected_MonoDebugThread { get { debuggerThread.VerifyAccess(); - return !(vm is null); + return vm is not null; } } @@ -214,7 +214,7 @@ public DelegatePendingMessage(bool mustWaitForRun, bool requireResumeVM, Func= 0); @@ -296,7 +296,7 @@ void StartCore(DebugProgramOptions options) { monoExe = MonoExeFinder.Find(startMonoOptions.MonoExeOptions); if (!File.Exists(monoExe)) throw new StartException(string.Format(dnSpy_Debugger_DotNet_Mono_Resources.Error_CouldNotFindFile, MonoExeFinder.MONO_EXE)); - Debug2.Assert(!(monoExe is null)); + Debug2.Assert(monoExe is not null); Debug.Assert(!connectionAddress.Contains(" ")); var psi = new ProcessStartInfo { FileName = monoExe, @@ -541,7 +541,7 @@ async void ReadConsoleOutputAsync() { void MonoEventThread() { var vm = this.vm; - Debug2.Assert(!(vm is null)); + Debug2.Assert(vm is not null); if (vm is null) throw new InvalidOperationException(); for (;;) { @@ -672,7 +672,7 @@ void OnDebuggerEvents() { eventSets = pendingEventSets.ToArray(); pendingEventSets.Clear(); } - if (!(eventSet is null)) + if (eventSet is not null) OnDebuggerEvents(eventSet); else { foreach (var e in eventSets!) @@ -769,7 +769,7 @@ void OnDebuggerEventsCore(EventSet eventSet) { case EventType.VMDeath: expectedSuspendPolicy = SuspendPolicy.None; var vmde = (VMDeathEvent)evt; - if (!(vmDeathExitCode is null)) + if (vmDeathExitCode is not null) break; if (vm!.Version.AtLeast(2, 27)) vmDeathExitCode = vmde.ExitCode; @@ -807,7 +807,7 @@ void OnDebuggerEventsCore(EventSet eventSet) { case EventType.MethodEntry: expectedSuspendPolicy = SuspendPolicy.None; Debug.Assert(evt.TryGetRequest() == methodEntryEventRequest); - if (!(methodEntryEventRequest is null) && evt.TryGetRequest() == methodEntryEventRequest) { + if (methodEntryEventRequest is not null && evt.TryGetRequest() == methodEntryEventRequest) { methodEntryEventRequest.Disable(); methodEntryEventRequest = null; // Func-eval doesn't work at first assembly load event for some reason. Should work now though. @@ -844,7 +844,7 @@ void OnDebuggerEventsCore(EventSet eventSet) { expectedSuspendPolicy = SuspendPolicy.All; var be = (BreakpointEvent)evt; var bpReq = be.TryGetRequest() as BreakpointEventRequest; - if (!(bpReq is null)) { + if (bpReq is not null) { if (breakOnEntryPointData?.Breakpoint == bpReq) { bpReq.Disable(); breakOnEntryPointData = null; @@ -875,7 +875,7 @@ void OnDebuggerEventsCore(EventSet eventSet) { // Add it to the cache var reflectionAppDomain = TryGetEngineAppDomain(tle.Type.Assembly.Domain)?.AppDomain.GetReflectionAppDomain(); - if (!(reflectionAppDomain is null)) { + if (reflectionAppDomain is not null) { try { GetReflectionType(reflectionAppDomain, tle.Type, null); } @@ -1098,7 +1098,7 @@ void DestroyAppDomain(AppDomainMirror monoAppDomain) { } } } - if (!(engineAppDomain is null)) + if (engineAppDomain is not null) engineAppDomain.Remove(GetMessageFlags()); } @@ -1135,7 +1135,7 @@ bool TryGetModuleData(DbgModule module, [NotNullWhen(true)] out DbgModuleData? d bool CreateModule(ModuleMirror monoModule) { debuggerThread.VerifyAccess(); - if (!(TryGetModuleCore_NoCreate(monoModule) is null)) + if (TryGetModuleCore_NoCreate(monoModule) is not null) return false; var appDomain = TryGetEngineAppDomain(monoModule.Assembly.Domain)?.AppDomain; @@ -1152,7 +1152,7 @@ bool CreateModule(ModuleMirror monoModule) { toEngineModule.Add(monoModule, engineModule); } - if (!(breakOnEntryPointData is null) && breakOnEntryPointData.Breakpoint is null && + if (breakOnEntryPointData is not null && breakOnEntryPointData.Breakpoint is null && StringComparer.OrdinalIgnoreCase.Equals(breakOnEntryPointData.Filename, engineModule.Module.Filename)) { try { CreateEntryPointBreakpoint(monoModule.Assembly.EntryPoint); @@ -1186,7 +1186,7 @@ void DestroyModule(ModuleMirror monoModule) { ((DbgMonoDebugInternalModuleImpl)engineModule.Module.InternalModule).Remove(); } } - if (!(engineModule is null)) + if (engineModule is not null) engineModule.Remove(GetMessageFlags()); } @@ -1194,11 +1194,11 @@ void DestroyModule(ModuleMirror monoModule) { if (monoModule is null) return null; var res = TryGetModuleCore_NoCreate(monoModule); - if (!(res is null)) + if (res is not null) return res; DiscoverNewModules(monoModule); res = TryGetModuleCore_NoCreate(monoModule); - Debug2.Assert(!(res is null)); + Debug2.Assert(res is not null); return res; } @@ -1217,7 +1217,7 @@ void DestroyModule(ModuleMirror monoModule) { // when we've found a new module. void DiscoverNewModules(ModuleMirror monoModule) { debuggerThread.VerifyAccess(); - if (!(monoModule is null)) { + if (monoModule is not null) { Debug.Assert(monoModule.Assembly.ManifestModule == monoModule); AddNewModule(monoModule); } @@ -1232,7 +1232,7 @@ void DiscoverNewModules(ModuleMirror monoModule) { void AddNewModule(ModuleMirror monoModule) { debuggerThread.VerifyAccess(); - if (!(TryGetModuleCore_NoCreate(monoModule) is null)) + if (TryGetModuleCore_NoCreate(monoModule) is not null) return; if (suspendCount == 0) { @@ -1296,7 +1296,7 @@ static string GetCouldNotConnectErrorMessage(string address, ushort port, string internal IDbgDotNetRuntime DotNetRuntime => internalRuntime!; DbgMonoDebugInternalRuntimeImpl? internalRuntime; public override DbgInternalRuntime CreateInternalRuntime(DbgRuntime runtime) { - if (!(internalRuntime is null)) + if (internalRuntime is not null) throw new InvalidOperationException(); dmdRuntime = DmdRuntimeFactory.CreateRuntime(new DmdEvaluatorImpl(this), runtime.Process.PointerSize == 4 ? DmdImageFileMachine.I386 : DmdImageFileMachine.AMD64); return internalRuntime = new DbgMonoDebugInternalRuntimeImpl(this, runtime, dmdRuntime, monoDebugRuntimeKind); @@ -1343,10 +1343,10 @@ void OnConnected_MonoDebug() { try { if (gotVMDisconnect) return; - if (!(consoleStdOut is null)) + if (consoleStdOut is not null) ReadConsoleOutputAsync(); - Debug2.Assert(!(vm is null)); - if (!(vm is null)) { + Debug2.Assert(vm is not null); + if (vm is not null) { InitializeVirtualMachine(); // Create the root AppDomain now since we want it to get id=1, which isn't guaranteed // if it's an attach and we wait for AppDomainCreate events. @@ -1516,7 +1516,7 @@ internal DmdType GetReflectionType(DmdAppDomain reflectionAppDomain, TypeMirror // can't create the correct instantiated generic type. We can't create a generic DmdType from a // TypeMirror. If we cache the generic DmdType, we'll be able to look it up later when we get // a generic TypeMirror. - if (!(couldBeRealTypeOpt is null) && !vm!.Version.AtLeast(2, 15)) { + if (couldBeRealTypeOpt is not null && !vm!.Version.AtLeast(2, 15)) { try { MonoDebugTypeCreator.GetType(this, couldBeRealTypeOpt, null); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DebuggerThread.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DebuggerThread.cs index 2a4cdda23d..d8fedfbd1c 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DebuggerThread.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/DebuggerThread.cs @@ -76,7 +76,7 @@ void DebuggerThreadProc(AutoResetEvent autoResetEvent) { internal void Terminate() { terminate = true; try { callDispatcherRunEvent?.Set(); } catch (ObjectDisposedException) { } - if (!(Dispatcher is null) && !Dispatcher.HasShutdownStarted && !Dispatcher.HasShutdownFinished) + if (Dispatcher is not null && !Dispatcher.HasShutdownStarted && !Dispatcher.HasShutdownFinished) Dispatcher.BeginInvokeShutdown(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/EvalReflectionUtils.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/EvalReflectionUtils.cs index 793e128ef9..fbddae5a47 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/EvalReflectionUtils.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/EvalReflectionUtils.cs @@ -36,7 +36,7 @@ static class EvalReflectionUtils { } static FieldInfoMirror? GetField(TypeMirror type, string name1, string name2) { - while (!(type is null)) { + while (type is not null) { foreach (var field in type.GetFields()) { if (field.Name == name1 || field.Name == name2) return field; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgDotNetRawValueFactory.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgDotNetRawValueFactory.cs index f98b1fb743..037b3b6401 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgDotNetRawValueFactory.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgDotNetRawValueFactory.cs @@ -35,8 +35,8 @@ readonly struct DbgDotNetRawValueFactory { static DbgDotNetRawValueFactory() { var ctor = typeof(DateTime).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(ulong) }, null); - Debug2.Assert(!(ctor is null)); - if (!(ctor is null)) { + Debug2.Assert(ctor is not null); + if (ctor is not null) { var dm = new DynamicMethod("DateTime_ctor_UInt64", typeof(DateTime), new[] { typeof(ulong) }, true); var ilg = dm.GetILGenerator(); ilg.Emit(OpCodes.Ldarg_0); @@ -108,62 +108,62 @@ DbgDotNetRawValue Create(Value value, DmdType type, int recursionCounter) { PrimitiveValue? bpv; switch (DmdType.GetTypeCode(type)) { case TypeCode.Boolean: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is bool) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is bool) return new DbgDotNetRawValue(DbgSimpleValueType.Boolean, bpv.Value); break; case TypeCode.Char: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is char) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is char) return new DbgDotNetRawValue(DbgSimpleValueType.CharUtf16, bpv.Value); break; case TypeCode.SByte: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is sbyte) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is sbyte) return new DbgDotNetRawValue(DbgSimpleValueType.Int8, bpv.Value); break; case TypeCode.Byte: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is byte) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is byte) return new DbgDotNetRawValue(DbgSimpleValueType.UInt8, bpv.Value); break; case TypeCode.Int16: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is short) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is short) return new DbgDotNetRawValue(DbgSimpleValueType.Int16, bpv.Value); break; case TypeCode.UInt16: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is ushort) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is ushort) return new DbgDotNetRawValue(DbgSimpleValueType.UInt16, bpv.Value); break; case TypeCode.Int32: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is int) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is int) return new DbgDotNetRawValue(DbgSimpleValueType.Int32, bpv.Value); break; case TypeCode.UInt32: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is uint) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is uint) return new DbgDotNetRawValue(DbgSimpleValueType.UInt32, bpv.Value); break; case TypeCode.Int64: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is long) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is long) return new DbgDotNetRawValue(DbgSimpleValueType.Int64, bpv.Value); break; case TypeCode.UInt64: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is ulong) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is ulong) return new DbgDotNetRawValue(DbgSimpleValueType.UInt64, bpv.Value); break; case TypeCode.Single: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is float) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is float) return new DbgDotNetRawValue(DbgSimpleValueType.Float32, bpv.Value); break; case TypeCode.Double: - if (sm.Fields.Length == 1 && !((bpv = sm.Fields[0] as PrimitiveValue) is null) && bpv.Value is double) + if (sm.Fields.Length == 1 && (bpv = sm.Fields[0] as PrimitiveValue) is not null && bpv.Value is double) return new DbgDotNetRawValue(DbgSimpleValueType.Float64, bpv.Value); break; @@ -208,7 +208,7 @@ DbgDotNetRawValue Create(Value value, DmdType type, int recursionCounter) { static decimal ReadDecimal(StructMirror value) { var fields = GetDecimalFields(value); - if (!(fields is null)) { + if (fields is not null) { var decimalBits = new int[4]; decimalBits[0] = fields.Value.lo; decimalBits[1] = fields.Value.mid; @@ -255,7 +255,7 @@ static DateTime ReadDateTime(StructMirror structMirror) { if (fields[0].Name != KnownMemberNames.DateTime_DateData_FieldName1 && fields[0].Name != KnownMemberNames.DateTime_DateData_FieldName2) return default; if (values[0] is PrimitiveValue pv && pv.Value is ulong) { - if (!(DateTime_ctor_UInt64 is null)) + if (DateTime_ctor_UInt64 is not null) return DateTime_ctor_UInt64((ulong)pv.Value); return default; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgDotNetValueImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgDotNetValueImpl.cs index 2c12456f49..f1650f2d40 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgDotNetValueImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgDotNetValueImpl.cs @@ -98,7 +98,7 @@ DbgDotNetValueResult Dereference_MonoDebug() { if (!Type.IsByRef) return PredefinedEvaluationErrorMessages.InternalDebuggerError; var res = engine.CreateMonoValue_MonoDebug(evalInfo, value, Type.GetElementType()!); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res.ErrorMessage; return valueLocation.Store(res.Value!); } @@ -176,7 +176,7 @@ DbgDotNetValueResult GetArrayElementAt_MonoDebug(uint index) { Debug.Assert(Type.IsArray); engine.VerifyMonoDebugThread(); var info = GetArrayElementValueLocation_MonoDebug(index); - if (!(info.errorMessage is null)) + if (info.errorMessage is not null) return DbgDotNetValueResult.CreateError(info.errorMessage); return DbgDotNetValueResult.Create(engine.CreateDotNetValue_MonoDebug(info.valueLocation!)); } @@ -202,10 +202,10 @@ DbgDotNetValueResult GetArrayElementAt_MonoDebug(uint index) { engine.VerifyMonoDebugThread(); evalInfo.CancellationToken.ThrowIfCancellationRequested(); var info = GetArrayElementValueLocation_MonoDebug(index); - if (!(info.errorMessage is null)) + if (info.errorMessage is not null) return info.errorMessage; var res = engine.CreateMonoValue_MonoDebug(evalInfo, value, info.valueLocation!.Type); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res.ErrorMessage; return info.valueLocation.Store(res.Value!); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgMonoDebugInternalRuntimeImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgMonoDebugInternalRuntimeImpl.cs index 1fe6145047..e640d845d2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgMonoDebugInternalRuntimeImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DbgMonoDebugInternalRuntimeImpl.cs @@ -64,7 +64,7 @@ public DbgMonoDebugInternalRuntimeImpl(DbgEngineImpl engine, DbgRuntime runtime, monoDebugValueConverter = new MonoDebugValueConverterImpl(this); classHooks = new Dictionary(); foreach (var info in ClassHookProvider.Create(engine, this)) { - Debug2.Assert(!(info.Hook is null)); + Debug2.Assert(info.Hook is not null); Debug.Assert(!classHooks.ContainsKey(info.WellKnownType)); classHooks.Add(info.WellKnownType, info.Hook); } @@ -176,7 +176,7 @@ sealed class GetFrameMethodState { static DmdMethodBase? TryGetMethod(DmdModule module, int methodMetadataToken, IList genericTypeArguments, IList genericMethodArguments) { var method = module?.ResolveMethod(methodMetadataToken, (IList?)null, null, DmdResolveOptions.None); - if (!(method is null)) { + if (method is not null) { if (genericTypeArguments.Count != 0) { var type = method.ReflectedType!.MakeGenericType(genericTypeArguments); method = type.GetMethod(method.Module, method.MetadataToken, throwOnError: true)!; @@ -208,7 +208,7 @@ DbgDotNetValueResult LoadFieldCore(DbgEvaluationInfo evalInfo, DbgDotNetValue? o Dispatcher.VerifyAccess(); try { var info = GetFieldValueLocationCore(evalInfo, obj, field); - if (!(info.errorMessage is null)) + if (info.errorMessage is not null) return DbgDotNetValueResult.CreateError(info.errorMessage); return DbgDotNetValueResult.Create(engine.CreateDotNetValue_MonoDebug(info.valueLocation!)); } @@ -272,7 +272,7 @@ sealed class StaticConstructorInitializedState { } void InitializeStaticConstructor(DbgEvaluationInfo evalInfo, ILDbgEngineStackFrame ilFrame, DmdType type, TypeMirror monoType) { - if (!(engine.CheckFuncEval(evalInfo.Context) is null)) + if (engine.CheckFuncEval(evalInfo.Context) is not null) return; var state = type.GetOrCreateData(); if (state.Initialized > 0 || Interlocked.Exchange(ref state.Initialized, 1) != 0) @@ -280,7 +280,7 @@ void InitializeStaticConstructor(DbgEvaluationInfo evalInfo, ILDbgEngineStackFra if (engine.MonoVirtualMachine.Version.AtLeast(2, 23) && monoType.IsInitialized) return; var cctor = type.TypeInitializer; - if (!(cctor is null)) { + if (cctor is not null) { var fields = type.DeclaredFields; for (int i = 0; i < fields.Count; i++) { var field = fields[i]; @@ -295,7 +295,7 @@ void InitializeStaticConstructor(DbgEvaluationInfo evalInfo, ILDbgEngineStackFra catch { break; } - if (!(fieldValue is null)) { + if (fieldValue is not null) { if (fieldValue is PrimitiveValue pv && pv.Value is null) continue; if (field.FieldType.IsValueType) { @@ -332,11 +332,11 @@ bool RuntimeHelpersRunClassConstructor(DbgEvaluationInfo evalInfo, DmdType type, try { var reflectionAppDomain = type.AppDomain; var runtimeTypeHandleType = reflectionAppDomain.GetWellKnownType(DmdWellKnownType.System_RuntimeTypeHandle, isOptional: true); - Debug2.Assert(!(runtimeTypeHandleType is null)); + Debug2.Assert(runtimeTypeHandleType is not null); if (runtimeTypeHandleType is null) return false; var getTypeHandleMethod = objValue.Type.GetMethod("get_" + nameof(Type.TypeHandle), DmdSignatureCallingConvention.Default | DmdSignatureCallingConvention.HasThis, 0, runtimeTypeHandleType, Array.Empty(), throwOnError: false); - Debug2.Assert(!(getTypeHandleMethod is null)); + Debug2.Assert(getTypeHandleMethod is not null); if (getTypeHandleMethod is null) return false; typeHandleRes = engine.FuncEvalCall_MonoDebug(evalInfo, getTypeHandleMethod, objValue, Array.Empty(), DbgDotNetInvokeOptions.None, false); @@ -344,7 +344,7 @@ bool RuntimeHelpersRunClassConstructor(DbgEvaluationInfo evalInfo, DmdType type, return false; var runtimeHelpersType = reflectionAppDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, isOptional: true); var runClassConstructorMethod = runtimeHelpersType?.GetMethod(nameof(RuntimeHelpers.RunClassConstructor), DmdSignatureCallingConvention.Default, 0, reflectionAppDomain.System_Void, new[] { runtimeTypeHandleType }, throwOnError: false); - Debug2.Assert(!(runClassConstructorMethod is null)); + Debug2.Assert(runClassConstructorMethod is not null); if (runClassConstructorMethod is null) return false; res = engine.FuncEvalCall_MonoDebug(evalInfo, runClassConstructorMethod, null, new[] { typeHandleRes.Value }, DbgDotNetInvokeOptions.None, false); @@ -411,10 +411,10 @@ bool IsZero(Value value, int recursionCounter) { evalInfo.CancellationToken.ThrowIfCancellationRequested(); try { var info = GetFieldValueLocationCore(evalInfo, obj, field); - if (!(info.errorMessage is null)) + if (info.errorMessage is not null) return info.errorMessage; var res = engine.CreateMonoValue_MonoDebug(evalInfo, value, field.FieldType); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res.ErrorMessage; return info.valueLocation!.Store(res.Value!); } @@ -445,7 +445,7 @@ DbgDotNetValueResult CallCore(DbgEvaluationInfo evalInfo, DbgDotNetValue? obj, D if (DmdWellKnownTypeUtils.TryGetWellKnownType(typeName, out var wellKnownType)) { if (classHooks.TryGetValue(wellKnownType, out var hook) && type == type.AppDomain.GetWellKnownType(wellKnownType, isOptional: true)) { var res = hook.Call(obj, method, arguments); - if (!(res is null)) + if (res is not null) return DbgDotNetValueResult.Create(res); } } @@ -479,7 +479,7 @@ DbgDotNetValueResult CreateInstanceCore(DbgEvaluationInfo evalInfo, DmdConstruct if (DmdWellKnownTypeUtils.TryGetWellKnownType(typeName, out var wellKnownType)) { if (classHooks.TryGetValue(wellKnownType, out var hook) && type == type.AppDomain.GetWellKnownType(wellKnownType, isOptional: true)) { var res = hook.CreateInstance(ctor, arguments); - if (!(res is null)) + if (res is not null) return DbgDotNetValueResult.Create(res); } } @@ -622,15 +622,15 @@ DbgDotNetAliasInfo[] GetAliasesCore(DbgEvaluationInfo evalInfo) { stowedException = GetStowedExceptionCore(evalInfo, DbgDotNetRuntimeConstants.StowedExceptionId); returnValues = GetReturnValuesCore(evalInfo); - int count = (!(exception is null) ? 1 : 0) + (!(stowedException is null) ? 1 : 0) + returnValues.Length + (returnValues.Length != 0 ? 1 : 0); + int count = (exception is not null ? 1 : 0) + (stowedException is not null ? 1 : 0) + returnValues.Length + (returnValues.Length != 0 ? 1 : 0); if (count == 0) return Array.Empty(); var res = new DbgDotNetAliasInfo[count]; int w = 0; - if (!(exception is null)) + if (exception is not null) res[w++] = new DbgDotNetAliasInfo(DbgDotNetAliasInfoKind.Exception, exception.Type, DbgDotNetRuntimeConstants.ExceptionId, Guid.Empty, null); - if (!(stowedException is null)) + if (stowedException is not null) res[w++] = new DbgDotNetAliasInfo(DbgDotNetAliasInfoKind.StowedException, stowedException.Type, DbgDotNetRuntimeConstants.StowedExceptionId, Guid.Empty, null); if (returnValues.Length != 0) { res[w++] = new DbgDotNetAliasInfo(DbgDotNetAliasInfoKind.ReturnValue, returnValues[returnValues.Length - 1].Value.Type, DbgDotNetRuntimeConstants.LastReturnValueId, Guid.Empty, null); @@ -671,14 +671,14 @@ DbgDotNetExceptionInfo[] GetExceptionsCore(DbgEvaluationInfo evalInfo) { try { exception = GetExceptionCore(evalInfo, DbgDotNetRuntimeConstants.ExceptionId); stowedException = GetStowedExceptionCore(evalInfo, DbgDotNetRuntimeConstants.StowedExceptionId); - int count = (!(exception is null) ? 1 : 0) + (!(stowedException is null) ? 1 : 0); + int count = (exception is not null ? 1 : 0) + (stowedException is not null ? 1 : 0); if (count == 0) return Array.Empty(); var res = new DbgDotNetExceptionInfo[count]; int w = 0; - if (!(exception is null)) + if (exception is not null) res[w++] = new DbgDotNetExceptionInfo(exception, DbgDotNetRuntimeConstants.ExceptionId, DbgDotNetExceptionInfoFlags.None); - if (!(stowedException is null)) + if (stowedException is not null) res[w++] = new DbgDotNetExceptionInfo(stowedException, DbgDotNetRuntimeConstants.StowedExceptionId, DbgDotNetExceptionInfoFlags.StowedException); if (w != res.Length) throw new InvalidOperationException(); @@ -779,7 +779,7 @@ DbgDotNetValueResult GetLocalValueCore(DbgEvaluationInfo evalInfo, uint index) { Dispatcher.VerifyAccess(); try { var info = GetLocalValueLocationCore(evalInfo, index); - if (!(info.errorMessage is null)) + if (info.errorMessage is not null) return DbgDotNetValueResult.CreateError(info.errorMessage); return DbgDotNetValueResult.Create(engine.CreateDotNetValue_MonoDebug(info.valueLocation!)); } @@ -806,8 +806,8 @@ DbgDotNetValueResult GetLocalValueCore(DbgEvaluationInfo evalInfo, uint index) { var method = GetFrameMethodCore(evalInfo); var localVars = GetCachedMethodBody(method)?.LocalVariables; - var localType = !(localVars is null) && (uint)index < (uint)localVars.Count ? localVars[(int)index].LocalType : null; - if (!(localType is null) && localType.IsByRef) + var localType = localVars is not null && (uint)index < (uint)localVars.Count ? localVars[(int)index].LocalType : null; + if (localType is not null && localType.IsByRef) localType = localType.GetElementType(); var type = engine.GetReflectionType(reflectionAppDomain, local.Type, localType); type = AddByRefIfNeeded(type, localVars, index); @@ -866,7 +866,7 @@ DbgDotNetValueResult GetParameterValueCore(DbgEvaluationInfo evalInfo, uint inde Dispatcher.VerifyAccess(); try { var info = GetParameterValueLocationCore(evalInfo, index); - if (!(info.errorMessage is null)) + if (info.errorMessage is not null) return DbgDotNetValueResult.CreateError(info.errorMessage); return DbgDotNetValueResult.Create(engine.CreateDotNetValue_MonoDebug(info.valueLocation!)); } @@ -904,8 +904,8 @@ DbgDotNetValueResult GetParameterValueCore(DbgEvaluationInfo evalInfo, uint inde var method = GetFrameMethodCore(evalInfo); var paramTypes = method?.GetMethodSignature().GetParameterTypes(); - var paramType = !(paramTypes is null) && (uint)index < (uint)paramTypes.Count ? paramTypes[(int)index] : null; - if (!(paramType is null) && paramType.IsByRef) + var paramType = paramTypes is not null && (uint)index < (uint)paramTypes.Count ? paramTypes[(int)index] : null; + if (paramType is not null && paramType.IsByRef) paramType = paramType.GetElementType(); type = engine.GetReflectionType(reflectionAppDomain, parameter.ParameterType, paramType); type = AddByRefIfNeeded(type, paramTypes, index); @@ -930,10 +930,10 @@ DbgDotNetValueResult GetParameterValueCore(DbgEvaluationInfo evalInfo, uint inde evalInfo.CancellationToken.ThrowIfCancellationRequested(); try { var info = GetLocalValueLocationCore(evalInfo, index); - if (!(info.errorMessage is null)) + if (info.errorMessage is not null) return info.errorMessage; var res = engine.CreateMonoValue_MonoDebug(evalInfo, value, targetType); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res.ErrorMessage; return info.valueLocation!.Store(res.Value!); } @@ -959,10 +959,10 @@ DbgDotNetValueResult GetParameterValueCore(DbgEvaluationInfo evalInfo, uint inde evalInfo.CancellationToken.ThrowIfCancellationRequested(); try { var info = GetParameterValueLocationCore(evalInfo, index); - if (!(info.errorMessage is null)) + if (info.errorMessage is not null) return info.errorMessage; var res = engine.CreateMonoValue_MonoDebug(evalInfo, value, targetType); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res.ErrorMessage; return info.valueLocation!.Store(res.Value!); } @@ -1014,10 +1014,10 @@ DbgDotNetValueResult BoxCore(DbgEvaluationInfo evalInfo, object? value) { DbgDotNetValueResult res = default; try { res = CreateValueCore(evalInfo, value); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; var boxedValue = res.Value!.Box(evalInfo); - if (!(boxedValue is null)) + if (boxedValue is not null) return boxedValue.Value; return DbgDotNetValueResult.CreateError(PredefinedEvaluationErrorMessages.InternalDebuggerError); } @@ -1058,13 +1058,13 @@ public bool CanCreateObjectId(DbgDotNetValue value) => var appDomain = value.Type.AppDomain; var gcHandleType = appDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_InteropServices_GCHandle, isOptional: true); - Debug2.Assert(!(gcHandleType is null)); + Debug2.Assert(gcHandleType is not null); if (gcHandleType is null) return null; var allocMethod = gcHandleType.GetMethod(nameof(System.Runtime.InteropServices.GCHandle.Alloc), DmdSignatureCallingConvention.Default, 0, gcHandleType, new[] { appDomain.System_Object }, throwOnError: false); - Debug2.Assert(!(allocMethod is null)); + Debug2.Assert(allocMethod is not null); if (allocMethod is null) return null; @@ -1108,13 +1108,13 @@ void FreeObjectId_Paused(DbgDotNetObjectIdImpl objectId) { var appDomain = objectId.ReflectionAppDomain; var gcHandleType = appDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_InteropServices_GCHandle, isOptional: true); - Debug2.Assert(!(gcHandleType is null)); + Debug2.Assert(gcHandleType is not null); if (gcHandleType is null) return; var freeMethod = gcHandleType.GetMethod(nameof(System.Runtime.InteropServices.GCHandle.Free), DmdSignatureCallingConvention.HasThis, 0, appDomain.System_Void, Array.Empty(), throwOnError: false); - Debug2.Assert(!(freeMethod is null)); + Debug2.Assert(freeMethod is not null); if (freeMethod is null) return; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DmdEvaluatorImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DmdEvaluatorImpl.cs index 6bdfcba964..180bad81a6 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DmdEvaluatorImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/DmdEvaluatorImpl.cs @@ -50,9 +50,9 @@ DbgEvaluationInfo GetEvaluationInfo(object? context) { } object GetValueThrow(DbgDotNetValueResult result) { - if (!(result.ErrorMessage is null)) + if (result.ErrorMessage is not null) throw new DmdEvaluatorException(result.ErrorMessage); - Debug2.Assert(!(result.Value is null)); + Debug2.Assert(result.Value is not null); if (result.ValueIsException) { var msg = "An exception was thrown: " + result.Value.Type.FullName; result.Value.Dispose(); @@ -82,7 +82,7 @@ object GetValueThrow(DbgDotNetValueResult result) { public override void StoreField(object? context, DmdFieldInfo field, object? obj, object? value) { var evalInfo = GetEvaluationInfo(context); var errorMessage = engine.DotNetRuntime.StoreField(evalInfo, GetDotNetValue(obj), field, value); - if (!(errorMessage is null)) + if (errorMessage is not null) throw new DmdEvaluatorException(errorMessage); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/EvalArgumentConverter.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/EvalArgumentConverter.cs index 97c019d1f4..a05e017f54 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/EvalArgumentConverter.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/EvalArgumentConverter.cs @@ -87,7 +87,7 @@ public EvalArgumentResult Convert(object? value, DmdType defaultType, out DmdTyp return new EvalArgumentResult(appDomain.CreateString(s)); } var res = ConvertCore(value, origType, out type); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; if (origType.IsEnum) { type = origType; @@ -323,7 +323,7 @@ EvalArgumentResult CreateDecimal(decimal value) { static bool IsInitialized(T[] array) where T : class { for (int i = 0; i < array.Length; i++) { - if (!(array[i] is null)) + if (array[i] is not null) return true; } return false; @@ -383,7 +383,7 @@ EvalArgumentResult ConvertSZArray(string[] array, out DmdType type) { var elementType = reflectionAppDomain.System_String; type = elementType.MakeArrayType(); var res = CreateSZArray(elementType, array.Length); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; if (!IsInitialized(array)) return res; @@ -396,7 +396,7 @@ EvalArgumentResult ConvertSZArray(string[] array, out DmdType type) { continue; var stringValueRes = Convert(s, elementType, out var type2); - if (!(stringValueRes.ErrorMessage is null)) + if (stringValueRes.ErrorMessage is not null) return stringValueRes; arrayValue[i] = stringValueRes.Value; @@ -408,7 +408,7 @@ EvalArgumentResult ConvertSZArray(string[] array, out DmdType type) { unsafe EvalArgumentResult ConvertSZArray(void* array, int length, int elementSize, DmdType elementType, out DmdType type) { type = elementType.MakeArrayType(); var res = CreateSZArray(elementType, length); - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return res; if (!IsInitialized(array, length * elementSize)) return res; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/Hooks/MonoDebugValueConverterImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/Hooks/MonoDebugValueConverterImpl.cs index 0f378ab25c..44e7a2f5a9 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/Hooks/MonoDebugValueConverterImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/Hooks/MonoDebugValueConverterImpl.cs @@ -34,7 +34,7 @@ bool TryGetUInt32(object? value, out uint result) { if (rawValue.HasRawValue) value = rawValue.RawValue; } - if (!(value is null)) { + if (value is not null) { if (value is bool) { result = (bool)value ? 1U : 0; return true; @@ -100,7 +100,7 @@ int IMonoDebugValueConverter.ToInt32(object? value) { var type = dnValue.Type; if (type.IsArray && type.GetElementType() == type.AppDomain.System_Char) { var addr = dnValue.GetRawAddressValue(onlyDataAddress: true); - if (!(addr is null)) { + if (addr is not null) { ulong chars = addr.Value.Length / 2; if (chars <= int.MaxValue / 2) { if (chars == 0) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/MethodCache.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/MethodCache.cs index 19f3fcd3c1..ce98e824b4 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/MethodCache.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/MethodCache.cs @@ -47,13 +47,13 @@ MethodMirror GetMethodCore(DmdMethodBase method, MonoTypeLoader? monoTypeLoader) MethodMirror? monoMethod; var mi = method as DmdMethodInfo; - if (!(mi is null) && mi.IsConstructedGenericMethod) { + if (mi is not null && mi.IsConstructedGenericMethod) { if (toMonoMethod.TryGetValue(method, out monoMethod)) return monoMethod; if (!engine.MonoVirtualMachine.Version.AtLeast(2, 24)) throw new InvalidOperationException(); monoMethod = TryGetMethodCore2(mi.GetGenericMethodDefinition(), monoTypeLoader); - if (!(monoMethod is null)) { + if (monoMethod is not null) { var genArgs = mi.GetGenericArguments(); var monoGenArgs = new TypeMirror[genArgs.Count]; for (int i = 0; i < monoGenArgs.Length; i++) @@ -65,7 +65,7 @@ MethodMirror GetMethodCore(DmdMethodBase method, MonoTypeLoader? monoTypeLoader) } else { monoMethod = TryGetMethodCore2(method, monoTypeLoader); - if (!(monoMethod is null)) + if (monoMethod is not null) return monoMethod; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/MonoDebugTypeCreator.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/MonoDebugTypeCreator.cs index 6854a743d4..e262505877 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/MonoDebugTypeCreator.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/Evaluation/MonoDebugTypeCreator.cs @@ -162,7 +162,7 @@ public static TypeMirror GetType(DbgEngineImpl engine, DmdType type, MonoTypeLoa // This fails if fullName is a generic instantiated type and at least one generic argument // is a type in another assembly, eg. List. var result = monoType.Module.Assembly.GetType(fullName); - if (!(result is null)) + if (result is not null) return result; return monoTypeLoader?.Load(monoType.Assembly, fullName); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/FuncEvalFactory.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/FuncEvalFactory.cs index 09039f2b0e..c69aef981a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/FuncEvalFactory.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/FuncEvalFactory.cs @@ -117,7 +117,7 @@ InvokeResult CallCore(MethodMirror method, Value? obj, IList arguments, F funcEvalState.methodInvokeCounter++; Debug2.Assert(!isNewobj || obj is null); - bool isInvokeInstanceMethod = !(obj is null) && !isNewobj; + bool isInvokeInstanceMethod = obj is not null && !isNewobj; AsyncCallback asyncCallback = asyncRes2 => { if (done) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ModuleCreator.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ModuleCreator.cs index 19db1d37ca..93fd444262 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ModuleCreator.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ModuleCreator.cs @@ -218,7 +218,7 @@ void InitializeExeFields(string filename, DbgImageLayout imageLayout, out bool i Debug.Assert(imageLayout == DbgImageLayout.File, nameof(GetFileVersion) + " assumes file layout"); var bytes = moduleSize == 0 ? null : engine.DbgRuntime.Process.ReadMemory(moduleAddress, (int)moduleSize); - if (!(bytes is null)) { + if (bytes is not null) { try { version = GetFileVersion(bytes); using (var peImage = new PEImage(bytes, imageLayout == DbgImageLayout.File ? ImageLayout.File : ImageLayout.Memory, true)) @@ -296,7 +296,7 @@ static string GetFileVersion(byte[] bytes) { } finally { try { - if (!(tempFilename is null)) + if (tempFilename is not null) File.Delete(tempFilename); } catch { } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/MonoExeFinder.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/MonoExeFinder.cs index cd664177b7..f32b8b9a83 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/MonoExeFinder.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/MonoExeFinder.cs @@ -40,14 +40,14 @@ static class MonoExeFinder { Find(options, out var mono32, out var mono64); - if ((options & MonoExeOptions.Prefer32) != 0 && (options & MonoExeOptions.Debug32) != 0 && !(mono32 is null)) + if ((options & MonoExeOptions.Prefer32) != 0 && (options & MonoExeOptions.Debug32) != 0 && mono32 is not null) return mono32; - if ((options & MonoExeOptions.Prefer64) != 0 && (options & MonoExeOptions.Debug64) != 0 && !(mono64 is null)) + if ((options & MonoExeOptions.Prefer64) != 0 && (options & MonoExeOptions.Debug64) != 0 && mono64 is not null) return mono64; - if ((options & MonoExeOptions.Debug32) != 0 && !(mono32 is null)) + if ((options & MonoExeOptions.Debug32) != 0 && mono32 is not null) return mono32; - if ((options & MonoExeOptions.Debug64) != 0 && !(mono64 is null)) + if ((options & MonoExeOptions.Debug64) != 0 && mono64 is not null) return mono64; return null; @@ -57,8 +57,8 @@ static void Find(MonoExeOptions options, out string? mono32, out string? mono64) mono32 = null; mono64 = null; foreach (var dir in GetDirectories()) { - bool has32 = !(mono32 is null) || (options & MonoExeOptions.Debug32) == 0; - bool has64 = !(mono64 is null) || (options & MonoExeOptions.Debug64) == 0; + bool has32 = mono32 is not null || (options & MonoExeOptions.Debug32) == 0; + bool has64 = mono64 is not null || (options & MonoExeOptions.Debug64) == 0; if (has32 && has64) break; if (!Directory.Exists(dir)) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/MonoTypeLoader.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/MonoTypeLoader.cs index c72bd5bff0..bc2d20bc47 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/MonoTypeLoader.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/MonoTypeLoader.cs @@ -49,7 +49,7 @@ sealed class LoaderState { public override TypeMirror? Load(AssemblyMirror assembly, string typeFullName) { var res = engine.CheckFuncEval(evalInfo.Context); - if (!(res is null)) + if (res is not null) return null; var appDomain = evalInfo.Frame.AppDomain; if (appDomain is null) @@ -70,14 +70,14 @@ sealed class LoaderState { state.Method_System_Reflection_Assembly_GetType_String = assemblyType.GetMethod(nameof(System.Reflection.Assembly.GetType), DmdSignatureCallingConvention.HasThis, 0, reflectionAppDomain.System_Type, new[] { reflectionAppDomain.System_String }, throwOnError: false); - Debug2.Assert(!(state.Method_System_Reflection_Assembly_GetType_String is null)); + Debug2.Assert(state.Method_System_Reflection_Assembly_GetType_String is not null); if (state.Method_System_Reflection_Assembly_GetType_String is null) return null; state.Method_System_Array_CreateInstance_Type_Int32 = reflectionAppDomain.System_Array.GetMethod(nameof(Array.CreateInstance), DmdSignatureCallingConvention.Default, 0, reflectionAppDomain.System_Array, new[] { reflectionAppDomain.System_Type, reflectionAppDomain.System_Int32 }, throwOnError: false); - Debug2.Assert(!(state.Method_System_Array_CreateInstance_Type_Int32 is null)); + Debug2.Assert(state.Method_System_Array_CreateInstance_Type_Int32 is not null); if (state.Method_System_Array_CreateInstance_Type_Int32 is null) return null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ObjectConstants.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ObjectConstants.cs index ba080730a9..82df85c8df 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ObjectConstants.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ObjectConstants.cs @@ -38,9 +38,9 @@ public ObjectConstantsFactory(DbgProcess process, ThreadMirror thread) { public bool TryCreate([NotNullWhen(true)] out ObjectConstants? objectConstants) { try { var offsetToStringData = GetOffsetToStringData(); - if (!(offsetToStringData is null)) { + if (offsetToStringData is not null) { var offsetToArrayData = GetOffsetToArrayData(); - if (!(offsetToArrayData is null)) { + if (offsetToArrayData is not null) { objectConstants = new ObjectConstants(offsetToStringData, offsetToArrayData); return true; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ReflectionTypeCreator.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ReflectionTypeCreator.cs index 00385affd2..c9710c1bd1 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ReflectionTypeCreator.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Impl/ReflectionTypeCreator.cs @@ -91,20 +91,20 @@ public DmdType Create(TypeMirror type) { else { var module = engine.TryGetModule(type.Module)?.GetReflectionModule() ?? throw new InvalidOperationException(); var reflectionType = module.ResolveType(type.MetadataToken, DmdResolveOptions.None); - if (!(reflectionType is null) && reflectionType.GetGenericArguments().Count != 0) { + if (reflectionType is not null && reflectionType.GetGenericArguments().Count != 0) { DmdType? parsedType = null; TypeMirror[] genericArgs; if (type.VirtualMachine.Version.AtLeast(2, 15)) genericArgs = type.GetGenericArguments(); else { parsedType = reflectionType.Assembly.GetType(type.FullName); - if (!(parsedType is null) && parsedType.MetadataToken != type.MetadataToken) + if (parsedType is not null && parsedType.MetadataToken != type.MetadataToken) parsedType = null; genericArgs = Array.Empty(); - canAddType = !(parsedType is null); + canAddType = parsedType is not null; } - if (!(parsedType is null)) + if (parsedType is not null) reflectionType = parsedType; else { types = GetTypesList(); @@ -116,7 +116,7 @@ public DmdType Create(TypeMirror type) { } types.Add(newType); } - if (!(reflectionType is null)) { + if (reflectionType is not null) { Debug.Assert(types.Count == 0 || reflectionType.GetGenericArguments().Count == types.Count); if (types.Count != 0) reflectionType = reflectionType.MakeGenericType(types.ToArray()); @@ -126,7 +126,7 @@ public DmdType Create(TypeMirror type) { } result = reflectionType; } - if (canAddType && !(result is null)) + if (canAddType && result is not null) typeCache.Add(type, result); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Metadata/DbgAssemblyInfoProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Metadata/DbgAssemblyInfoProviderImpl.cs index 433f2b569e..8cfe942bbe 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Metadata/DbgAssemblyInfoProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Metadata/DbgAssemblyInfoProviderImpl.cs @@ -27,7 +27,7 @@ namespace dnSpy.Debugger.DotNet.Mono.Metadata { sealed class DbgAssemblyInfoProviderFactoryImpl : DbgAssemblyInfoProviderFactory { public override DbgAssemblyInfoProvider? Create(DbgRuntime runtime) { var engine = DbgEngineImpl.TryGetEngine(runtime); - if (!(engine is null)) + if (engine is not null) return new DbgAssemblyInfoProviderImpl(engine); return null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Steppers/DbgDotNetEngineStepperImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Steppers/DbgDotNetEngineStepperImpl.cs index da9f0da4aa..8d9c621547 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Steppers/DbgDotNetEngineStepperImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet.Mono/Steppers/DbgDotNetEngineStepperImpl.cs @@ -89,7 +89,7 @@ public override bool TryGetLocation([NotNullWhen(true)] out DbgModule? module, o token = (uint)(frameMethod?.MetadataToken ?? 0); var offs = frame?.ILOffset; offset = (uint)(offs ?? 0); - return !(module is null) && token != 0 && !(offs is null); + return module is not null && token != 0 && offs is not null; } public override bool Equals(DbgDotNetEngineStepperFrameInfo other) { @@ -118,9 +118,9 @@ public override Task StepOverAsync(DbgDotNetEngineStepperFrameInfo fr async Task StepCoreAsync(ThreadMirror thread, DbgCodeRange[] ranges, bool isStepInto) { engine.VerifyMonoDebugThread(); - Debug2.Assert(!(session is null)); + Debug2.Assert(session is not null); var method = GetFrame(thread)?.Method; - Debug2.Assert(!(method is null)); + Debug2.Assert(method is not null); if (method is null) throw new StepErrorException("Internal error"); @@ -136,7 +136,7 @@ async Task StepCoreAsync(ThreadMirror thread, DbgCodeRange[] ranges, Task StepCore2Async(ThreadMirror thread, DbgCodeRange[] ranges, bool isStepInto) { engine.VerifyMonoDebugThread(); - Debug2.Assert(!(session is null)); + Debug2.Assert(session is not null); var tcs = new TaskCompletionSource(); var stepReq = engine.CreateStepRequest(thread, e => { if (engine.IsClosed || e.Canceled) @@ -158,7 +158,7 @@ Task StepCore2Async(ThreadMirror thread, DbgCodeRange[] ranges, bo public override Task StepOutAsync(DbgDotNetEngineStepperFrameInfo frame) { engine.VerifyMonoDebugThread(); - Debug2.Assert(!(session is null)); + Debug2.Assert(session is not null); var frameImpl = (DbgDotNetEngineStepperFrameInfoImpl)frame; var tcs = new TaskCompletionSource(); var stepReq = engine.CreateStepRequest(frameImpl.MonoThread, e => { @@ -168,7 +168,7 @@ public override Task StepOutAsync(DbgDotNetEngineStepperFrameInfo fra tcs.SetException(new ForciblyCanceledException(forciblyCanceledErrorMessage)); else { var thread = engine.TryGetThread(frameImpl.MonoThread); - if (!(thread is null)) + if (thread is not null) tcs.SetResult(thread); else tcs.SetException(new InvalidOperationException()); @@ -224,7 +224,7 @@ void CancelStepper(SessionBase? session) { var sessionImpl = (SessionImpl)session; var stepper = sessionImpl.MonoStepper; sessionImpl.MonoStepper = null; - if (!(stepper is null)) + if (stepper is not null) engine.CancelStepper(stepper); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/DbgBreakpointLocationFormatterProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/DbgBreakpointLocationFormatterProviderImpl.cs index fc505a20f0..8ef9c8427d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/DbgBreakpointLocationFormatterProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/DbgBreakpointLocationFormatterProviderImpl.cs @@ -36,7 +36,7 @@ sealed class DbgBreakpointLocationFormatterProviderImpl : DbgBreakpointLocationF switch (location) { case DbgDotNetCodeLocationImpl loc: var formatter = loc.Formatter; - if (!(formatter is null)) + if (formatter is not null) return formatter; formatter = breakpointFormatterService.Value.Create(loc); loc.Formatter = formatter; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/ClassBreakpointCommands.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/ClassBreakpointCommands.cs index 0e46e171b0..ad922fd2b5 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/ClassBreakpointCommands.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/ClassBreakpointCommands.cs @@ -78,7 +78,7 @@ public void Add(MethodDef[] methods, bool tracepoint) { existing.Add(location); list.Add(new DbgCodeBreakpointInfo(location, settings)); } - if (!(objsToClose is null)) + if (objsToClose is not null) dbgManager.Value.Close(objsToClose); dbgCodeBreakpointsService.Value.Add(list.ToArray()); } @@ -102,8 +102,8 @@ protected MenuItemCommon(Lazy methodBreakpointsService this.guid = Guid.Parse(guid); } - public override bool IsVisible(IMenuItemContext context) => !(GetTypeRef(context, guid) is null); - public override bool IsEnabled(IMenuItemContext context) => !(GetTypeRef(context, guid) is null); + public override bool IsVisible(IMenuItemContext context) => GetTypeRef(context, guid) is not null; + public override bool IsEnabled(IMenuItemContext context) => GetTypeRef(context, guid) is not null; public override void Execute(IMenuItemContext context) { var type = GetTypeRef(context, guid)?.ResolveTypeDef(); @@ -171,7 +171,7 @@ static IEnumerable GetReferences(IMenuItemContext context, Gui yield break; var @ref = context.Find(); - if (!(@ref is null)) { + if (@ref is not null) { var realRef = @ref.Reference; if (realRef is Parameter) realRef = ((Parameter)realRef).ParamDef; @@ -182,7 +182,7 @@ static IEnumerable GetReferences(IMenuItemContext context, Gui } var nodes = context.Find(); - if (!(nodes is null) && nodes.Length != 0) { + if (nodes is not null && nodes.Length != 0) { foreach (var node in nodes) { if (node is IMDTokenNode tokenNode && tokenNode.Reference is IMDTokenProvider tokenProvider) yield return tokenProvider; @@ -208,11 +208,11 @@ static IEnumerable GetReferences(IMenuItemContext context, Gui } case EventDef evt: - if (!(evt.AddMethod is null)) + if (evt.AddMethod is not null) methods.Add(evt.AddMethod); - if (!(evt.RemoveMethod is null)) + if (evt.RemoveMethod is not null) methods.Add(evt.RemoveMethod); - if (!(evt.InvokeMethod is null)) + if (evt.InvokeMethod is not null) methods.Add(evt.InvokeMethod); methods.AddRange(evt.OtherMethods); break; @@ -233,14 +233,14 @@ protected MenuItemCommon(Lazy methodBreakpointsService this.guid = Guid.Parse(guid); } - public override bool IsVisible(IMenuItemContext context) => !(GetMethodReferences(context, guid) is null); - public override bool IsEnabled(IMenuItemContext context) => !(GetMethodReferences(context, guid) is null); + public override bool IsVisible(IMenuItemContext context) => GetMethodReferences(context, guid) is not null; + public override bool IsEnabled(IMenuItemContext context) => GetMethodReferences(context, guid) is not null; public override void Execute(IMenuItemContext context) { var methodRefs = GetMethodReferences(context, guid); if (methodRefs is null) return; - methodBreakpointsService.Value.Add(methodRefs.Select(a => a.ResolveMethodDef()).Where(a => !(a is null)).ToArray(), tracepoint); + methodBreakpointsService.Value.Add(methodRefs.Select(a => a.ResolveMethodDef()).Where(a => a is not null).ToArray(), tracepoint); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/DbgBreakpointGlyphFormatterImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/DbgBreakpointGlyphFormatterImpl.cs index 0976c1a846..1a75e6377b 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/DbgBreakpointGlyphFormatterImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/DbgBreakpointGlyphFormatterImpl.cs @@ -81,10 +81,10 @@ bool WriteLocation(IDbgTextWriter output, ITextView textView, SnapshotSpan span, } var documentViewer = textView.TextBuffer.TryGetDocumentViewer(); - Debug2.Assert(!(documentViewer is null)); + Debug2.Assert(documentViewer is not null); var statement = documentViewer?.GetMethodDebugService().FindByCodeOffset(new ModuleTokenId(location.Module, location.Token), location.Offset); - Debug2.Assert((!(documentViewer is null)) == (!(statement is null))); - if (!(statement is null)) { + Debug2.Assert((documentViewer is not null) == (statement is not null)); + if (statement is not null) { output.Write(DbgTextColor.Text, " ('"); var decompiler = (documentViewer?.DocumentTab?.Content as IDecompilerTabContent)?.Decompiler ?? decompilerService.Decompiler; decompiler.Write(new DbgTextColorWriter(output), statement.Value.Method, FormatterOptions.Default); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/DeleteBreakpointsInRemovedModules.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/DeleteBreakpointsInRemovedModules.cs index fceecd6a91..54875dba03 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/DeleteBreakpointsInRemovedModules.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Breakpoints/Code/TextEditor/DeleteBreakpointsInRemovedModules.cs @@ -55,7 +55,7 @@ void Initialize_UI() { } void DocumentTabService_FileCollectionChanged(object? sender, NotifyDocumentCollectionChangedEventArgs e) { - Debug2.Assert(!(dbgCodeBreakpointsService is null)); + Debug2.Assert(dbgCodeBreakpointsService is not null); if (dbgCodeBreakpointsService is null) return; switch (e.Type) { @@ -87,7 +87,7 @@ void DocumentTabService_FileCollectionChanged(object? sender, NotifyDocumentColl breakpointsToRemove.Add(bp); } } - if (!(breakpointsToRemove is null)) + if (breakpointsToRemove is not null) dbgCodeBreakpointsService.Remove(breakpointsToRemove.ToArray()); break; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgCodeLocationSerializerImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgCodeLocationSerializerImpl.cs index d6ac0dd2c9..5c8fc4a68a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgCodeLocationSerializerImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgCodeLocationSerializerImpl.cs @@ -63,7 +63,7 @@ public override void Serialize(ISettingsSection section, DbgCodeLocation locatio state.MethodAsString = GetMethodAsString(loc.Module, loc.Token); state.Initialized = true; } - if (!(state.MethodAsString is null)) + if (state.MethodAsString is not null) section.Attribute("Method", state.MethodAsString); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgDotNetDebugInfoServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgDotNetDebugInfoServiceImpl.cs index 15e8ad4ac8..fd24af5e25 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgDotNetDebugInfoServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgDotNetDebugInfoServiceImpl.cs @@ -90,7 +90,7 @@ MethodDebugInfoResult TryGetMethodDebugInfo_UI(DbgModule module, uint token) { DbgMethodDebugInfo? debugInfo; DbgMethodDebugInfo? stateMachineDebugInfo = null; int methodVersion; - if (!(decompilerDebugInfo is null)) { + if (decompilerDebugInfo is not null) { methodVersion = 1; debugInfo = DbgMethodDebugInfoUtils.ToDbgMethodDebugInfo(decompilerDebugInfo); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgDotNetDecompilerServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgDotNetDecompilerServiceImpl.cs index 99f60b2048..bbe1a590e3 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgDotNetDecompilerServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgDotNetDecompilerServiceImpl.cs @@ -53,7 +53,7 @@ void DbgLanguageService_LanguageChanged(object? sender, DbgLanguageChangedEventA Guid GetDecompilerGuid(DbgLanguage language) { foreach (var lz in dbgDotNetDecompilerGuidProviders) { var guid = lz.Value.GetDecompilerGuid(language); - if (!(guid is null)) + if (guid is not null) return guid.Value; } return DecompilerConstants.LANGUAGE_CSHARP; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgMethodDebugInfoProvider.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgMethodDebugInfoProvider.cs index cff0266c88..d87df9ab9a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgMethodDebugInfoProvider.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DbgMethodDebugInfoProvider.cs @@ -111,7 +111,7 @@ sealed class RuntimeState { } MethodDebugInfoResult GetMethodDebugInfo(DbgRuntime runtime, in MethodDebugInfoResultKey key, IDecompiler decompiler, ModuleDef? mdModule, uint token, CancellationToken cancellationToken) { - Debug2.Assert(!(mdModule is null)); + Debug2.Assert(mdModule is not null); if (mdModule is null) return default; @@ -122,8 +122,8 @@ MethodDebugInfoResult GetMethodDebugInfo(DbgRuntime runtime, in MethodDebugInfoR for (int i = debugInfos.Count - 1; i >= 0; i--) { var info = debugInfos[i]; if (info.key.Equals(key)) { - if ((!(info.result.DebugInfo is null) && info.result.DebugInfo.DebugInfoVersion != decompiler.Settings.Version) || - (!(info.result.StateMachineDebugInfo is null) && info.result.StateMachineDebugInfo.DebugInfoVersion != decompiler.Settings.Version)) { + if ((info.result.DebugInfo is not null && info.result.DebugInfo.DebugInfoVersion != decompiler.Settings.Version) || + (info.result.StateMachineDebugInfo is not null && info.result.StateMachineDebugInfo.DebugInfoVersion != decompiler.Settings.Version)) { debugInfos.RemoveAt(i); continue; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DecompilerOutputImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DecompilerOutputImpl.cs index d03420f607..fbe6e2dede 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DecompilerOutputImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DecompilerOutputImpl.cs @@ -47,8 +47,8 @@ internal void Clear() { public void Initialize(uint methodToken) => this.methodToken = methodToken; public (DbgMethodDebugInfo debugInfo, DbgMethodDebugInfo? stateMachineDebugInfo) TryGetMethodDebugInfo() { - if (!(methodDebugInfo is null)) { - if (!(kickoffMethodDebugInfo is null)) + if (methodDebugInfo is not null) { + if (kickoffMethodDebugInfo is not null) return (kickoffMethodDebugInfo, methodDebugInfo); return (methodDebugInfo, null); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DotNetReferenceNavigator.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DotNetReferenceNavigator.cs index 9ece4a8613..a3eab2ab42 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DotNetReferenceNavigator.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Code/DotNetReferenceNavigator.cs @@ -104,7 +104,7 @@ bool GoTo(DotNetTokenReference tokenRef, ReadOnlyCollection options) { if (def is null) return false; - bool found = !(documentTabService.DocumentTreeView.FindNode(def.Module) is null); + bool found = documentTabService.DocumentTreeView.FindNode(def.Module) is not null; if (found) { documentTabService.FollowReference(def, newTab, true, e => { Debug.Assert(e.Tab.UIContext is IDocumentViewer); @@ -145,7 +145,7 @@ public override void GoToLocation(IDocumentTab tab, MethodDef method, ModuleToke if (offset == EPILOG) { specialIpOffset = true; var mod = dbgMetadataService.Value.TryGetMetadata(module.Module, DbgLoadModuleOptions.AutoLoaded); - if (mod?.ResolveToken(module.Token) is MethodDef md && !(md.Body is null) && md.Body.Instructions.Count > 0) + if (mod?.ResolveToken(module.Token) is MethodDef md && md.Body is not null && md.Body.Instructions.Count > 0) offset = md.Body.Instructions[md.Body.Instructions.Count - 1].Offset; else return; @@ -207,7 +207,7 @@ static bool MoveCaretTo(IDocumentViewer documentViewer, ModuleTokenId module, ui static bool VerifyAndGetCurrentDebuggedMethod(IDocumentViewer documentViewer, ModuleTokenId token, out IMethodDebugService methodDebugService) { methodDebugService = documentViewer.GetMethodDebugService(); - return !(methodDebugService.TryGetMethodDebugInfo(token) is null); + return methodDebugService.TryGetMethodDebugInfo(token) is not null; } void RefreshMethodBodies(IDocumentViewer documentViewer, MethodDef method, ModuleTokenId module, uint offset, bool specialIpOffset, bool newTab) { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DbgRuntimeNativeCodeProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DbgRuntimeNativeCodeProviderImpl.cs index a093607089..93415cf00f 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DbgRuntimeNativeCodeProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DbgRuntimeNativeCodeProviderImpl.cs @@ -96,15 +96,15 @@ bool CreateResult(IDbgDotNetRuntime runtime, DbgModule? methodModule, uint metho } IDecompiler? decompiler = decompilerService.Decompiler; - if (!(decompiler is null) && decompiler.GenericGuid == DecompilerConstants.LANGUAGE_IL) + if (decompiler is not null && decompiler.GenericGuid == DecompilerConstants.LANGUAGE_IL) decompiler = null; - bool canShowILCode = (options & DbgNativeCodeOptions.ShowILCode) != 0 && !(ilDecompiler is null); - bool canShowCode = (options & DbgNativeCodeOptions.ShowCode) != 0 && !(decompiler is null); + bool canShowILCode = (options & DbgNativeCodeOptions.ShowILCode) != 0 && ilDecompiler is not null; + bool canShowCode = (options & DbgNativeCodeOptions.ShowCode) != 0 && decompiler is not null; NativeVariableInfo[]? nativeVariableInfo = null; - if (!(methodModule is null) && methodToken != 0 && (canShowILCode || canShowCode) && HasSequencePoints(nativeCode)) { + if (methodModule is not null && methodToken != 0 && (canShowILCode || canShowCode) && HasSequencePoints(nativeCode)) { var module = dbgMetadataService.Value.TryGetMetadata(methodModule, DbgLoadModuleOptions.AutoLoaded); var method = module?.ResolveToken(methodToken) as MethodDef; - if (!(method is null)) { + if (method is not null) { var cancellationToken = CancellationToken.None; ILSourceStatementProvider ilCodeProvider = default; @@ -112,7 +112,7 @@ bool CreateResult(IDbgDotNetRuntime runtime, DbgModule? methodModule, uint metho List? ilOffsets = null; if (canShowILCode) { - Debug2.Assert(!(ilDecompiler is null)); + Debug2.Assert(ilDecompiler is not null); var provider = new DecompiledCodeProvider(ilDecompiler, method, cancellationToken); if (provider.TryDecompile()) ilCodeProvider = provider.CreateILCodeProvider(); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DecompiledCodeProvider.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DecompiledCodeProvider.cs index 1aed06421e..4211295830 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DecompiledCodeProvider.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DecompiledCodeProvider.cs @@ -62,7 +62,7 @@ public bool TryDecompile() { info = TryDecompileCode(method, method.MDToken.Raw, ctx, output); } debugInfo = info.debugInfo; - return !(debugInfo is null); + return debugInfo is not null; } public NativeVariableInfo[] CreateNativeVariableInfo() { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DecompilerOutputImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DecompilerOutputImpl.cs index 028b566ff2..1ed95417bd 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DecompilerOutputImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Disassembly/DecompilerOutputImpl.cs @@ -52,8 +52,8 @@ internal void Clear() { public void Initialize(uint methodToken) => this.methodToken = methodToken; public (MethodDebugInfo debugInfo, MethodDebugInfo? stateMachineDebugInfo) TryGetMethodDebugInfo() { - if (!(methodDebugInfo is null)) { - if (!(kickoffMethodDebugInfo is null)) + if (methodDebugInfo is not null) { + if (kickoffMethodDebugInfo is not null) return (kickoffMethodDebugInfo, methodDebugInfo); return (methodDebugInfo, null); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetEngineValueNodeFactoryService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetEngineValueNodeFactoryService.cs index 10aaaadd67..102fef2727 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetEngineValueNodeFactoryService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetEngineValueNodeFactoryService.cs @@ -71,7 +71,7 @@ sealed class DbgDotNetEngineValueNodeFactoryServiceImpl : DbgDotNetEngineValueNo Debug.Fail($"Default value node factory ({LanguageConstants.DefaultLanguageGuid.ToString()}) wasn't exported"); var lz = toLazyFactory.Values.FirstOrDefault(); - if (!(lz is null)) + if (lz is not null) return GetFactory(formatter, lz); return null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetLanguageServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetLanguageServiceImpl.cs index 1f675998f0..0ce148a329 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetLanguageServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetLanguageServiceImpl.cs @@ -105,7 +105,7 @@ public override IEnumerable CreateLanguages() { else if (decompilerGuid == visualBasicDecompilerGuid) decompilerGuid = DecompilerConstants.LANGUAGE_VISUALBASIC; var decompiler = decompilerService.Find(decompilerGuid); - Debug2.Assert(!(decompiler is null)); + Debug2.Assert(decompiler is not null); if (decompiler is null) continue; @@ -132,7 +132,7 @@ bool TryGetFormatter(string guidString, [NotNullWhen(true)] out Lazy diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetValueCreator.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetValueCreator.cs index 5b0361d9db..bd348a25a7 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetValueCreator.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgDotNetValueCreator.cs @@ -41,14 +41,14 @@ public DbgDotNetValueCreator(DbgDotNetEngineValueNodeFactory valueNodeFactory, D } public DbgEngineValueNode CreateValueNode(ref DbgDotNetILInterpreterState? ilInterpreterState, ref DbgDotNetCompiledExpressionResult compExprInfo) { - if (!(compExprInfo.ErrorMessage is null)) + if (compExprInfo.ErrorMessage is not null) return valueNodeFactory.CreateError(evalInfo, compExprInfo.Name, compExprInfo.ErrorMessage, compExprInfo.Expression, (compExprInfo.Flags & DbgEvaluationResultFlags.SideEffects) != 0); else { if (ilInterpreterState is null) ilInterpreterState = dnILInterpreter.CreateState(assemblyBytes); var res = dnILInterpreter.Execute(evalInfo, ilInterpreterState, compExprInfo.TypeName, compExprInfo.MethodName, options, out var expectedType); try { - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) return valueNodeFactory.CreateError(evalInfo, compExprInfo.Name, res.ErrorMessage, compExprInfo.Expression, (compExprInfo.Flags & DbgEvaluationResultFlags.SideEffects) != 0); //TODO: Pass in compExprInfo.CustomTypeInfo, or attach it to the DbgDotNetValueNode return valueNodeFactory.Create(evalInfo, compExprInfo.Name, res.Value!, compExprInfo.FormatSpecifiers, nodeOptions, compExprInfo.Expression, compExprInfo.ImageName, (compExprInfo.Flags & DbgEvaluationResultFlags.ReadOnly) != 0, (compExprInfo.Flags & DbgEvaluationResultFlags.SideEffects) != 0, expectedType); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineAutosProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineAutosProviderImpl.cs index 14e17f35b0..2b51950bd8 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineAutosProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineAutosProviderImpl.cs @@ -57,7 +57,7 @@ DbgEngineValueNode[] GetNodesCore(DbgEvaluationInfo evalInfo, DbgValueNodeEvalua } } catch (Exception ex) { - evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => !(a is null))); + evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => a is not null)); if (!ExceptionUtils.IsInternalDebuggerError(ex)) throw; return valueNodeFactory.CreateInternalErrorResult(evalInfo); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineExceptionsProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineExceptionsProviderImpl.cs index 99b37439de..3bc99fed56 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineExceptionsProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineExceptionsProviderImpl.cs @@ -62,7 +62,7 @@ DbgEngineValueNode[] GetNodesCore(DbgEvaluationInfo evalInfo, DbgValueNodeEvalua } } catch (Exception ex) { - evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => !(a is null))); + evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => a is not null)); if (!ExceptionUtils.IsInternalDebuggerError(ex)) throw; return valueNodeFactory.CreateInternalErrorResult(evalInfo); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineExpressionEvaluatorImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineExpressionEvaluatorImpl.cs index d1491ade2f..c909a267a3 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineExpressionEvaluatorImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineExpressionEvaluatorImpl.cs @@ -68,7 +68,7 @@ DbgEngineEEAssignmentResult AssignCore(DbgEvaluationInfo evalInfo, string expres try { var info = dbgAliasProvider.GetAliases(evalInfo); var refsResult = dbgModuleReferenceProvider.GetModuleReferences(evalInfo.Runtime, evalInfo.Frame, info.typeReferences); - if (!(refsResult.ErrorMessage is null)) + if (refsResult.ErrorMessage is not null) return new DbgEngineEEAssignmentResult(resultFlags, refsResult.ErrorMessage); var compRes = expressionCompiler.CompileAssignment(evalInfo, refsResult.ModuleReferences!, info.aliases, expression, valueExpression, options); @@ -79,7 +79,7 @@ DbgEngineEEAssignmentResult AssignCore(DbgEvaluationInfo evalInfo, string expres var state = dnILInterpreter.CreateState(compRes.Assembly!); Debug.Assert(compRes.CompiledExpressions!.Length == 1); ref var exprInfo = ref compRes.CompiledExpressions[0]; - if (!(exprInfo.ErrorMessage is null)) + if (exprInfo.ErrorMessage is not null) return new DbgEngineEEAssignmentResult(resultFlags | DbgEEAssignmentResultFlags.CompilerError, exprInfo.ErrorMessage); resultFlags |= DbgEEAssignmentResultFlags.ExecutedCode; var res = dnILInterpreter.Execute(evalInfo, state, exprInfo.TypeName, exprInfo.MethodName, options, out _); @@ -116,9 +116,9 @@ DbgEngineEvaluationResult Evaluate(DbgDotNetDispatcher dispatcher2, DbgEvaluatio DbgEngineEvaluationResult EvaluateCore(DbgEvaluationInfo evalInfo, string expression, DbgEvaluationOptions options, object? state) { var res = EvaluateImpl(evalInfo, expression, options | DbgEvaluationOptions.NoName, state); - if (!(res.Error is null)) + if (res.Error is not null) return new DbgEngineEvaluationResult(res.Error, res.Flags); - Debug2.Assert(!(res.Value is null)); + Debug2.Assert(res.Value is not null); try { return new DbgEngineEvaluationResult(new DbgEngineValueImpl(res.Value), res.FormatSpecifiers, res.Flags); } @@ -234,26 +234,26 @@ static bool Equals(ReadOnlyCollection? a, ReadOnlyCollection? b) { EvaluateImplResult? GetInterpreterStateCommon(DbgEvaluationInfo evalInfo, DmdModule? reflectionModule, int debugInfoVersion, object memberModule, int memberToken, int memberVersion, DbgMethodDebugScope? scope, DbgDotNetAlias[] aliases, DmdType[] typeReferences, DbgEvaluationOptions options, string expression, object? stateObj, DmdType? type, out EvaluateImplExpressionState? evalExprState) { evalExprState = null; EvaluateImplExpressionState? evalState; - if (!(stateObj is null)) { + if (stateObj is not null) { evalState = stateObj as EvaluateImplExpressionState; - Debug2.Assert(!(evalState is null)); + Debug2.Assert(evalState is not null); if (evalState is null) throw new ArgumentException("Invalid expression evaluator state. It must be null or created by " + nameof(DbgExpressionEvaluator) + "." + nameof(DbgExpressionEvaluator.CreateExpressionEvaluatorState) + "()"); } else evalState = evalInfo.Context.GetOrCreateData(); - var refsResult = !(reflectionModule is null) ? + var refsResult = reflectionModule is not null ? dbgModuleReferenceProvider.GetModuleReferences(evalInfo.Runtime, reflectionModule, typeReferences) : dbgModuleReferenceProvider.GetModuleReferences(evalInfo.Runtime, evalInfo.Frame, typeReferences); - if (!(refsResult.ErrorMessage is null)) + if (refsResult.ErrorMessage is not null) return new EvaluateImplResult(refsResult.ErrorMessage, CreateName(expression), null, null, 0, PredefinedDbgValueNodeImageNames.Error, null); var keyOptions = options & ~(DbgEvaluationOptions.NoSideEffects | DbgEvaluationOptions.NoFuncEval); - Debug2.Assert(!(refsResult.ModuleReferences is null)); + Debug2.Assert(refsResult.ModuleReferences is not null); var key = new EvaluateImplExpressionState.Key(this, debugInfoVersion, memberModule, memberToken, memberVersion, refsResult.ModuleReferences, scope, aliases, keyOptions, expression); if (!evalState.CachedKey.Equals(key)) { - evalState.CompilationResult = !(type is null) ? + evalState.CompilationResult = type is not null ? expressionCompiler.CompileTypeExpression(evalInfo, type, refsResult.ModuleReferences, aliases, expression, keyOptions) : expressionCompiler.CompileExpression(evalInfo, refsResult.ModuleReferences, aliases, expression, keyOptions); evalState.CachedKey = key; @@ -275,7 +275,7 @@ static bool Equals(ReadOnlyCollection? a, ReadOnlyCollection? b) { if (compRes.CompiledExpressions.Length != 1) return new EvaluateImplResult(PredefinedEvaluationErrorMessages.InternalDebuggerError, CreateName(expression), null, null, 0, PredefinedDbgValueNodeImageNames.Error, null); var exprInfo = compRes.CompiledExpressions[0]; - if (!(exprInfo.ErrorMessage is null)) + if (exprInfo.ErrorMessage is not null) return new EvaluateImplResult(exprInfo.ErrorMessage, exprInfo.Name, null, exprInfo.FormatSpecifiers, exprInfo.Flags & ~DbgEvaluationResultFlags.SideEffects, exprInfo.ImageName, null); return null; @@ -287,7 +287,7 @@ static bool HasAllowFuncEval(ReadOnlyCollection? formatSpecifiers) => internal EvaluateImplResult EvaluateImpl(DbgEvaluationInfo evalInfo, string expression, DbgEvaluationOptions options, object? stateObj) { try { var errorRes = GetMethodInterpreterState(evalInfo, expression, options, stateObj, out var state); - if (!(errorRes is null)) + if (errorRes is not null) return errorRes.Value; Debug.Assert(state!.CompilationResult.CompiledExpressions!.Length == 1); @@ -325,7 +325,7 @@ DbgDotNetEvalResult Evaluate2(DbgDotNetDispatcher dispatcher2, DbgEvaluationInfo DbgDotNetEvalResult EvaluateCore(DbgEvaluationInfo evalInfo, DbgDotNetValue obj, string expression, DbgEvaluationOptions options, object? state) { var res = EvaluateImpl(evalInfo, obj, expression, options, state); - if (!(res.Error is null)) + if (res.Error is not null) return new DbgDotNetEvalResult(predefinedEvaluationErrorMessagesHelper.GetErrorMessage(res.Error), res.FormatSpecifiers, res.Flags); return new DbgDotNetEvalResult(res.Value!, res.FormatSpecifiers, res.Flags); } @@ -336,7 +336,7 @@ EvaluateImplResult EvaluateImpl(DbgEvaluationInfo evalInfo, DbgDotNetValue obj, if (type.IsGenericType) type = type.GetGenericTypeDefinition(); var errorRes = GetTypeInterpreterState(evalInfo, type, expression, options | DbgEvaluationOptions.NoName, stateObj, out var state); - if (!(errorRes is null)) + if (errorRes is not null) return errorRes.Value; var genericTypeArguments = obj.Type.GetGenericArguments(); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineLanguageImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineLanguageImpl.cs index ae2f6765f0..22a87ad1cb 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineLanguageImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineLanguageImpl.cs @@ -118,7 +118,7 @@ sealed class RuntimeState { } public override void InitializeContext(DbgEvaluationContext context, DbgCodeLocation? location, CancellationToken cancellationToken) { - Debug2.Assert(!(context.Runtime.GetDotNetRuntime() is null)); + Debug2.Assert(context.Runtime.GetDotNetRuntime() is not null); IDebuggerDisplayAttributeEvaluatorUtils.Initialize(context, debuggerDisplayAttributeEvaluator); // Needed by DebuggerRuntimeImpl (calls expressionCompiler.TryGetAliasInfo()) @@ -127,7 +127,7 @@ public override void InitializeContext(DbgEvaluationContext context, DbgCodeLoca if ((context.Options & DbgEvaluationContextOptions.NoMethodBody) == 0 && location is IDbgDotNetCodeLocation loc) { var state = StateWithKey.GetOrCreate(context.Runtime, decompiler); var debugInfo = GetOrCreateDebugInfo(context, state, loc, cancellationToken); - if (!(debugInfo is null)) + if (debugInfo is not null) DbgLanguageDebugInfoExtensions.SetLanguageDebugInfo(context, debugInfo); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineLocalsProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineLocalsProviderImpl.cs index 2b0792e6be..85ebf082e8 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineLocalsProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineLocalsProviderImpl.cs @@ -146,9 +146,9 @@ DbgEngineLocalsValueNodeInfo[] GetNodesCore(DbgEvaluationInfo evalInfo, DbgValue // in the same arguments so it won't get recreated every time the method gets called. var info = dbgAliasProvider.GetAliases(evalInfo); var refsResult = dbgModuleReferenceProvider.GetModuleReferences(evalInfo.Runtime, evalInfo.Frame, info.typeReferences); - if (!(refsResult.ErrorMessage is null)) + if (refsResult.ErrorMessage is not null) return new[] { CreateInternalErrorNode(evalInfo, refsResult.ErrorMessage) }; - Debug2.Assert(!(refsResult.ModuleReferences is null)); + Debug2.Assert(refsResult.ModuleReferences is not null); // Since we attach this to the module, the module doesn't have to be part of Key var state = StateWithKey.GetOrCreate(module, this); @@ -272,8 +272,8 @@ DbgEngineLocalsValueNodeInfo[] GetNodesCore(DbgEvaluationInfo evalInfo, DbgValue return valueNodes; } catch (Exception ex) { - if (!(valueNodes is null)) - evalInfo.Runtime.Process.DbgManager.Close(valueNodes.Select(a => a.ValueNode).Where(a => !(a is null))); + if (valueNodes is not null) + evalInfo.Runtime.Process.DbgManager.Close(valueNodes.Select(a => a.ValueNode).Where(a => a is not null)); if (!ExceptionUtils.IsInternalDebuggerError(ex)) throw; return new[] { CreateInternalErrorNode(evalInfo, PredefinedEvaluationErrorMessages.InternalDebuggerError) }; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineReturnValuesProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineReturnValuesProviderImpl.cs index 03c0238d43..2d0672d253 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineReturnValuesProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineReturnValuesProviderImpl.cs @@ -59,7 +59,7 @@ DbgEngineValueNode[] GetNodesCore(DbgEvaluationInfo evalInfo, DbgValueNodeEvalua } } catch (Exception ex) { - evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => !(a is null))); + evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => a is not null)); if (!ExceptionUtils.IsInternalDebuggerError(ex)) throw; return valueNodeFactory.CreateInternalErrorResult(evalInfo); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineValueNodeFactoryImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineValueNodeFactoryImpl.cs index fb500afe5a..a6c20ee7ea 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineValueNodeFactoryImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineValueNodeFactoryImpl.cs @@ -60,7 +60,7 @@ DbgEngineValueNode[] CreateCore(DbgEvaluationInfo evalInfo, DbgExpressionEvaluat var evalRes = expressionEvaluator.EvaluateImpl(evalInfo, info.Expression, info.Options, info.ExpressionEvaluatorState); bool causesSideEffects = (evalRes.Flags & DbgEvaluationResultFlags.SideEffects) != 0; DbgEngineValueNode newNode; - if (!(evalRes.Error is null)) + if (evalRes.Error is not null) newNode = valueNodeFactory.CreateError(evalInfo, evalRes.Name, evalRes.Error, info.Expression, causesSideEffects); else { bool isReadOnly = (evalRes.Flags & DbgEvaluationResultFlags.ReadOnly) != 0; @@ -70,7 +70,7 @@ DbgEngineValueNode[] CreateCore(DbgEvaluationInfo evalInfo, DbgExpressionEvaluat } } catch (Exception ex) { - evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => !(a is null))); + evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => a is not null)); if (!ExceptionUtils.IsInternalDebuggerError(ex)) throw; return valueNodeFactory.CreateInternalErrorResult(evalInfo); @@ -115,7 +115,7 @@ DbgEngineValueNode[] CreateCore(DbgEvaluationInfo evalInfo, DbgEngineObjectId[] return res; } catch (Exception ex) { - evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => !(a is null))); + evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => a is not null)); objectIdValue?.Dispose(); if (!ExceptionUtils.IsInternalDebuggerError(ex)) throw; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineValueNodeImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineValueNodeImpl.cs index bdf3c3ffd3..b9306be4dd 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineValueNodeImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgEngineValueNodeImpl.cs @@ -92,9 +92,9 @@ DbgEngineValueNode[] GetChildrenCore(DbgEvaluationInfo evalInfo, ulong index, in } } catch (Exception ex) { - if (!(res is null)) - evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => !(a is null))); - if (!(dnNodes is null)) + if (res is not null) + evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => a is not null)); + if (dnNodes is not null) evalInfo.Runtime.Process.DbgManager.Close(dnNodes); if (!ExceptionUtils.IsInternalDebuggerError(ex)) throw; @@ -123,7 +123,7 @@ void FormatCore(DbgEvaluationInfo evalInfo, IDbgValueNodeFormatParameters option DbgValueFormatterTypeOptions typeFormatterOptions; var formatter = owner.Formatter; var dnValue = value?.DotNetValue; - if (!(options.NameOutput is null)) { + if (options.NameOutput is not null) { formatterOptions = PredefinedFormatSpecifiers.GetValueFormatterOptions(dnValueNode.FormatSpecifiers, options.NameFormatterOptions); if (dnValueNode.FormatName(evalInfo, options.NameOutput, formatter, formatterOptions, cultureInfo)) { // Nothing @@ -132,7 +132,7 @@ void FormatCore(DbgEvaluationInfo evalInfo, IDbgValueNodeFormatParameters option dnValueNode.Name.WriteTo(options.NameOutput); evalInfo.CancellationToken.ThrowIfCancellationRequested(); } - if (!(options.ExpectedTypeOutput is null)) { + if (options.ExpectedTypeOutput is not null) { formatterOptions = PredefinedFormatSpecifiers.GetValueFormatterOptions(dnValueNode.FormatSpecifiers, options.TypeFormatterOptions); typeFormatterOptions = PredefinedFormatSpecifiers.GetValueFormatterTypeOptions(dnValueNode.FormatSpecifiers, options.ExpectedTypeFormatterOptions); if (dnValueNode.FormatExpectedType(evalInfo, options.ExpectedTypeOutput, formatter, typeFormatterOptions, formatterOptions, cultureInfo)) { @@ -142,7 +142,7 @@ void FormatCore(DbgEvaluationInfo evalInfo, IDbgValueNodeFormatParameters option formatter.FormatType(evalInfo, options.ExpectedTypeOutput, expectedType, null, typeFormatterOptions, cultureInfo); evalInfo.CancellationToken.ThrowIfCancellationRequested(); } - if (!(options.ActualTypeOutput is null)) { + if (options.ActualTypeOutput is not null) { formatterOptions = PredefinedFormatSpecifiers.GetValueFormatterOptions(dnValueNode.FormatSpecifiers, options.TypeFormatterOptions); typeFormatterOptions = PredefinedFormatSpecifiers.GetValueFormatterTypeOptions(dnValueNode.FormatSpecifiers, options.ActualTypeFormatterOptions); if (dnValueNode.FormatActualType(evalInfo, options.ActualTypeOutput, formatter, typeFormatterOptions, formatterOptions, cultureInfo)) { @@ -152,12 +152,12 @@ void FormatCore(DbgEvaluationInfo evalInfo, IDbgValueNodeFormatParameters option formatter.FormatType(evalInfo, options.ActualTypeOutput, actualType, dnValue, typeFormatterOptions, cultureInfo); evalInfo.CancellationToken.ThrowIfCancellationRequested(); } - if (!(options.ValueOutput is null)) { + if (options.ValueOutput is not null) { formatterOptions = PredefinedFormatSpecifiers.GetValueFormatterOptions(dnValueNode.FormatSpecifiers, options.ValueFormatterOptions); if (dnValueNode.FormatValue(evalInfo, options.ValueOutput, formatter, formatterOptions, cultureInfo)) { // Nothing } - else if (!(dnValue is null)) + else if (dnValue is not null) formatter.FormatValue(evalInfo, options.ValueOutput, dnValue, formatterOptions, cultureInfo); else if (ErrorMessage is string errorMessage) options.ValueOutput.Write(DbgTextColor.Error, owner.ErrorMessagesHelper.GetErrorMessage(errorMessage)); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgModuleReferenceProvider.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgModuleReferenceProvider.cs index 698b41fe29..55b839feb4 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgModuleReferenceProvider.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/DbgModuleReferenceProvider.cs @@ -302,7 +302,7 @@ void InitializeState(DbgRuntime runtime, DmdModule sourceModule, DmdType[] typeR foreach (var modInfo in info.Modules) { foreach (var asmRef in modInfo.Module.GetReferencedAssemblies()) { var asm = appDomain.GetAssembly(asmRef); - if (!(asm is null)) { + if (asm is not null) { if (!hash.Contains(asm)) stack.Add(new AssemblyInfo(asm)); } @@ -373,21 +373,21 @@ static bool Equals(DbgModuleReference[]? a, List b) { } } } - if (!(modRef is null)) { + if (modRef is not null) { modRef.Update(module.RefreshedVersion); return modRef; } } - if (!(module is null) && !module.IsDynamic && !module.IsInMemory && File.Exists(module.Filename)) { + if (module is not null && !module.IsDynamic && !module.IsInMemory && File.Exists(module.Filename)) { modRef = GetOrCreateFileModuleReference(rtState, runtime, modInfo, module); - if (!(modRef is null)) + if (modRef is not null) return modRef; } - if (!(module is null)) { + if (module is not null) { var info = runtime.GetDotNetRuntime().GetRawModuleBytes(module); - if (!(info.RawBytes is null)) { + if (info.RawBytes is not null) { var state = module.GetOrCreateData(); if (state.Equals(info)) return state.ModuleReference; @@ -467,7 +467,7 @@ bool CanReuse(DmdAppDomain appDomain, DmdType[] typeReferences, ModuleReferences } foreach (var asmRef in state.NonLoadedAssemblies) { - if (!(appDomain.GetAssembly(asmRef) is null)) + if (appDomain.GetAssembly(asmRef) is not null) return false; } @@ -493,7 +493,7 @@ static bool Equals(DmdModule[] a, ModuleInfo[] b) { if (am != info.Module || am.DynamicModuleVersion != info.DynamicModuleVersion) return false; var dm = info.DebuggerModule ?? am.GetDebuggerModule(); - if (!(dm is null) && dm.RefreshedVersion != info.DebuggerModuleVersion) + if (dm is not null && dm.RefreshedVersion != info.DebuggerModuleVersion) return false; } return true; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/ArrayILValue.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/ArrayILValue.cs index 5301d91ef0..5b455c1001 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/ArrayILValue.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/ArrayILValue.cs @@ -38,7 +38,7 @@ public ArrayILValue(DebuggerRuntimeImpl runtime, DbgDotNetValue arrayValue) } void InitializeArrayInfo() { - if (!(dimensionInfos is null)) + if (dimensionInfos is not null) return; if (!ObjValue.GetArrayInfo(out elementCount, out dimensionInfos)) throw new InvalidOperationException(); @@ -48,7 +48,7 @@ public override bool Call(bool isCallvirt, DmdMethodBase method, ILValue[] argum switch (method.SpecialMethodKind) { case DmdSpecialMethodKind.Array_Get: returnValue = LoadArrayElement(GetZeroBasedIndex(arguments, arguments.Length)); - return !(returnValue is null); + return returnValue is not null; case DmdSpecialMethodKind.Array_Set: StoreArrayElement(GetZeroBasedIndex(arguments, arguments.Length - 1), arguments[arguments.Length - 1]); @@ -58,7 +58,7 @@ public override bool Call(bool isCallvirt, DmdMethodBase method, ILValue[] argum case DmdSpecialMethodKind.Array_Address: uint index = GetZeroBasedIndex(arguments, arguments.Length); var addrValue = ObjValue.GetArrayElementAddressAt(index); - if (!(addrValue is null)) { + if (addrValue is not null) { runtime.RecordValue(addrValue.Value); Debug.Assert(addrValue.Value.Value!.Type.IsByRef); returnValue = new ByRefILValueImpl(runtime, addrValue.Value.Value); @@ -123,7 +123,7 @@ public override bool StoreSZArrayElement(LoadValueType loadValueType, long index if ((ulong)index > uint.MaxValue) return null; var addrValue = ObjValue.GetArrayElementAddressAt((uint)index); - if (!(addrValue is null)) { + if (addrValue is not null) { runtime.RecordValue(addrValue.Value); Debug.Assert(addrValue.Value.Value!.Type.IsByRef); return new ByRefILValueImpl(runtime, addrValue.Value.Value); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/DebuggerRuntimeImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/DebuggerRuntimeImpl.cs index 80987117fd..dbbe1826a3 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/DebuggerRuntimeImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/DebuggerRuntimeImpl.cs @@ -64,15 +64,15 @@ public DebuggerRuntimeImpl(DbgObjectIdService dbgObjectIdService, IDbgDotNetRunt classHooks = new Dictionary(DmdTypeNameEqualityComparer.Instance); foreach (var factory in dotNetClassHookFactories) { foreach (var info in factory.Create(this)) { - Debug2.Assert(!(info.Hook is null)); + Debug2.Assert(info.Hook is not null); if (info.WellKnownType is null && info.TypeName is null) anyClassHooksList.Add(info.Hook); else { DmdTypeName typeName; - if (!(info.WellKnownType is null)) + if (info.WellKnownType is not null) typeName = DmdWellKnownTypeUtils.GetTypeName(info.WellKnownType.Value); else { - Debug2.Assert(!(info.TypeName is null)); + Debug2.Assert(info.TypeName is not null); typeName = info.TypeName.Value; } Debug.Assert(!classHooks.ContainsKey(typeName)); @@ -94,7 +94,7 @@ public DebuggerRuntimeImpl(DbgObjectIdService dbgObjectIdService, IDbgDotNetRunt public override void Initialize(DbgEvaluationInfo evalInfo, DmdMethodBody? realMethodBody, VariablesProvider? argumentsProvider, VariablesProvider? localsProvider, bool canFuncEval) { Debug2.Assert(this.evalInfo is null); - if (!(this.evalInfo is null)) + if (this.evalInfo is not null) throw new InvalidOperationException(); this.evalInfo = evalInfo; this.canFuncEval = canFuncEval; @@ -111,7 +111,7 @@ public override void Initialize(DmdMethodBase method, DmdMethodBody body) { public override void Clear(DbgDotNetValue? returnValue) { evalInfo = null!; canFuncEval = false; - Debug2.Assert(!(argumentsProvider is null)); + Debug2.Assert(argumentsProvider is not null); foreach (var v in valuesToDispose) { if (v != returnValue && argumentsProvider.CanDispose(v) && interpreterLocalsProvider.CanDispose(v)) v.Dispose(); @@ -125,14 +125,14 @@ public override void Clear(DbgDotNetValue? returnValue) { public override DbgDotNetValue GetDotNetValue(ILValue value, DmdType? targetType = null) { targetType ??= value.Type; var dnValue = TryGetDotNetValue(value, value.IsNull ? targetType : value.Type, canCreateValue: true); - if (!(dnValue is null)) + if (dnValue is not null) return dnValue; throw new InvalidOperationException();//TODO: } DbgDotNetValue? TryCreateSyntheticValue(DmdType type, object? value) { var dnValue = SyntheticValueFactory.TryCreateSyntheticValue(type, value); - if (!(dnValue is null)) + if (dnValue is not null) RecordValue(dnValue); return dnValue; } @@ -214,9 +214,9 @@ public override DbgDotNetValue GetDotNetValue(ILValue value, DmdType? targetType newValue = null; break; } - if (!(newValue is null)) { + if (newValue is not null) { var dnValue = TryCreateSyntheticValue(type!, newValue); - if (!(dnValue is null)) + if (dnValue is not null) return dnValue; return RecordValue(runtime.CreateValue(evalInfo, newValue)); } @@ -226,7 +226,7 @@ public override DbgDotNetValue GetDotNetValue(ILValue value, DmdType? targetType internal object? GetDebuggerValue(ILValue value, DmdType targetType) { var dnValue = TryGetDotNetValue(value, targetType, canCreateValue: false); - if (!(dnValue is null)) + if (dnValue is not null) return dnValue; if (value.IsNull) @@ -318,7 +318,7 @@ internal DbgDotNetValue RecordValue(DbgDotNetValueResult result) { internal DbgDotNetValue RecordValue(DbgDotNetValue value) { try { evalInfo.CancellationToken.ThrowIfCancellationRequested(); - Debug2.Assert(!(value is null)); + Debug2.Assert(value is not null); valuesToDispose.Add(value); return value; } @@ -330,7 +330,7 @@ internal DbgDotNetValue RecordValue(DbgDotNetValue value) { internal ILValue CreateILValue(DbgDotNetValue value) { try { - Debug2.Assert(!(value is null)); + Debug2.Assert(value is not null); valuesToDispose.Add(value); return CreateILValueCore(value); } @@ -419,7 +419,7 @@ ILValue CreateILValueCore(DbgDotNetValue value) { public override ILValue? LoadArgumentAddress(int index, DmdType type) { var addrValue = argumentsProvider.GetValueAddress(index, type); - if (!(addrValue is null)) { + if (addrValue is not null) { Debug.Assert(addrValue.Type.IsByRef); return new ByRefILValueImpl(this, RecordValue(addrValue)); } @@ -428,7 +428,7 @@ ILValue CreateILValueCore(DbgDotNetValue value) { public override ILValue? LoadLocalAddress(int index, DmdType type) { var addrValue = interpreterLocalsProvider.GetValueAddress(index, type); - if (!(addrValue is null)) { + if (addrValue is not null) { Debug.Assert(addrValue.Type.IsByRef); return new ByRefILValueImpl(this, RecordValue(addrValue)); } @@ -439,7 +439,7 @@ ILValue CreateILValueCore(DbgDotNetValue value) { internal bool StoreArgument2(int index, DmdType targetType, object? value) { var error = SetArgument(index, targetType, value); - if (!(error is null)) + if (error is not null) throw new InterpreterMessageException(error); return true; } @@ -448,7 +448,7 @@ internal bool StoreArgument2(int index, DmdType targetType, object? value) { internal bool StoreLocal2(int index, DmdType targetType, object? value) { var error = SetLocal(index, targetType, value); - if (!(error is null)) + if (error is not null) throw new InterpreterMessageException(error); return true; } @@ -509,7 +509,7 @@ internal DbgDotNetValue GetDefaultValue(DmdType type) { if (!type.IsValueType) return new SyntheticNullValue(type); var dnValue = TryCreateDefaultValue(type); - if (!(dnValue is null)) + if (dnValue is not null) return dnValue; if (!canFuncEval) throw new InterpreterMessageException(PredefinedEvaluationErrorMessages.FuncEvalDisabled); @@ -518,7 +518,7 @@ internal DbgDotNetValue GetDefaultValue(DmdType type) { public override ILValue? CreateTypeNoConstructor(DmdType type) { var dnValue = TryCreateDefaultValue(type); - if (!(dnValue is null)) + if (dnValue is not null) return CreateILValue(dnValue); if (!canFuncEval) throw new InterpreterMessageException(PredefinedEvaluationErrorMessages.FuncEvalDisabled); @@ -569,7 +569,7 @@ DbgDotNetValueResult CreateInstanceCore(DmdConstructorInfo ctor, ILValue[] argum const DotNetClassHookCallOptions options = DotNetClassHookCallOptions.None; foreach (var anyHook in anyClassHooks) { var res = anyHook.CreateInstance(options, ctor, arguments); - if (!(res is null)) + if (res is not null) return DbgDotNetValueResult.Create(res); } @@ -583,9 +583,9 @@ DbgDotNetValueResult CreateInstanceCore(DmdConstructorInfo ctor, ILValue[] argum if (type != type.AppDomain.GetWellKnownType(wellKnownType, isOptional: true)) hook = null; } - if (!(hook is null)) { + if (hook is not null) { var res = hook.CreateInstance(options, ctor, arguments); - if (!(res is null)) + if (res is not null) return DbgDotNetValueResult.Create(res); } } @@ -618,7 +618,7 @@ internal DbgDotNetValue LoadStaticField2(DmdFieldInfo field) { public override ILValue? LoadStaticFieldAddress(DmdFieldInfo field) { var addrValue = runtime.LoadFieldAddress(evalInfo, null, field); - if (!(addrValue is null)) { + if (addrValue is not null) { Debug.Assert(addrValue.Type.IsByRef); return new ByRefILValueImpl(this, RecordValue(addrValue)); } @@ -628,7 +628,7 @@ internal DbgDotNetValue LoadStaticField2(DmdFieldInfo field) { public override bool StoreStaticField(DmdFieldInfo field, ILValue value) => StoreStaticField(field, GetDebuggerValue(value, field.FieldType)); internal bool StoreStaticField(DmdFieldInfo field, object? value) { var error = runtime.StoreField(evalInfo, null, field, value); - if (!(error is null)) + if (error is not null) throw new InterpreterMessageException(error); return true; } @@ -647,7 +647,7 @@ internal void SetArrayElementAt(DbgDotNetValue arrayValue, uint index, ILValue v internal void SetArrayElementAt(DbgDotNetValue arrayValue, uint index, object? value) { var error = arrayValue.SetArrayElementAt(evalInfo, index, value); - if (!(error is null)) + if (error is not null) throw new InterpreterMessageException(error); } @@ -659,7 +659,7 @@ internal void SetArrayElementAt(DbgDotNetValue arrayValue, uint index, object? v return laddr.Equals(raddr); if (TryGetDotNetValue(left, canCreateValue: false) is DbgDotNetValue lv && TryGetDotNetValue(right, canCreateValue: false) is DbgDotNetValue rv) { var res = runtime.Equals(lv, rv); - if (!(res is null)) + if (res is not null) return res; } return null; @@ -672,7 +672,7 @@ internal bool Equals(DbgDotNetValue a, DbgDotNetValue b) { return false; var res = runtime.Equals(a, b); - if (!(res is null)) + if (res is not null) return res.Value; return false; @@ -683,7 +683,7 @@ internal bool StoreInstanceField(DbgDotNetValue objValue, DmdFieldInfo field, IL internal bool StoreInstanceField(DbgDotNetValue objValue, DmdFieldInfo field, object? value) { var error = runtime.StoreField(evalInfo, objValue, field, value); - if (!(error is null)) + if (error is not null) throw new InterpreterMessageException(error); return true; } @@ -697,9 +697,9 @@ internal DbgDotNetValue LoadInstanceField2(DbgDotNetValue objValue, DmdFieldInfo internal ILValue LoadValueTypeFieldAddress(AddressILValue objValue, DmdFieldInfo field) { Debug.Assert(field.ReflectedType!.IsValueType); var dnObjValue = TryGetDotNetValue(objValue, canCreateValue: false); - if (!(dnObjValue is null)) { + if (dnObjValue is not null) { var addrValue = runtime.LoadFieldAddress(evalInfo, dnObjValue, field); - if (!(addrValue is null)) { + if (addrValue is not null) { Debug.Assert(addrValue.Type.IsByRef); return new ByRefILValueImpl(this, RecordValue(addrValue)); } @@ -710,7 +710,7 @@ internal ILValue LoadValueTypeFieldAddress(AddressILValue objValue, DmdFieldInfo internal ILValue LoadReferenceTypeFieldAddress(DbgDotNetValue objValue, DmdFieldInfo field) { Debug.Assert(!field.ReflectedType!.IsValueType); var addrValue = runtime.LoadFieldAddress(evalInfo, objValue, field); - if (!(addrValue is null)) { + if (addrValue is not null) { Debug.Assert(addrValue.Type.IsByRef); return new ByRefILValueImpl(this, RecordValue(addrValue)); } @@ -720,7 +720,7 @@ internal ILValue LoadReferenceTypeFieldAddress(DbgDotNetValue objValue, DmdField internal bool StoreIndirect(DbgDotNetValue refValue, object? value) { Debug.Assert(refValue.Type.IsByRef || refValue.Type.IsPointer); var error = refValue.StoreIndirect(evalInfo, value); - if (!(error is null)) + if (error is not null) throw new InterpreterMessageException(error); return true; } @@ -758,7 +758,7 @@ DbgDotNetValueResult CallCore(DbgDotNetValue? obj, bool isCallvirt, DmdMethodBas var options = isCallvirt ? DotNetClassHookCallOptions.IsCallvirt : DotNetClassHookCallOptions.None; foreach (var anyHook in anyClassHooks) { var res = anyHook.Call(options, obj, method, arguments); - if (!(res is null)) + if (res is not null) return DbgDotNetValueResult.Create(res); } @@ -772,9 +772,9 @@ DbgDotNetValueResult CallCore(DbgDotNetValue? obj, bool isCallvirt, DmdMethodBas if (type != type.AppDomain.GetWellKnownType(wellKnownType, isOptional: true)) hook = null; } - if (!(hook is null)) { + if (hook is not null) { var res = hook.Call(options, obj, method, arguments); - if (!(res is null)) + if (res is not null) return DbgDotNetValueResult.Create(res); } } @@ -804,7 +804,7 @@ internal int ToInt32(ILValue value) { if (value is ConstantInt32ILValue i32Value) return i32Value.Value; var dnValue = TryGetDotNetValue(value, canCreateValue: false); - if (!(dnValue is null)) { + if (dnValue is not null) { if (dnValue.Type != dnValue.Type.AppDomain.System_Int32) throw new InvalidOperationException(); var rawValue = dnValue.GetRawValue(); @@ -817,7 +817,7 @@ internal int ToInt32(ILValue value) { DbgDotNetValue IDebuggerRuntime.CreateValue(object? value, DmdType targetType) { var res = TryCreateSyntheticValue(targetType, value); - if (!(res is null)) + if (res is not null) return res; return RecordValue(runtime.CreateValue(evalInfo, value)); } @@ -863,7 +863,7 @@ byte[] IDebuggerRuntime.ToByteArray(ILValue value) { DbgDotNetValue IDebuggerRuntime.ToDotNetValue(ILValue value) { var dnValue = TryGetDotNetValue(value, canCreateValue: false); - if (!(dnValue is null)) + if (dnValue is not null) return dnValue; throw new InterpreterMessageException(PredefinedEvaluationErrorMessages.InternalDebuggerError); } @@ -891,7 +891,7 @@ DbgDotNetValue IDebuggerRuntime.GetReturnValue(int index) { DbgDotNetValue IDebuggerRuntime.GetObjectByAlias(string name) { evalInfo.Context.TryGetData(out DbgDotNetExpressionCompiler? expressionCompiler); - Debug2.Assert(!(expressionCompiler is null)); + Debug2.Assert(expressionCompiler is not null); if (expressionCompiler is null) throw new InvalidOperationException(); @@ -912,7 +912,7 @@ DbgDotNetValue IDebuggerRuntime.GetObjectByAlias(string name) { case DbgDotNetAliasKind.ObjectId: var objectId = dbgObjectIdService.GetObjectId(evalInfo.Runtime, aliasInfo.Id); - if (!(objectId is null)) { + if (objectId is not null) { var dbgValue = objectId.GetValue(evalInfo); value = (DbgDotNetValue)dbgValue.InternalValue; return RecordValue(value); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/Hooks/System_Runtime_CompilerServices_RuntimeHelpers.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/Hooks/System_Runtime_CompilerServices_RuntimeHelpers.cs index ffa67ca476..562ff32c16 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/Hooks/System_Runtime_CompilerServices_RuntimeHelpers.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/Hooks/System_Runtime_CompilerServices_RuntimeHelpers.cs @@ -72,7 +72,7 @@ sealed class System_Runtime_CompilerServices_RuntimeHelpers : DotNetClassHook { static bool TryGetSize(DmdType type, out int size) { if (type.IsValueType) { var attr = type.StructLayoutAttribute; - if (!(attr is null) && attr.Size >= 0) { + if (attr is not null && attr.Size >= 0) { size = attr.Size; return true; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/Hooks/dnSpy_Roslyn_ExpressionEvaluator_IntrinsicMethods.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/Hooks/dnSpy_Roslyn_ExpressionEvaluator_IntrinsicMethods.cs index b6529dbb7d..6d3f24ea82 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/Hooks/dnSpy_Roslyn_ExpressionEvaluator_IntrinsicMethods.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/Interpreter/Hooks/dnSpy_Roslyn_ExpressionEvaluator_IntrinsicMethods.cs @@ -119,7 +119,7 @@ sealed class dnSpy_Roslyn_ExpressionEvaluator_IntrinsicMethods : DotNetClassHook break; type = sig.ReturnType.GetElementType()!; var origMethod = method.ReflectedType!.GetMethod(method.Module, method.MetadataToken); - Debug2.Assert(!(origMethod is null)); + Debug2.Assert(origMethod is not null); sig = origMethod.GetMethodSignature(); ps = sig.GetParameterTypes(); if (sig.GenericParameterCount == 1 && sig.ReturnType.IsPointer && diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/StateWithKey.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/StateWithKey.cs index 76ab6deb8d..b654ed8922 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/StateWithKey.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Evaluation/Engine/StateWithKey.cs @@ -27,8 +27,8 @@ namespace dnSpy.Debugger.DotNet.Evaluation.Engine { readonly List<(object key, T data)> list = new List<(object, T)>(); public static T GetOrCreate(DbgObject obj, object key) { - Debug2.Assert(!(obj is null)); - Debug2.Assert(!(key is null)); + Debug2.Assert(obj is not null); + Debug2.Assert(key is not null); var state = obj.GetOrCreateData>(); lock (state.lockObj) { var list = state.list; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Exceptions/BreakWhenThrownExceptionCommand.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Exceptions/BreakWhenThrownExceptionCommand.cs index 4dcaca9821..767aa18635 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Exceptions/BreakWhenThrownExceptionCommand.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Exceptions/BreakWhenThrownExceptionCommand.cs @@ -65,7 +65,7 @@ static bool IsException(TypeDef type) { TypeDef? td = type; if (IsSystemException(td)) return true; - for (int i = 0; i < 1000 && !(td is null); i++) { + for (int i = 0; i < 1000 && td is not null; i++) { if (IsSystemException(td.BaseType)) return true; var bt = td.BaseType; @@ -75,7 +75,7 @@ static bool IsException(TypeDef type) { } static bool IsSystemException(ITypeDefOrRef type) => - !(type is null) && + type is not null && type.DeclaringType is null && type.Namespace == "System" && type.Name == "Exception" && diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ClassLoader.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ClassLoader.cs index ccc4054d19..44e191f24e 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ClassLoader.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ClassLoader.cs @@ -137,7 +137,7 @@ void LoadNewClasses_EngineThread(List states) { dbgDynamicModuleProvider.InitializeNonLoadedClasses(state.Document.DbgModule, nonLoadedTokens); } - var remaining = states.Where(a => a.ModifiedTypes.Count != 0 || (!(a.LoadClassHash is null) && a.LoadClassHash.Count != 0)).Select(a => a.Document).ToArray(); + var remaining = states.Where(a => a.ModifiedTypes.Count != 0 || (a.LoadClassHash is not null && a.LoadClassHash.Count != 0)).Select(a => a.Document).ToArray(); if (remaining.Length == 0) return; @@ -157,7 +157,7 @@ void LoadNewClasses_EngineThread(List states) { uint[] GetNonLoadedTokens(ModuleState state) { var hash = new HashSet(state.ModifiedTypes); - if (!(state.LoadClassHash is null)) { + if (state.LoadClassHash is not null) { foreach (var a in state.LoadClassHash) hash.Add(a); } @@ -165,7 +165,7 @@ uint[] GetNonLoadedTokens(ModuleState state) { tokens.Sort(); var res = new List(tokens.Count); foreach (uint token in tokens) { - bool loaded = !(state.LoadClassHash is null) && state.LoadClassHash.Contains(token); + bool loaded = state.LoadClassHash is not null && state.LoadClassHash.Contains(token); if (loaded) continue; // It has already been initialized diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Commands.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Commands.cs index 7fe6c857d1..65d4a5c3f4 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Commands.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Commands.cs @@ -62,7 +62,7 @@ sealed class FilesCommand : CommandBase { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTS_TREEVIEW_GUID)) return null; var nodes = context.Find(); - if (!(nodes is null) && nodes.Length != 0) + if (nodes is not null && nodes.Length != 0) return nodes[0] as DocumentTreeNodeData; return null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgAssemblyInfoProviderService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgAssemblyInfoProviderService.cs index e3dd363cfc..e485c7768d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgAssemblyInfoProviderService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgAssemblyInfoProviderService.cs @@ -42,7 +42,7 @@ sealed class DbgAssemblyInfoProviderServiceImpl : DbgAssemblyInfoProviderService throw new ArgumentNullException(nameof(runtime)); foreach (var lz in dbgAssemblyInfoProviderFactories) { var provider = lz.Value.Create(runtime); - if (!(provider is null)) + if (provider is not null) return provider; } return null; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgDynamicModuleProviderService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgDynamicModuleProviderService.cs index 0c0954de8f..9f296e1bcd 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgDynamicModuleProviderService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgDynamicModuleProviderService.cs @@ -42,7 +42,7 @@ sealed class DbgDynamicModuleProviderServiceImpl : DbgDynamicModuleProviderServi throw new ArgumentNullException(nameof(runtime)); foreach (var lz in dbgDynamicModuleProviderFactories) { var provider = lz.Value.Create(runtime); - if (!(provider is null)) + if (provider is not null) return provider; } return null; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgInMemoryModuleService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgInMemoryModuleService.cs index 212379ba97..b51cb8bf97 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgInMemoryModuleService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgInMemoryModuleService.cs @@ -67,7 +67,7 @@ public RuntimeInfo(DbgInMemoryModuleServiceImpl owner, DbgAssemblyInfoProvider d AssemblyInfoProvider = dbgAssemblyInfoProvider ?? throw new ArgumentNullException(nameof(dbgAssemblyInfoProvider)); DynamicModuleProvider = dbgDynamicModuleProvider; ClassLoader = classLoader; - if (!(dbgDynamicModuleProvider is null)) + if (dbgDynamicModuleProvider is not null) dbgDynamicModuleProvider.ClassLoaded += DbgDynamicModuleProvider_ClassLoaded; } @@ -159,7 +159,7 @@ void DbgRuntime_ModulesChanged(object? sender, DbgCollectionChangedEventArgs(); list.Add((manifestModule, module)); } - if (!(list is null)) { + if (list is not null) { uiDispatcher.UI(() => { foreach (var t in list) OnModuleAdded_UI(info, t.manifestModule, t.module); @@ -175,7 +175,7 @@ void OnModuleAdded_UI(RuntimeInfo info, DbgModule manifestModule, DbgModule modu // new netmodule node to the assembly in the treeview. // Update a dynamic assembly, if one exists - if (!(info.DynamicModuleProvider is null)) { + if (info.DynamicModuleProvider is not null) { var manifestKey = DynamicModuleDefDocument.CreateKey(manifestModule); var asmFile = FindDocument(manifestKey); if (documentTreeView.Value.FindNode(asmFile) is AssemblyDocumentNode asmNode) { @@ -186,7 +186,7 @@ void OnModuleAdded_UI(RuntimeInfo info, DbgModule manifestModule, DbgModule modu Debug2.Assert(moduleNode is null); if (moduleNode is null) { var md = info.DynamicModuleProvider.GetDynamicMetadata(module, out var moduleId); - if (!(md is null)) { + if (md is not null) { UpdateResolver(md); var newFile = new DynamicModuleDefDocument(moduleId, module, md, UseDebugSymbols); asmNode.Document.Children.Add(newFile); @@ -215,9 +215,9 @@ void OnModuleAdded_UI(RuntimeInfo info, DbgModule manifestModule, DbgModule modu catch { } - Debug2.Assert(!(newFile is null)); - if (!(newFile is null)) { - Debug2.Assert(!(newFile.ModuleDef is null)); + Debug2.Assert(newFile is not null); + if (newFile is not null) { + Debug2.Assert(newFile.ModuleDef is not null); UpdateResolver(newFile.ModuleDef); asmNode.Document.Children.Add(newFile); RemoveFromAssembly(newFile.ModuleDef); @@ -231,12 +231,12 @@ void OnModuleAdded_UI(RuntimeInfo info, DbgModule manifestModule, DbgModule modu static void RemoveFromAssembly(ModuleDef module) { // It could be a netmodule that contains an AssemblyDef row, if so remove it from the assembly - if (!(module.Assembly is null)) + if (module.Assembly is not null) module.Assembly.Modules.Remove(module); } void UpdateResolver(ModuleDef module) { - if (!(module is null)) + if (module is not null) module.Context = DsDotNetDocumentBase.CreateModuleContext(documentProvider.AssemblyResolver); } @@ -255,7 +255,7 @@ void UpdateResolver(ModuleDef module) { throw new ArgumentNullException(nameof(module)); var doc = FindDynamicModule(module); - if (!(doc is null)) + if (doc is not null) return doc; if (!TryGetRuntimeInfo(module.Runtime, out var info)) @@ -272,7 +272,7 @@ void UpdateResolver(ModuleDef module) { lock (lockObj) { doc = FindDynamicModule(module); - if (!(doc is null)) + if (doc is not null) return doc; var modules = info.AssemblyInfoProvider.GetAssemblyModules(module); @@ -282,12 +282,12 @@ void UpdateResolver(ModuleDef module) { var manifestKey = DynamicModuleDefDocument.CreateKey(manifestDnModule); var manMod = FindDocument(manifestKey); Debug2.Assert(manMod is null); - if (!(manMod is null)) + if (manMod is not null) return null; var manDoc = FindDynamicModule(manifestDnModule); Debug2.Assert(manDoc is null); - if (!(manDoc is null)) + if (manDoc is not null) return null; var files = new List(modules.Length); @@ -326,13 +326,13 @@ void UpdateResolver(ModuleDef module) { return null; var doc = FindMemoryModule(module); - if (!(doc is null)) + if (doc is not null) return doc; MemoryModuleDefDocument? result = null; lock (lockObj) { doc = FindMemoryModule(module); - if (!(doc is null)) + if (doc is not null) return doc; var modules = info.AssemblyInfoProvider.GetAssemblyModules(module); @@ -342,12 +342,12 @@ void UpdateResolver(ModuleDef module) { var manifestKey = MemoryModuleDefDocument.CreateKey(manifestModule.Process, manifestModule.Address); var manMod = FindDocument(manifestKey); Debug2.Assert(manMod is null); - if (!(manMod is null)) + if (manMod is not null) return null; var manDoc = FindMemoryModule(manifestModule); Debug2.Assert(manDoc is null); - if (!(manDoc is null)) + if (manDoc is not null) return null; var docs = new List(modules.Length); @@ -365,7 +365,7 @@ void UpdateResolver(ModuleDef module) { } docs.Add(modDoc); } - Debug2.Assert(!(result is null)); + Debug2.Assert(result is not null); if (docs.Count == 0 || result is null) return null; var asmFile = MemoryModuleDefDocument.CreateAssembly(docs); @@ -424,7 +424,7 @@ void Initialize(RuntimeInfo info, DynamicModuleDefDocument[] docs) => void Initialize_UI(RuntimeInfo info, DynamicModuleDefDocument[] docs) { uiDispatcher.VerifyAccess(); - Debug2.Assert(!(info.DynamicModuleProvider is null)); + Debug2.Assert(info.DynamicModuleProvider is not null); if (info.DynamicModuleProvider is null) return; info.ClassLoader?.LoadEverything_UI(docs); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgMetadataServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgMetadataServiceImpl.cs index 4eac95c7c8..95571512ce 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgMetadataServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgMetadataServiceImpl.cs @@ -54,11 +54,11 @@ sealed class DbgMetadataServiceImpl : DbgMetadataService { return dbgInMemoryModuleService.LoadModule(module); var mod = dbgInMemoryModuleService.FindModule(module); - if (!(mod is null)) + if (mod is not null) return mod; var id = dbgModuleIdProviderService.GetModuleId(module); - if (!(id is null)) + if (id is not null) return TryGetMetadata(id.Value, options); return null; @@ -67,7 +67,7 @@ sealed class DbgMetadataServiceImpl : DbgMetadataService { ModuleDef? LoadNonDiskFile(ModuleId moduleId, DbgLoadModuleOptions options) { if (UseMemoryModules || moduleId.IsDynamic || moduleId.IsInMemory || (options & DbgLoadModuleOptions.ForceMemory) != 0) { var module = dbgModuleIdProviderService.GetModule(moduleId); - if (!(module is null)) + if (module is not null) return dbgInMemoryModuleService.LoadModule(module); } @@ -94,7 +94,7 @@ sealed class DbgMetadataServiceImpl : DbgMetadataService { public override ModuleDef? TryGetMetadata(ModuleId moduleId, DbgLoadModuleOptions options) { var mod = LoadNonDiskFile(moduleId, options) ?? LoadExisting(moduleId); - if (!(mod is null)) + if (mod is not null) return mod; if (moduleId.IsDynamic || moduleId.IsInMemory) @@ -110,7 +110,7 @@ sealed class DbgMetadataServiceImpl : DbgMetadataService { var document = documentService.TryGetOrCreate(DsDocumentInfo.CreateDocument(asmFilename), isAutoLoaded); if (document is null) document = documentService.Resolve(new AssemblyNameInfo(moduleId.AssemblyFullName), null); - if (!(document is null)) { + if (document is not null) { // Common case is a single-file assembly or first module of a multifile assembly if (asmFilename.Equals(moduleFilename, StringComparison.OrdinalIgnoreCase)) return document.ModuleDef; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgModuleIdProviderService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgModuleIdProviderService.cs index 6e916ea803..276ca59119 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgModuleIdProviderService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DbgModuleIdProviderService.cs @@ -63,7 +63,7 @@ sealed class CachedModuleId { ModuleId? GetModuleIdCore(DbgModule module) { foreach (var lz in dbgModuleIdProviders) { var id = lz.Value.GetModuleId(module); - if (!(id is null)) + if (id is not null) return id; } return null; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DsDocumentProvider.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DsDocumentProvider.cs index 5ac579b238..7178c5b694 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DsDocumentProvider.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DsDocumentProvider.cs @@ -71,7 +71,7 @@ public override IEnumerable DocumentInfos { get { foreach (var doc in Documents) { var info = GetDocumentInfo(doc); - if (!(info is null)) + if (info is not null) yield return info.Value; } } @@ -82,7 +82,7 @@ public override IEnumerable DocumentInfos { if (dnDoc is IModuleIdHolder idHolder) return new DocumentInfo(doc, idHolder.ModuleId, dnDoc.IsActive); var mod = doc.ModuleDef; - if (!(mod is null) && File.Exists(mod.Location)) + if (mod is not null && File.Exists(mod.Location)) return new DocumentInfo(doc, ModuleId.CreateFromFile(mod), isActive: dnDoc?.IsActive ?? true); return null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DynamicModuleDefDocument.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DynamicModuleDefDocument.cs index e5b12a316a..f6936cafd4 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DynamicModuleDefDocument.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/DynamicModuleDefDocument.cs @@ -55,7 +55,7 @@ public static DynamicModuleDefDocument CreateAssembly(List CreateChildren() { var list = new TList(); - if (!(files is null)) { + if (files is not null) { list.AddRange(files); files = null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Internal/DbgRawMetadataImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Internal/DbgRawMetadataImpl.cs index 0f8b36b4c0..6bce1254ee 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Internal/DbgRawMetadataImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Internal/DbgRawMetadataImpl.cs @@ -182,7 +182,7 @@ void Dispose() { internal void ForceDispose() { GC.SuppressFinalize(this); - if (!(process is null) && address != IntPtr.Zero && Interlocked.Exchange(ref freedAddress, 1) == 0) { + if (process is not null && address != IntPtr.Zero && Interlocked.Exchange(ref freedAddress, 1) == 0) { bool b = NativeMethods.VirtualFree(address, IntPtr.Zero, NativeMethods.MEM_RELEASE); Debug.Assert(b); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Internal/DbgRawMetadataServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Internal/DbgRawMetadataServiceImpl.cs index 59f37080a0..cbe72a9097 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Internal/DbgRawMetadataServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/Internal/DbgRawMetadataServiceImpl.cs @@ -51,7 +51,7 @@ public override DbgRawMetadata Create(DbgRuntime runtime, bool isFileLayout, ulo var state = runtime.GetOrCreateData(); lock (state.LockObj) { if (state.Dict.TryGetValue(moduleAddress, out var rawMd)) { - if (!(rawMd.TryAddRef() is null)) { + if (rawMd.TryAddRef() is not null) { if (rawMd.IsFileLayout != isFileLayout || rawMd.Size != moduleSize) { rawMd.Release(); throw new InvalidOperationException(); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/MemoryModuleDefDocument.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/MemoryModuleDefDocument.cs index be4e5f7f31..6b7f535f30 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/MemoryModuleDefDocument.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/MemoryModuleDefDocument.cs @@ -67,7 +67,7 @@ public DocKey(DbgProcess process, ulong address) { protected override TList CreateChildren() { var list = new TList(); - if (!(files is null)) { + if (files is not null) { list.AddRange(files); files = null; } @@ -98,7 +98,7 @@ internal bool TryUpdateMemory() { return false; } finally { - if (!(buffer is null)) + if (buffer is not null) ReleaseBuffer(buffer); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ModuleLoaderDlg.xaml.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ModuleLoaderDlg.xaml.cs index 9c7f67f423..db348bf460 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ModuleLoaderDlg.xaml.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ModuleLoaderDlg.xaml.cs @@ -27,7 +27,7 @@ public ModuleLoaderDlg() { InitializeComponent(); DataContextChanged += (s, e) => { var data = DataContext as ModuleLoaderVM; - if (!(data is null)) { + if (data is not null) { data.OnCompleted += ModuleLoaderVM_OnCompleted; if (data.HasCompleted) OnCompleted(); @@ -56,7 +56,7 @@ protected override void OnClosing(CancelEventArgs e) { void OnCompleted() { var data = DataContext as ModuleLoaderVM; - DialogResult = !(data is null) && !data.WasCanceled; + DialogResult = data is not null && !data.WasCanceled; Close(); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ModuleLoaderVM.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ModuleLoaderVM.cs index 6392858aa0..96f9f2528d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ModuleLoaderVM.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/ModuleLoaderVM.cs @@ -190,7 +190,7 @@ string CalculateCurrentItemName(DynamicModuleDefDocument document) { sb.Append($"({Array.IndexOf(documents, document) + 1}/{documents.Length}): "); var asm = module.Assembly; - if (!(asm is null)) { + if (asm is not null) { if (module.IsManifestModule) sb.Append(asm.FullName); else diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/RuntimeAssemblyResolver.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/RuntimeAssemblyResolver.cs index b68b77c705..7f0a8554ea 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/RuntimeAssemblyResolver.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/RuntimeAssemblyResolver.cs @@ -153,9 +153,9 @@ static bool HasAssemblyOrModule(DbgRuntime runtime, IAssembly assembly, string? static IEnumerable GetRuntimesCore(DbgManager dbgManager) { var currentRuntime = dbgManager.CurrentRuntime; DbgRuntime? runtime; - if (!((runtime = currentRuntime.Current) is null)) + if ((runtime = currentRuntime.Current) is not null) yield return runtime; - if (!((runtime = currentRuntime.Break) is null)) + if ((runtime = currentRuntime.Break) is not null) yield return runtime; if (currentRuntime.Current?.Process is DbgProcess currentProcess) { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/TreeViewUpdater.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/TreeViewUpdater.cs index 24f28aecda..11f636d495 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/TreeViewUpdater.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Metadata/TreeViewUpdater.cs @@ -53,7 +53,7 @@ public void Update() { if (ModuleNode.TreeNode.LazyLoading) return; - if (!(loadedClassTokens is null)) { + if (loadedClassTokens is not null) { foreach (var a in loadedClassTokens) modifiedTypes.Add(a); } @@ -63,7 +63,7 @@ public void Update() { bool needRedecompile = false; foreach (uint token in tokensList) { var td = Document.ModuleDef!.ResolveToken(token) as TypeDef; - Debug2.Assert(!(td is null)); + Debug2.Assert(td is not null); if (td is null) continue; Update(td); @@ -79,7 +79,7 @@ public void Update() { List GetNonCheckedTypeAndDeclaringTypes(TypeDef td) { var list = new List(); - while (!(td is null) && !checkedTypes.Contains(td)) { + while (td is not null && !checkedTypes.Contains(td)) { list.Add(td); checkedTypes.Add(td); td = td.DeclaringType; @@ -109,7 +109,7 @@ void CreateTypeNodes(List types) { break; typeNode = GetOrCreateNestedTypeTreeNode(parentNode, type); } - Debug2.Assert(!(typeNode is null)); + Debug2.Assert(typeNode is not null); if (wasLoaded || modifiedTypes.Contains(type.MDToken.Raw)) UpdateMemberNodes(typeNode); @@ -119,12 +119,12 @@ void CreateTypeNodes(List types) { } static TypeNode GetOrCreateNonNestedTypeTreeNode(ModuleDocumentNode modNode, TypeDef type) { - Debug2.Assert(!(type is null) && type.DeclaringType is null); + Debug2.Assert(type is not null && type.DeclaringType is null); modNode.TreeNode.EnsureChildrenLoaded(); TypeNode? typeNode; var nsNode = GetOrCreateNamespaceNode(modNode, type.Namespace); typeNode = nsNode.TreeNode.DataChildren.OfType().FirstOrDefault(a => a.TypeDef == type); - if (!(typeNode is null)) + if (typeNode is not null) return typeNode; typeNode = nsNode.Create(type); nsNode.TreeNode.AddChild(typeNode.TreeNode); @@ -134,7 +134,7 @@ static TypeNode GetOrCreateNonNestedTypeTreeNode(ModuleDocumentNode modNode, Typ static NamespaceNode GetOrCreateNamespaceNode(ModuleDocumentNode modNode, string ns) { modNode.TreeNode.EnsureChildrenLoaded(); var nsNode = modNode.TreeNode.DataChildren.OfType().FirstOrDefault(a => a.Name == ns); - if (!(nsNode is null)) + if (nsNode is not null) return nsNode; nsNode = modNode.Create(ns); modNode.TreeNode.AddChild(nsNode.TreeNode); @@ -142,10 +142,10 @@ static NamespaceNode GetOrCreateNamespaceNode(ModuleDocumentNode modNode, string } static TypeNode GetOrCreateNestedTypeTreeNode(TypeNode typeNode, TypeDef nestedType) { - Debug2.Assert(!(nestedType is null) && nestedType.DeclaringType == typeNode.TypeDef); + Debug2.Assert(nestedType is not null && nestedType.DeclaringType == typeNode.TypeDef); typeNode.TreeNode.EnsureChildrenLoaded(); var childTypeNode = typeNode.TreeNode.DataChildren.OfType().FirstOrDefault(a => a.TypeDef == nestedType); - if (!(childTypeNode is null)) + if (childTypeNode is not null) return childTypeNode; childTypeNode = typeNode.Create(nestedType); typeNode.TreeNode.AddChild(childTypeNode.TreeNode); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/CompilerUtils.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/CompilerUtils.cs index 701724370f..a99ffbeecc 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/CompilerUtils.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/CompilerUtils.cs @@ -62,11 +62,11 @@ public static bool IsIgnoredIteratorStateMachineMethod(MethodDef method) { // from inside an iterator or async method. That method just calls the real base method. public static bool IsBaseWrapperMethod(DbgModule module, uint token) { var reflectionModule = module.GetReflectionModule(); - Debug2.Assert(!(reflectionModule is null)); + Debug2.Assert(reflectionModule is not null); if (reflectionModule is null) return false; var method = reflectionModule.ResolveMethod((int)token, DmdResolveOptions.None); - Debug2.Assert(!(method is null)); + Debug2.Assert(method is not null); if (method is null) return false; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/DbgEngineStepperImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/DbgEngineStepperImpl.cs index 82dd05679a..2fa0a6a17f 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/DbgEngineStepperImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/DbgEngineStepperImpl.cs @@ -80,7 +80,7 @@ DbgEvaluationInfo CreateEvaluationInfo(DbgThread thread) { frame = thread.GetTopStackFrame(); if (frame is null) throw new InvalidOperationException(); - Debug2.Assert(!(frame is null)); + Debug2.Assert(frame is not null); return CreateEvaluationInfo(frame); } catch { @@ -144,7 +144,7 @@ async Task CreateReturnToAwaiterTaskCoreAsync(Task setResu try { if (TryCallSetNotificationForWaitCompletion(thread, builderFieldModule, builderFieldToken, true, out taskValue)) { var notifyDebuggerOfWaitCompletionMethod = TaskEvalUtils.GetNotifyDebuggerOfWaitCompletionMethod(taskValue.Type.AppDomain); - Debug2.Assert(!(notifyDebuggerOfWaitCompletionMethod is null)); + Debug2.Assert(notifyDebuggerOfWaitCompletionMethod is not null); thread = await SetNotifyDebuggerOfWaitCompletionBreakpoint(notifyDebuggerOfWaitCompletionMethod, taskValue); } } @@ -224,21 +224,21 @@ async Task SetNotifyDebuggerOfWaitCompletionBreakpointCoreAsync(Task< frames = null; var frame = stepper.TryGetFrameInfo(thread); - Debug2.Assert(!(frame is null)); + Debug2.Assert(frame is not null); if (frame is null) break; thread = await stepper.StepOutAsync(frame); } finally { - if (!(frames is null)) + if (frames is not null) thread.Process.DbgManager.Close(frames); } } // Step over any hidden instructions so we end up on a statement var newFrame = stepper.TryGetFrameInfo(thread); - Debug2.Assert(!(newFrame is null)); - if (!(newFrame is null)) + Debug2.Assert(newFrame is not null); + if (newFrame is not null) thread = await StepOverHiddenInstructionsAsync(newFrame); return thread; @@ -287,7 +287,7 @@ void ClearReturnToAwaiterBreakpoint() { return; returnToAwaiterState.taskCompletionSource?.TrySetCanceled(); returnToAwaiterState.taskCompletionSource = null; - if (!(returnToAwaiterState.breakpoint is null)) { + if (returnToAwaiterState.breakpoint is not null) { stepper.RemoveBreakpoints(new[] { returnToAwaiterState.breakpoint }); returnToAwaiterState.breakpoint = null; } @@ -307,7 +307,7 @@ bool TryCallSetNotificationForWaitCompletion(DbgThread thread, DbgModule builder try { evalInfo = CreateEvaluationInfo(thread); var info = TaskEvalUtils.CallSetNotificationForWaitCompletion(evalInfo, builderFieldModule, builderFieldToken, value); - if (info.success && info.taskValue is object) { + if (info.success && info.taskValue is not null) { taskValue = info.taskValue; return true; } @@ -327,7 +327,7 @@ void RaiseStepComplete(object? tag, string? error, bool forciblyCanceled = false if (IsClosed) return; var thread = CurrentThread.IsClosed ? null : CurrentThread; - Debug2.Assert(!(StepComplete is null)); + Debug2.Assert(StepComplete is not null); StepComplete?.Invoke(this, new DbgEngineStepCompleteEventArgs(thread, tag, error, forciblyCanceled)); } @@ -340,7 +340,7 @@ public override void Step(object? tag, DbgEngineStepKind step) { void Step_EngineThread(object? tag, DbgEngineStepKind step) { runtime.Dispatcher.VerifyAccess(); - if (!(stepper.Session is null)) { + if (stepper.Session is not null) { Debug.Fail("The previous step hasn't been canceled"); // No need to localize it, if we're here it's a bug RaiseStepComplete(tag, "The previous step hasn't been canceled"); @@ -380,7 +380,7 @@ async Task StepOverHiddenInstructionsAsync(DbgDotNetEngineStepperFram Task StepOverHiddenInstructionsAsync(DbgDotNetEngineStepperFrameInfo frame, GetStepRangesAsyncResult result) { var thread = frame.Thread; - if (!(result.DebugInfo is null)) { + if (result.DebugInfo is not null) { if (!frame.TryGetLocation(out var module, out var token, out var offset)) throw new InvalidOperationException(); bool skipMethod = (offset == 0 || offset == DbgDotNetInstructionOffsetConstants.PROLOG) && AreIteratorsDecompiled && CompilerUtils.IsIgnoredIteratorStateMachineMethod(result.DebugInfo.Method); @@ -396,7 +396,7 @@ Task StepOverHiddenInstructionsAsync(DbgDotNetEngineStepperFrameInfo } var ilSpans = TryCreateMethodBodySpans(frame); - if (!(ilSpans is null)) { + if (ilSpans is not null) { var ranges = CreateStepRanges(ilSpans); if (ranges.Length != 0) return stepper.StepOverAsync(frame, ranges); @@ -481,7 +481,7 @@ void ClearStepIntoBreakpoint() { runtime.Dispatcher.VerifyAccess(); if (stepIntoState is null) return; - if (!(stepIntoState.breakpoint is null)) { + if (stepIntoState.breakpoint is not null) { stepper.RemoveBreakpoints(new[] { stepIntoState.breakpoint }); stepIntoState.breakpoint = null; } @@ -521,7 +521,7 @@ async Task StepIntoCoreAsync(DbgDotNetEngineStepperFrameInfo frame) { for (;;) { thread = await StepIntoCoreAsync(f, origResult.DebugInfo, origResult.StatementRanges); f = stepper.TryGetFrameInfo(thread); - Debug2.Assert(!(f is null)); + Debug2.Assert(f is not null); if (f is null) return thread; if (!f.TryGetLocation(out var module, out var token, out uint offset)) @@ -536,20 +536,20 @@ async Task StepIntoCoreAsync(DbgDotNetEngineStepperFrameInfo frame) { if (offset == 0 || offset == DbgDotNetInstructionOffsetConstants.PROLOG) { if (debuggerSettings.AsyncDebugging) { var newResult = await GetStepRangesAsync(f, returnValues: false); - if (!(newResult.DebugInfo is null) && !(newResult.StateMachineDebugInfo?.AsyncInfo is null)) { + if (newResult.DebugInfo is not null && newResult.StateMachineDebugInfo?.AsyncInfo is not null) { var stepIntoTask = SetStepIntoBreakpoint(thread, module, newResult.StateMachineDebugInfo.Method.MDToken.Raw, 0); stepper.Continue(); thread = await stepIntoTask; ClearStepIntoState(); f = stepper.TryGetFrameInfo(thread); - Debug2.Assert(!(f is null)); + Debug2.Assert(f is not null); if (f is null) return thread; } } thread = await StepOverHiddenInstructionsAsync(f); f = stepper.TryGetFrameInfo(thread); - Debug2.Assert(!(f is null)); + Debug2.Assert(f is not null); if (f is null) return thread; if (!f.TryGetLocation(out module, out token, out offset)) @@ -567,7 +567,7 @@ async Task StepIntoCoreAsync(DbgDotNetEngineStepperFrameInfo frame) { thread.Runtime.Process.DbgManager.WriteMessage(PredefinedDbgManagerMessageKinds.StepFilter, GetStepFilterMessage(member)); thread = await stepper.StepOutAsync(f); f = stepper.TryGetFrameInfo(thread); - Debug2.Assert(!(f is null)); + Debug2.Assert(f is not null); if (f is null) return thread; if (!f.TryGetLocation(out module, out token, out offset)) @@ -624,7 +624,7 @@ bool IsPropertyOrOperatorMethod(DbgThread thread, [NotNullWhen(true)] out DmdMem try { evalInfo = CreateEvaluationInfo(thread); var method = runtime.GetFrameMethod(evalInfo); - if (!(method is null)) { + if (method is not null) { // Operators should have special-name bit set if (method.IsSpecialName && method.Name.StartsWith("op_")) { member = method; @@ -656,11 +656,11 @@ bool IsPropertyOrOperatorMethod(DbgThread thread, [NotNullWhen(true)] out DmdMem } async Task StepIntoCoreAsync(DbgDotNetEngineStepperFrameInfo frame, DbgMethodDebugInfo? debugInfo, DbgCodeRange[] statementRanges) { - if (!(debugInfo?.AsyncInfo is null) && debugInfo.AsyncInfo.SetResultOffset != uint.MaxValue) { + if (debugInfo?.AsyncInfo is not null && debugInfo.AsyncInfo.SetResultOffset != uint.MaxValue) { if (!frame.TryGetLocation(out var module, out var token, out _)) throw new InvalidOperationException(); var returnToAwaiterTask = TryCreateReturnToAwaiterTask(frame.Thread, module, token, debugInfo.AsyncInfo.SetResultOffset, debugInfo.AsyncInfo.BuilderField?.MDToken.Raw ?? 0); - if (!(returnToAwaiterTask is null)) { + if (returnToAwaiterTask is not null) { var stepIntoTask = stepper.StepIntoAsync(frame, statementRanges); return await await WhenAny(new[] { returnToAwaiterTask, stepIntoTask }); } @@ -704,7 +704,7 @@ async Task StepOverCoreAsync(DbgDotNetEngineStepperFrameInfo frame) { bool keepLooping = false; if (IgnoreBaseWrapperMethods) { f = stepper.TryGetFrameInfo(thread); - Debug2.Assert(!(f is null)); + Debug2.Assert(f is not null); if (f is null) return thread; if (!f.TryGetLocation(out var module, out var token, out _)) @@ -720,7 +720,7 @@ async Task StepOverCoreAsync(DbgDotNetEngineStepperFrameInfo frame) { async Task StepOverCore2Async(DbgDotNetEngineStepperFrameInfo frame) { runtime.Dispatcher.VerifyAccess(); - Debug2.Assert(!(stepper.Session is null)); + Debug2.Assert(stepper.Session is not null); DbgThread thread; var result = await GetStepRangesAsync(frame, returnValues: true); @@ -730,7 +730,7 @@ async Task StepOverCore2Async(DbgDotNetEngineStepperFrameInfo frame) var asyncStepInfos = GetAsyncStepInfos(result); Debug2.Assert(asyncStepInfos is null || asyncStepInfos.Count != 0); - if (!(asyncStepInfos is null)) { + if (asyncStepInfos is not null) { try { var asyncState = SetAsyncStepOverState(new AsyncStepOverState(this, stepper, result.DebugInfo!.AsyncInfo!.BuilderField))!; foreach (var stepInfo in asyncStepInfos) @@ -759,10 +759,10 @@ async Task StepOverCore2Async(DbgDotNetEngineStepperFrameInfo frame) asyncState.Dispose(); var newFrame = stepper.TryGetFrameInfo(thread); - Debug2.Assert(!(newFrame is null)); - if (!(newFrame is null) && newFrame.TryGetLocation(out var newModule, out var newToken, out _)) { + Debug2.Assert(newFrame is not null); + if (newFrame is not null && newFrame.TryGetLocation(out var newModule, out var newToken, out _)) { Debug.Assert(newModule == module && asyncState.ResumeToken == newToken); - if (!(result.DebugInfo is null) && newModule == module && asyncState.ResumeToken == newToken) + if (result.DebugInfo is not null && newModule == module && asyncState.ResumeToken == newToken) thread = await StepOverHiddenInstructionsAsync(newFrame, result); } } @@ -775,7 +775,7 @@ async Task StepOverCore2Async(DbgDotNetEngineStepperFrameInfo frame) } else { var tasks = new List>(2); - if (!(returnToAwaiterTask is null)) + if (returnToAwaiterTask is not null) tasks.Add(returnToAwaiterTask); stepper.CollectReturnValues(result.Frame, result.StatementInstructions); tasks.Add(stepper.StepOverAsync(result.Frame, result.StatementRanges)); @@ -846,7 +846,7 @@ public void AddYieldBreakpoint(DbgThread thread, DbgModule module, uint token, D internal Task SetResumeBreakpoint(DbgThread thread, DbgModule module) { Debug.Assert(yieldTaskCompletionSource.Task.IsCompleted); Debug2.Assert(resumeBreakpoint is null); - if (!(resumeBreakpoint is null)) + if (resumeBreakpoint is not null) throw new InvalidOperationException(); var bpState = yieldTaskCompletionSource.Task.GetAwaiter().GetResult(); builderFieldModule = module; @@ -857,7 +857,7 @@ internal Task SetResumeBreakpoint(DbgThread thread, DbgModule module) var runtime = module.Runtime.GetDotNetRuntime(); if ((runtime.Features & DbgDotNetRuntimeFeatures.ObjectIds) != 0 && (runtime.Features & DbgDotNetRuntimeFeatures.NoAsyncStepObjectId) == 0) { taskObjId = TryGetTaskObjectId(thread); - if (!(taskObjId is null)) + if (taskObjId is not null) taskObjectId = runtime.CreateObjectId(taskObjId, 0); } @@ -914,7 +914,7 @@ internal void ClearYieldBreakpoints() { internal void Dispose() { ClearYieldBreakpoints(); - if (!(resumeBreakpoint is null)) { + if (resumeBreakpoint is not null) { stepper.RemoveBreakpoints(new[] { resumeBreakpoint }); resumeBreakpoint = null; } @@ -938,7 +938,7 @@ public AsyncBreakpointState(DbgDotNetStepperBreakpoint yieldBreakpoint, MethodDe } void YieldBreakpoint_Hit(object? sender, DbgDotNetStepperBreakpointEventArgs e) { - Debug2.Assert(!(Hit is null)); + Debug2.Assert(Hit is not null); e.Pause = true; Hit?.Invoke(this, this); } @@ -1023,7 +1023,7 @@ async Task StepOutCoreAsync(DbgDotNetEngineStepperFrameInfo frame) { bool keepLooping = false; if (IgnoreBaseWrapperMethods) { f = stepper.TryGetFrameInfo(thread); - Debug2.Assert(!(f is null)); + Debug2.Assert(f is not null); if (f is null) return thread; if (!f.TryGetLocation(out var module, out var token, out _)) @@ -1039,16 +1039,16 @@ async Task StepOutCoreAsync(DbgDotNetEngineStepperFrameInfo frame) { async Task StepOutCore2Async(DbgDotNetEngineStepperFrameInfo frame) { runtime.Dispatcher.VerifyAccess(); - Debug2.Assert(!(stepper.Session is null)); + Debug2.Assert(stepper.Session is not null); if (debuggerSettings.AsyncDebugging) { var result = await GetStepRangesAsync(frame, returnValues: false); - if (!(result.DebugInfo?.AsyncInfo is null) && result.DebugInfo.AsyncInfo.SetResultOffset != uint.MaxValue) { + if (result.DebugInfo?.AsyncInfo is not null && result.DebugInfo.AsyncInfo.SetResultOffset != uint.MaxValue) { if (!frame.TryGetLocation(out var module, out var token, out _)) throw new InvalidOperationException(); // When the BP gets hit, we could be on a different thread, so pass in null var returnToAwaiterTask = TryCreateReturnToAwaiterTask(null, module, token, result.DebugInfo.AsyncInfo.SetResultOffset, result.DebugInfo.AsyncInfo.BuilderField?.MDToken.Raw ?? 0); - if (!(returnToAwaiterTask is null)) { + if (returnToAwaiterTask is not null) { stepper.Continue(); return await returnToAwaiterTask; } @@ -1088,7 +1088,7 @@ async Task GetStepRangesAsync(DbgDotNetEngineStepperFr var codeRanges = Array.Empty(); var exactCodeRanges = Array.Empty(); var instructions = Array.Empty(); - if (!(info.DebugInfo is null)) { + if (info.DebugInfo is not null) { var sourceStatement = info.DebugInfo.GetSourceStatementByCodeOffset(offset); DbgILSpan[] ranges; if (sourceStatement is null) @@ -1167,7 +1167,7 @@ void StepCompleted(string? forciblyCanceledErrorMessage, object? tag) { if (forciblyCanceledErrorMessage is null) stepper.OnStepComplete(); stepper.Session = null; - RaiseStepComplete(tag, forciblyCanceledErrorMessage, forciblyCanceled: !(forciblyCanceledErrorMessage is null)); + RaiseStepComplete(tag, forciblyCanceledErrorMessage, forciblyCanceled: forciblyCanceledErrorMessage is not null); } void StepError(string errorMessage, object? tag) { @@ -1210,12 +1210,12 @@ void ForceCancel_EngineThread() { CleanUp(); var oldSession = stepper.Session; stepper.Session = null; - if (!(oldSession is null)) + if (oldSession is not null) stepper.OnCanceled(oldSession); } protected override void CloseCore(DbgDispatcher dispatcher) { - if (!(stepper.Session is null)) { + if (stepper.Session is not null) { if (!runtime.Dispatcher.TryBeginInvoke(() => ForceCancel_EngineThread())) { // process has exited } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/TaskEvalUtils.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/TaskEvalUtils.cs index 68fee0a9d0..e67b30236b 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/TaskEvalUtils.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/Steppers/Engine/TaskEvalUtils.cs @@ -56,7 +56,7 @@ static class TaskEvalUtils { } DmdFieldInfo? builderField = null; - if (!(builderFieldModule is null) && builderFieldToken != 0) + if (builderFieldModule is not null && builderFieldToken != 0) builderField = thisArg.Value.Type.GetField(builderFieldModule, (int)builderFieldToken); if (builderField is null) builderField = TryGetBuilderField(thisArg.Value.Type); @@ -102,7 +102,7 @@ static class TaskEvalUtils { if (fieldType.MetadataNamespace == info.@namespace && fieldType.MetadataName == info.name) return field; } - if (builderField is null && !(fieldType.MetadataName is null) && + if (builderField is null && fieldType.MetadataName is not null && (fieldType.MetadataName.EndsWith("MethodBuilder", StringComparison.Ordinal) || fieldType.MetadataName.EndsWith("MethodBuilder`1", StringComparison.Ordinal))) { builderField = field; @@ -144,14 +144,14 @@ static class TaskEvalUtils { var currInst = builderValue; field = currInst.Type.GetField(KnownMemberNames.AsyncTaskMethodBuilder_Builder_FieldName, DmdBindingFlags.Instance | DmdBindingFlags.Public | DmdBindingFlags.NonPublic); - if (!(field is null)) { + if (field is not null) { fieldResult1 = runtime.LoadField(evalInfo, currInst, field); if (fieldResult1.IsNormalResult) currInst = fieldResult1.Value!; } field = currInst.Type.GetField(KnownMemberNames.Builder_Task_FieldName, DmdBindingFlags.Instance | DmdBindingFlags.Public | DmdBindingFlags.NonPublic); - if (!(field is null)) { + if (field is not null) { fieldResult2 = runtime.LoadField(evalInfo, currInst, field); if (fieldResult2.IsNormalResult && !fieldResult2.Value!.IsNull) return resultValue = fieldResult2.Value; @@ -175,7 +175,7 @@ static class TaskEvalUtils { var prop = builderValue.Type.GetProperty(KnownMemberNames.Builder_ObjectIdForDebugger_PropertyName, DmdBindingFlags.Instance | DmdBindingFlags.Public | DmdBindingFlags.NonPublic); var getMethod = prop?.GetGetMethod(DmdGetAccessorOptions.All); - if (!(getMethod is null) && getMethod.GetMethodSignature().GetParameterTypes().Count == 0) { + if (getMethod is not null && getMethod.GetMethodSignature().GetParameterTypes().Count == 0) { getObjectIdTaskResult = runtime.Call(evalInfo, builderValue, getMethod, Array.Empty(), DbgDotNetInvokeOptions.None); if (getObjectIdTaskResult.IsNormalResult && !getObjectIdTaskResult.Value!.IsNull) return resultValue = getObjectIdTaskResult.Value; @@ -210,11 +210,11 @@ static class TaskEvalUtils { var field = getTaskResult.Value.Type.GetField(KnownMemberNames.ValueTask_Task_FieldName, DmdBindingFlags.Instance | DmdBindingFlags.Public | DmdBindingFlags.NonPublic); if (field is null) field = getTaskResult.Value.Type.GetField(KnownMemberNames.ValueTask_Obj_FieldName, DmdBindingFlags.Instance | DmdBindingFlags.Public | DmdBindingFlags.NonPublic); - if (!(field is null)) { + if (field is not null) { taskFieldResult = runtime.LoadField(evalInfo, getTaskResult.Value, field); if (taskFieldResult.IsNormalResult && !taskFieldResult.Value!.IsNull) { var taskType = taskFieldResult.Value.Type.AppDomain.GetWellKnownType(DmdWellKnownType.System_Threading_Tasks_Task, isOptional: true); - if (!(taskType is null) && taskFieldResult.Value.Type.IsSubclassOf(taskType)) + if (taskType is not null && taskFieldResult.Value.Type.IsSubclassOf(taskType)) return resultValue = taskFieldResult.Value; } } @@ -249,7 +249,7 @@ AsyncStepOutState SupportsAsyncStepOutCore(DmdAppDomain appDomain2) { } public static bool SupportsAsyncStepOut(DmdAppDomain? appDomain) => - !(GetNotifyDebuggerOfWaitCompletionMethod(appDomain) is null); + GetNotifyDebuggerOfWaitCompletionMethod(appDomain) is not null; public static DmdMethodInfo? GetNotifyDebuggerOfWaitCompletionMethod(DmdAppDomain? appDomain) => appDomain is null ? null : GetAsyncStepOutState(appDomain).NotifyDebuggerOfWaitCompletionMethod; @@ -266,7 +266,7 @@ public static (bool success, DbgDotNetValue? taskValue) CallSetNotificationForWa return (false, null); bool calledMethod = TryCallSetNotificationForWaitCompletion(evalInfo, builderValue, value); taskValue = TryGetTaskValue(evalInfo, builderValue); - if (!calledMethod && !(taskValue is null)) + if (!calledMethod && taskValue is not null) calledMethod = TryCallSetNotificationForWaitCompletion(evalInfo, taskValue, value); if (!calledMethod) return (false, null); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/UI/UIDispatcher.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/UI/UIDispatcher.cs index b526cf5cf0..ba72bb90ff 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/UI/UIDispatcher.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger.DotNet/UI/UIDispatcher.cs @@ -30,7 +30,7 @@ sealed class UIDispatcher { static readonly FieldInfo? _disableProcessingCountFieldInfo; static UIDispatcher() { _disableProcessingCountFieldInfo = typeof(Dispatcher).GetField("_disableProcessingCount", BindingFlags.NonPublic | BindingFlags.Instance); - Debug2.Assert(!(_disableProcessingCountFieldInfo is null) && _disableProcessingCountFieldInfo.FieldType == typeof(int)); + Debug2.Assert(_disableProcessingCountFieldInfo is not null && _disableProcessingCountFieldInfo.FieldType == typeof(int)); } Dispatcher Dispatcher { get; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/DbgHookedNativeFunctionProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/DbgHookedNativeFunctionProviderImpl.cs index 5fd4f1cccc..f48b2bac2a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/DbgHookedNativeFunctionProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/DbgHookedNativeFunctionProviderImpl.cs @@ -76,9 +76,9 @@ public override DbgHookedNativeFunction GetFunction(string dllName, string funcN } if (info.ExportedFunctions.TryGet(funcName, out var address)) { var result = PatchAPI(address, info.Address, info.EndAddress); - if (!(result.ErrorMessage is null)) + if (result.ErrorMessage is not null) throw new DbgHookException(result.ErrorMessage); - Debug2.Assert(!(result.Block is null)); + Debug2.Assert(result.Block is not null); simplePatches.Add(result.SimplePatch); return new DbgHookedNativeFunctionImpl(result.Block, result.NewFunctionAddress, address); } @@ -93,9 +93,9 @@ public override DbgHookedNativeFunction GetFunction(string dllName, string funcN if (!hookedFuncs.Add((dllName, funcName))) throw new DbgHookException($"Some code tried to hook the same func twice: {dllName}: {funcName}"); var result = PatchAPI(address, address, address + 1); - if (!(result.ErrorMessage is null)) + if (result.ErrorMessage is not null) throw new DbgHookException(result.ErrorMessage); - Debug2.Assert(!(result.Block is null)); + Debug2.Assert(result.Block is not null); simplePatches.Add(result.SimplePatch); return new DbgHookedNativeFunctionImpl(result.Block, result.NewFunctionAddress, address); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/PreventNativeDebuggerDetection.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/PreventNativeDebuggerDetection.cs index e652fc9f53..d53bc7b940 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/PreventNativeDebuggerDetection.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/PreventNativeDebuggerDetection.cs @@ -102,7 +102,7 @@ void HookFuncs(DbgProcess process) { catch (DbgHookException ex) { errorMessage = ex.Message ?? "???"; } - if (!(errorMessage is null)) + if (errorMessage is not null) errors.Add($"{lz.Metadata.Dll}!{lz.Metadata.Function}: {errorMessage}"); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/ProcessMemoryBlockAllocator.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/ProcessMemoryBlockAllocator.cs index eaebb90547..dda1a42da2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/ProcessMemoryBlockAllocator.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/AntiAntiDebug/ProcessMemoryBlockAllocator.cs @@ -72,7 +72,7 @@ static bool IsClose64(ulong start, ulong end, ulong addr) { public ProcessMemoryBlock Allocate(ulong moduleAddress, ulong moduleEndAddress) { var mem = GetCloseBlock(moduleAddress, moduleEndAddress); - if (!(mem is null)) + if (mem is not null) return mem; IntPtr memPtr; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Attach/AttachableProcessInfo.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Attach/AttachableProcessInfo.cs index 78cba92829..4f88bd85c2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Attach/AttachableProcessInfo.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Attach/AttachableProcessInfo.cs @@ -95,7 +95,7 @@ sealed class AttachableProcessInfo { DbgOperatingSystem? operatingSystem = default; var process = processProvider.GetProcess(attachProgramOptions.ProcessId); - if (!(process is null)) { + if (process is not null) { if (attachProgramOptions.CommandLine is null) commandLine = Win32CommandLineProvider.TryGetCommandLine(process.Handle); if (attachProgramOptions.Title is null) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Attach/AttachableProcessesServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Attach/AttachableProcessesServiceImpl.cs index b8be786798..66c1a46299 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Attach/AttachableProcessesServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Attach/AttachableProcessesServiceImpl.cs @@ -133,7 +133,7 @@ void AddOptions(AttachProgramOptions options) { throw new ArgumentNullException(nameof(options)); lock (lockObj) { var info = AttachableProcessInfo.Create(processProvider, options); - if (!(info is null) && IsMatch(info)) + if (info is not null && IsMatch(info)) result.Add(new AttachableProcessImpl(dbgManager.Value, options, info)); } } @@ -161,11 +161,11 @@ bool IsValidProcess(Process process) { bool IsValidProcessId(int pid) => processIds.Length == 0 || Array.IndexOf(processIds, pid) >= 0; void EnumeratorCompleted(ProviderInfo info, bool canceled, Exception? ex) { - Debug2.Assert(!(taskCompletionSource is null)); + Debug2.Assert(taskCompletionSource is not null); AttachableProcess[]? attachableProcesses; lock (lockObj) { wasCanceled |= canceled; - if (!(ex is null)) { + if (ex is not null) { if (thrownExceptions is null) thrownExceptions = new List(); thrownExceptions.Add(ex); @@ -179,8 +179,8 @@ void EnumeratorCompleted(ProviderInfo info, bool canceled, Exception? ex) { else attachableProcesses = null; } - if (!(attachableProcesses is null)) { - if (!(thrownExceptions is null)) + if (attachableProcesses is not null) { + if (thrownExceptions is not null) taskCompletionSource.SetException(thrownExceptions); else if (wasCanceled) taskCompletionSource.SetCanceled(); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointConditionsFormatter.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointConditionsFormatter.cs index 52a372192f..8ddb8dafdb 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointConditionsFormatter.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointConditionsFormatter.cs @@ -99,7 +99,7 @@ public override void Write(IDbgTextWriter output, DbgCodeBreakpointHitCount? hit } void WriteCurrentHitCountValue(IDbgTextWriter output, int? currentHitCount) { - if (!(currentHitCount is null)) { + if (currentHitCount is not null) { output.Write(DbgTextColor.Comment, " "); output.Write(DbgTextColor.Punctuation, "("); WriteArgumentAndText(output, DbgTextColor.Number, dnSpy_Debugger_Resources.Breakpoint_HitCount_CurrentHitCountValue, currentHitCount.Value.ToString()); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointImageUtilities.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointImageUtilities.cs index f80a6acb1a..f5b6ee5192 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointImageUtilities.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointImageUtilities.cs @@ -47,7 +47,7 @@ enum BreakpointKind { static class BreakpointImageUtilities { public static BreakpointKind GetBreakpointKind(DbgCodeBreakpoint breakpoint) { var settings = breakpoint.Settings; - bool isAdvanced = !(settings.Condition is null) || !(settings.HitCount is null) || !(settings.Filter is null); + bool isAdvanced = settings.Condition is not null || settings.HitCount is not null || settings.Filter is not null; var msg = breakpoint.BoundBreakpointsMessage; if (settings.Trace is null || !settings.Trace.Value.Continue) { switch (msg.Severity) { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointsSerializer.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointsSerializer.cs index 7bd0dad6dd..1d9a40b1b0 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointsSerializer.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/BreakpointsSerializer.cs @@ -113,15 +113,15 @@ public void Save(DbgCodeBreakpoint[] breakpoints) { var bpSettings = bp.Settings; bpSect.Attribute("IsEnabled", bpSettings.IsEnabled); dbgCodeLocationSerializerService.Serialize(bpSect.CreateSection("BPL"), location); - if (!(bpSettings.Condition is null)) + if (bpSettings.Condition is not null) Save(bpSect.CreateSection("Condition"), bpSettings.Condition.Value); - if (!(bpSettings.HitCount is null)) + if (bpSettings.HitCount is not null) Save(bpSect.CreateSection("HitCount"), bpSettings.HitCount.Value); - if (!(bpSettings.Filter is null)) + if (bpSettings.Filter is not null) Save(bpSect.CreateSection("Filter"), bpSettings.Filter.Value); - if (!(bpSettings.Trace is null)) + if (bpSettings.Trace is not null) Save(bpSect.CreateSection("Trace"), bpSettings.Trace.Value); - if (!(bpSettings.Labels is null) && bpSettings.Labels.Count != 0) + if (bpSettings.Labels is not null && bpSettings.Labels.Count != 0) SaveLabels(bpSect, bpSettings.Labels.ToArray()); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/BreakpointBreakChecker.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/BreakpointBreakChecker.cs index b3f01bb051..2a1e4bc4a7 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/BreakpointBreakChecker.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/BreakpointBreakChecker.cs @@ -67,7 +67,7 @@ bool ShouldBreak(DbgBoundCodeBreakpoint boundBreakpoint, DbgThread? thread) { if (settings.Filter is DbgCodeBreakpointFilter filter) { checkRes = dbgCodeBreakpointFilterChecker.Value.ShouldBreak(boundBreakpoint, thread, filter); - if (!(checkRes.ErrorMessage is null)) { + if (checkRes.ErrorMessage is not null) { boundBreakpoint.Process.DbgManager.ShowError(checkRes.ErrorMessage); return true; } @@ -77,7 +77,7 @@ bool ShouldBreak(DbgBoundCodeBreakpoint boundBreakpoint, DbgThread? thread) { if (settings.Condition is DbgCodeBreakpointCondition condition) { checkRes = dbgCodeBreakpointConditionChecker.Value.ShouldBreak(boundBreakpoint, thread, condition); - if (!(checkRes.ErrorMessage is null)) { + if (checkRes.ErrorMessage is not null) { boundBreakpoint.Process.DbgManager.ShowError(checkRes.ErrorMessage); return true; } @@ -89,7 +89,7 @@ bool ShouldBreak(DbgBoundCodeBreakpoint boundBreakpoint, DbgThread? thread) { int currentHitCount = dbgCodeBreakpointHitCountService.Value.Hit_DbgThread(boundBreakpoint.Breakpoint); if (settings.HitCount is DbgCodeBreakpointHitCount hitCount) { checkRes = dbgCodeBreakpointHitCountChecker.Value.ShouldBreak(boundBreakpoint, thread, hitCount, currentHitCount); - if (!(checkRes.ErrorMessage is null)) { + if (checkRes.ErrorMessage is not null) { boundBreakpoint.Process.DbgManager.ShowError(checkRes.ErrorMessage); return true; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgCodeBreakpointConditionChecker.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgCodeBreakpointConditionChecker.cs index fdfa240044..f6e30ac83d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgCodeBreakpointConditionChecker.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgCodeBreakpointConditionChecker.cs @@ -89,10 +89,10 @@ abstract class SavedValue { if (value.HasRawValue && value.RawValue is null) return new SimpleSavedValue(value.ValueType, value.RawValue, valueType); var objectId = dbgObjectIdService.CreateObjectId(value, CreateObjectIdOptions.Hidden); - if (!(objectId is null)) + if (objectId is not null) return new ObjectIdSavedValue(dbgObjectIdService, objectId); var addr = value.GetRawAddressValue(onlyDataAddress: false); - if (!(addr is null)) + if (addr is not null) return new AddressSavedValue(addr.Value, valueType); return null; @@ -137,7 +137,7 @@ public SimpleSavedValue(DbgSimpleValueType type, object? value, string valueType public override bool Equals(DbgEvaluationInfo evalInfo, SavedValue other) { var obj = other as SimpleSavedValue; - return !(obj is null) && + return obj is not null && obj.type == type && Equals(obj.value, value) && (value is null || obj.valueType == valueType); @@ -192,7 +192,7 @@ public override bool Equals(DbgEvaluationInfo evalInfo, SavedValue other) { public override DbgCodeBreakpointCheckResult ShouldBreak(DbgBoundCodeBreakpoint boundBreakpoint, DbgThread thread, DbgCodeBreakpointCondition condition) { var expression = condition.Condition; - Debug2.Assert(!(expression is null)); + Debug2.Assert(expression is not null); if (expression is null) return new DbgCodeBreakpointCheckResult("Missing expression"); @@ -208,7 +208,7 @@ public override DbgCodeBreakpointCheckResult ShouldBreak(DbgBoundCodeBreakpoint var state = GetState(boundBreakpoint, language, frame, condition, cancellationToken); var evalInfo = new DbgEvaluationInfo(state.Context!, frame, cancellationToken); var evalRes = language.ExpressionEvaluator.Evaluate(evalInfo, expression, DbgEvaluationOptions.Expression, state.ExpressionEvaluatorState!); - if (!(evalRes.Error is null)) + if (evalRes.Error is not null) return new DbgCodeBreakpointCheckResult(evalRes.Error); value = evalRes.Value!; @@ -254,9 +254,9 @@ public override DbgCodeBreakpointCheckResult ShouldBreak(DbgBoundCodeBreakpoint } } finally { - if (!(frame is null)) + if (frame is not null) thread.Process.DbgManager.Close(frame); - if (!(value is null)) + if (value is not null) thread.Process.DbgManager.Close(value); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgCodeBreakpointFilterChecker.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgCodeBreakpointFilterChecker.cs index 643e224170..b41a590b84 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgCodeBreakpointFilterChecker.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgCodeBreakpointFilterChecker.cs @@ -68,7 +68,7 @@ public override DbgCodeBreakpointCheckResult ShouldBreak(DbgBoundCodeBreakpoint } var expr = filter.Filter; - Debug2.Assert(!(expr is null)); + Debug2.Assert(expr is not null); if (expr is null) return new DbgCodeBreakpointCheckResult("Missing expression"); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgFilterExpressionEvaluatorService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgFilterExpressionEvaluatorService.cs index 8f84a6f5f0..08554431c6 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgFilterExpressionEvaluatorService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/DbgFilterExpressionEvaluatorService.cs @@ -36,7 +36,7 @@ abstract class DbgFilterExpressionEvaluatorService { sealed class DbgFilterExpressionEvaluatorServiceImpl : DbgFilterExpressionEvaluatorService { readonly Lazy? dbgFilterExpressionEvaluator; - public override bool HasExpressionEvaluator => !(dbgFilterExpressionEvaluator is null); + public override bool HasExpressionEvaluator => dbgFilterExpressionEvaluator is not null; [ImportingConstructor] DbgFilterExpressionEvaluatorServiceImpl([ImportMany] IEnumerable> dbgFilterExpressionEvaluators) => @@ -47,7 +47,7 @@ sealed class DbgFilterExpressionEvaluatorServiceImpl : DbgFilterExpressionEvalua public override string? IsValidExpression(string expr) { if (expr is null) throw new ArgumentNullException(nameof(expr)); - if (!(dbgFilterExpressionEvaluator is null)) + if (dbgFilterExpressionEvaluator is not null) return dbgFilterExpressionEvaluator.Value.IsValidExpression(expr); return NoFEEError; } @@ -65,7 +65,7 @@ public override void Write(IDbgTextWriter output, string expr) { throw new ArgumentNullException(nameof(output)); if (expr is null) throw new ArgumentNullException(nameof(expr)); - if (!(dbgFilterExpressionEvaluator is null)) + if (dbgFilterExpressionEvaluator is not null) dbgFilterExpressionEvaluator.Value.Write(output, expr); else output.Write(DbgTextColor.Error, expr); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/TracepointMessageCreator.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/TracepointMessageCreator.cs index f6a8b5290b..d3059309cf 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/TracepointMessageCreator.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/CondChecker/TracepointMessageCreator.cs @@ -137,7 +137,7 @@ public override string Create(DbgBoundCodeBreakpoint boundBreakpoint, DbgThread int maxFrames = parsed.MaxFrames; if (parsed.Evaluates && maxFrames < 1) maxFrames = 1; - if (maxFrames > 0 && !(thread is null)) { + if (maxFrames > 0 && thread is not null) { stackWalker = thread.CreateStackWalker(); stackFrames = stackWalker.GetNextStackFrames(maxFrames); } @@ -147,7 +147,7 @@ public override string Create(DbgBoundCodeBreakpoint boundBreakpoint, DbgThread finally { this.boundBreakpoint = null; this.thread = null; - if (!(stackWalker is null)) { + if (stackWalker is not null) { stackWalker.Close(); boundBreakpoint.Process.DbgManager.Close(stackFrames!); stackWalker = null; @@ -178,7 +178,7 @@ ParsedTracepointMessage GetOrCreate(string text) { } void Write(ParsedTracepointMessage parsed, string tracepointMessage) { - Debug2.Assert(!(boundBreakpoint is null)); + Debug2.Assert(boundBreakpoint is not null); DbgStackFrame? frame; foreach (var part in parsed.Parts) { switch (part.Kind) { @@ -194,7 +194,7 @@ void Write(ParsedTracepointMessage parsed, string tracepointMessage) { var language = dbgLanguageService.GetCurrentLanguage(thread!.Runtime.RuntimeKindGuid); var cancellationToken = CancellationToken.None; var state = GetTracepointEvalState(boundBreakpoint, language, frame, tracepointMessage, cancellationToken); - Debug2.Assert(!(part.String is null)); + Debug2.Assert(part.String is not null); var eeState = state.GetExpressionEvaluatorState(part.String); var evalInfo = new DbgEvaluationInfo(state.Context!, frame, cancellationToken); var evalRes = language.ExpressionEvaluator.Evaluate(evalInfo, part.String, DbgEvaluationOptions.Expression, eeState); @@ -224,7 +224,7 @@ void Write(ParsedTracepointMessage parsed, string tracepointMessage) { case TracepointMessageKind.WriteCallerModule: var module = TryGetFrame(part.Number)?.Module; - if (!(module is null)) + if (module is not null) Write(module.Filename); else WriteError(); @@ -232,7 +232,7 @@ void Write(ParsedTracepointMessage parsed, string tracepointMessage) { case TracepointMessageKind.WriteCallerOffset: frame = TryGetFrame(part.Number); - if (!(frame is null)) { + if (frame is not null) { Write("0x"); Write(frame.FunctionOffset.ToString("X8")); } @@ -242,7 +242,7 @@ void Write(ParsedTracepointMessage parsed, string tracepointMessage) { case TracepointMessageKind.WriteCallerToken: frame = TryGetFrame(part.Number); - if (!(frame is null) && frame.HasFunctionToken) { + if (frame is not null && frame.HasFunctionToken) { Write("0x"); Write(frame.FunctionToken.ToString("X8")); } @@ -312,7 +312,7 @@ void Write(ParsedTracepointMessage parsed, string tracepointMessage) { void WriteFrame(int index, DbgStackFrameFormatterOptions frameOptions) => WriteFrame(TryGetFrame(index), frameOptions); void WriteFrame(DbgStackFrame? frame, DbgStackFrameFormatterOptions frameOptions) { - if (!(frame is null)) { + if (frame is not null) { if (!debuggerSettings.UseHexadecimal) frameOptions |= DbgStackFrameFormatterOptions.Decimal; if (debuggerSettings.UseDigitSeparators) @@ -427,7 +427,7 @@ TracepointEvalState GetTracepointEvalState(DbgBoundCodeBreakpoint boundBreakpoin } void Write(DbgEvaluationInfo evalInfo, DbgLanguage language, in DbgEvaluationResult evalRes) { - if (!(evalRes.Error is null)) { + if (evalRes.Error is not null) { Write("<<<"); Write(PredefinedEvaluationErrorMessagesHelper.GetErrorMessage(evalRes.Error)); Write(">>>"); @@ -435,7 +435,7 @@ void Write(DbgEvaluationInfo evalInfo, DbgLanguage language, in DbgEvaluationRes else { var options = GetValueFormatterOptions(evalRes.FormatSpecifiers, isEdit: false); const CultureInfo? cultureInfo = null; - Debug2.Assert(!(evalRes.Value is null)); + Debug2.Assert(evalRes.Value is not null); language.Formatter.FormatValue(evalInfo, stringBuilderTextColorWriter, evalRes.Value, options, cultureInfo); evalRes.Value.Close(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgBreakpointLocationFormatterService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgBreakpointLocationFormatterService.cs index d267c7de66..13d7d603ce 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgBreakpointLocationFormatterService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgBreakpointLocationFormatterService.cs @@ -45,7 +45,7 @@ public override DbgBreakpointLocationFormatter GetFormatter(DbgCodeLocation loca foreach (var lz in dbgBreakpointLocationFormatterProviders) { if (Array.IndexOf(lz.Metadata.Types, type) >= 0) { var formatter = lz.Value.Create(location); - if (!(formatter is null)) + if (formatter is not null) return formatter; } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgBreakpointLocationSerializerService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgBreakpointLocationSerializerService.cs index 36f4aa609f..b28c446f28 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgBreakpointLocationSerializerService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgBreakpointLocationSerializerService.cs @@ -48,7 +48,7 @@ sealed class DbgCodeLocationSerializerServiceImpl : DbgCodeLocationSerializerSer return null; } - public override bool CanSerialize(DbgCodeLocation location) => !(TryGetSerializer(location.Type) is null); + public override bool CanSerialize(DbgCodeLocation location) => TryGetSerializer(location.Type) is not null; public override void Serialize(ISettingsSection section, DbgCodeLocation location) { if (section is null) @@ -58,7 +58,7 @@ public override void Serialize(ISettingsSection section, DbgCodeLocation locatio var bpType = location.Type; var serializer = TryGetSerializer(bpType); - Debug2.Assert(!(serializer is null)); + Debug2.Assert(serializer is not null); if (serializer is null) return; @@ -71,11 +71,11 @@ public override void Serialize(ISettingsSection section, DbgCodeLocation locatio return null; var typeFullName = section.Attribute("__BPT"); - Debug2.Assert(!(typeFullName is null)); + Debug2.Assert(typeFullName is not null); if (typeFullName is null) return null; var serializer = TryGetSerializer(typeFullName); - Debug2.Assert(!(serializer is null)); + Debug2.Assert(serializer is not null); if (serializer is null) return null; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointHitCountServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointHitCountServiceImpl.cs index 8fb50909ed..0ec3315eb8 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointHitCountServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointHitCountServiceImpl.cs @@ -113,7 +113,7 @@ void DbgCodeBreakpointsService_BreakpointsChanged(object? sender, DbgCollectionC public override int Hit_DbgThread(DbgCodeBreakpoint breakpoint) { dbgDispatcherProvider.VerifyAccess(); - Debug2.Assert(!(dbgManager is null)); + Debug2.Assert(dbgManager is not null); if (breakpoint is null) throw new ArgumentNullException(nameof(breakpoint)); int hitCount; @@ -198,7 +198,7 @@ void Reset_DbgThread(DbgCodeBreakpoint[] breakpoints) { } if (raisePendingEvent) FlushPendingHitCountChanged_DbgThread(); - if (!(updated is null)) + if (updated is not null) HitCountChanged?.Invoke(this, new DbgHitCountChangedEventArgs(new ReadOnlyCollection(updated))); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointImpl.cs index ecd2387e9d..6f138fb1c0 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointImpl.cs @@ -225,7 +225,7 @@ DbgBoundCodeBreakpointMessage CalculateBoundBreakpointsMessage_NoLock() { DbgBoundCodeBreakpointMessage? warningMsg = null; foreach (var bp in boundCodeBreakpoints) { var msg = bp.Message; - Debug2.Assert(!(msg.Message is null)); + Debug2.Assert(msg.Message is not null); if (msg.Message is null) continue; switch (msg.Severity) { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointsServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointsServiceImpl.cs index e100f0e206..138dd33b65 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointsServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointsServiceImpl.cs @@ -78,7 +78,7 @@ void ModifyCore(DbgCodeBreakpointAndSettings[] settings) { lock (lockObj) { foreach (var info in settings) { var bpImpl = info.Breakpoint as DbgCodeBreakpointImpl; - Debug2.Assert(!(bpImpl is null)); + Debug2.Assert(bpImpl is not null); if (bpImpl is null) continue; Debug.Assert(breakpoints.Contains(bpImpl)); @@ -97,7 +97,7 @@ void ModifyCore(DbgCodeBreakpointAndSettings[] settings) { } if (bps.Count > 0) BreakpointsModified?.Invoke(this, new DbgBreakpointsModifiedEventArgs(new ReadOnlyCollection(bps))); - if (!(updatedBreakpoints is null)) { + if (updatedBreakpoints is not null) { foreach (var bp in updatedBreakpoints) bp.RaiseBoundBreakpointsMessageChanged_DbgThread(); BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection(updatedBreakpoints.ToArray()))); @@ -164,13 +164,13 @@ void AddCore(List breakpoints, List? objsToClo } } } - if (!(objsToClose is null)) { + if (objsToClose is not null) { foreach (var obj in objsToClose) obj.Close(dbgDispatcherProvider.Dispatcher); } if (added.Count > 0) BreakpointsChanged?.Invoke(this, new DbgCollectionChangedEventArgs(added, added: true)); - if (!(updatedBreakpoints is null)) { + if (updatedBreakpoints is not null) { foreach (var bp in updatedBreakpoints) bp.RaiseBoundBreakpointsMessageChanged_DbgThread(); BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection(updatedBreakpoints.ToArray()))); @@ -189,7 +189,7 @@ void RemoveCore(DbgCodeBreakpoint[] breakpoints) { lock (lockObj) { foreach (var bp in breakpoints) { var bpImpl = bp as DbgCodeBreakpointImpl; - Debug2.Assert(!(bpImpl is null)); + Debug2.Assert(bpImpl is not null); if (bpImpl is null) continue; if (!this.breakpoints.Contains(bpImpl)) @@ -290,7 +290,7 @@ static Dictionary> CreateBre for (int i = 0; i < boundBreakpoints.Count; i++) { var bound = boundBreakpoints[i]; var bpImpl = bound.Breakpoint as DbgCodeBreakpointImpl; - Debug2.Assert(!(bpImpl is null)); + Debug2.Assert(bpImpl is not null); if (bpImpl is null) continue; if (!dict.TryGetValue(bpImpl, out var list)) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/RemoveTemporaryBreakpoints.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/RemoveTemporaryBreakpoints.cs index e787c48697..241c0ca45a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/RemoveTemporaryBreakpoints.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/RemoveTemporaryBreakpoints.cs @@ -45,7 +45,7 @@ void DbgManager_IsDebuggingChanged(object? sender, EventArgs e) { bpsToRemove.Add(bp); } } - if (!(bpsToRemove is null)) + if (bpsToRemove is not null) dbgCodeBreakpointsService.Value.Remove(bpsToRemove.ToArray()); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/ResetHitCount.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/ResetHitCount.cs index e464a9aaec..c61dfe3a28 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/ResetHitCount.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/ResetHitCount.cs @@ -40,7 +40,7 @@ void IDbgCodeBreakpointsServiceListener.Initialize(DbgCodeBreakpointsService dbg void DbgCodeBreakpointsService_BreakpointsModified(object? sender, DbgBreakpointsModifiedEventArgs e) { List? resetThese = null; foreach (var info in e.Breakpoints) { - if (!(info.OldSettings.HitCount is null)) + if (info.OldSettings.HitCount is not null) continue; var breakpoint = info.Breakpoint; if (breakpoint.Settings.HitCount is null) @@ -49,7 +49,7 @@ void DbgCodeBreakpointsService_BreakpointsModified(object? sender, DbgBreakpoint resetThese = new List(); resetThese.Add(breakpoint); } - if (!(resetThese is null)) + if (resetThese is not null) dbgCodeBreakpointHitCountService.Value.Reset(resetThese.ToArray()); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphPopupControl.xaml.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphPopupControl.xaml.cs index 981474ab05..05c4ebe4d6 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphPopupControl.xaml.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphPopupControl.xaml.cs @@ -45,7 +45,7 @@ public BreakpointGlyphPopupControl(BreakpointGlyphPopupVM vm, FrameworkElement g } void RemoveFadeOut() { - if (!(fadeOutStoryboard is null)) { + if (fadeOutStoryboard is not null) { fadeOutStoryboard.Completed -= FadeOutStoryboard_Completed; fadeOutStoryboard.Stop(); fadeOutStoryboard = null; @@ -69,7 +69,7 @@ void BreakpointGlyphPopupControl_Loaded(object? sender, RoutedEventArgs e) { if (loaded) return; loaded = true; - if (!(focusedElement is null)) + if (focusedElement is not null) focusedElement.LostKeyboardFocus += FocusedElement_LostKeyboardFocus; glyphMargin.MouseEnter += GlyphMargin_MouseEnter; glyphMargin.MouseLeave += GlyphMargin_MouseLeave; @@ -108,7 +108,7 @@ void StopTimer() { void StartTimerIfNeeded() { if (IsMouseWithinControls) return; - if (!(timer is null)) + if (timer is not null) return; timer = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher); timer.Tick += Timer_Tick; @@ -121,7 +121,7 @@ void ClosePopup() { if (Parent is Popup popup) popup.IsOpen = false; - if (!(focusedElement is null)) + if (focusedElement is not null) focusedElement.LostKeyboardFocus -= FocusedElement_LostKeyboardFocus; glyphMargin.MouseEnter -= GlyphMargin_MouseEnter; glyphMargin.MouseLeave -= GlyphMargin_MouseLeave; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphTextMarkerHandler.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphTextMarkerHandler.cs index c3c17c38f5..8c88d2a7b2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphTextMarkerHandler.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphTextMarkerHandler.cs @@ -83,31 +83,31 @@ string GetToolTipContent(DbgCodeBreakpoint breakpoint, ITextView textView, Snaps WriteLocation(output, breakpoint, textView, span); const string INDENTATION = " "; - if (!(breakpoint.Condition is null) || !(breakpoint.HitCount is null) || !(breakpoint.Filter is null)) { + if (breakpoint.Condition is not null || breakpoint.HitCount is not null || breakpoint.Filter is not null) { output.WriteLine(); output.WriteLine(); output.Write(DbgTextColor.Text, dnSpy_Debugger_Resources.GlyphToolTip_Conditions); - if (!(breakpoint.Condition is null)) { + if (breakpoint.Condition is not null) { output.WriteLine(); output.Write(DbgTextColor.Text, INDENTATION); breakpointConditionsFormatter.WriteToolTip(output, breakpoint.Condition.Value); } - if (!(breakpoint.HitCount is null)) { + if (breakpoint.HitCount is not null) { output.WriteLine(); output.Write(DbgTextColor.Text, INDENTATION); breakpointConditionsFormatter.WriteToolTip(output, breakpoint.HitCount.Value, dbgCodeBreakpointHitCountService.GetHitCount(breakpoint)); } - if (!(breakpoint.Filter is null)) { + if (breakpoint.Filter is not null) { output.WriteLine(); output.Write(DbgTextColor.Text, INDENTATION); breakpointConditionsFormatter.WriteToolTip(output, breakpoint.Filter.Value); } } - if (!(breakpoint.Trace is null)) { + if (breakpoint.Trace is not null) { output.WriteLine(); output.WriteLine(); output.Write(DbgTextColor.Text, dnSpy_Debugger_Resources.GlyphToolTip_Actions); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphTextMarkerLocationProviderService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphTextMarkerLocationProviderService.cs index fdb5db73db..dcef41198e 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphTextMarkerLocationProviderService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointGlyphTextMarkerLocationProviderService.cs @@ -43,7 +43,7 @@ sealed class DbgBreakpointGlyphTextMarkerLocationProviderServiceImpl : DbgBreakp throw new ArgumentNullException(nameof(breakpoint)); foreach (var lz in dbgBreakpointGlyphTextMarkerLocationProviders) { var loc = lz.Value.GetLocation(breakpoint); - if (!(loc is null)) + if (loc is not null) return loc; } return null; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointMarker.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointMarker.cs index ec248dc780..c2d6b5abc7 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointMarker.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/BreakpointMarker.cs @@ -133,7 +133,7 @@ void OnBreakpointsAdded_UI(DbgCollectionChangedEventArgs e) { if (bp.IsHidden) continue; var location = dbgBreakpointGlyphTextMarkerLocationProviderService.GetLocation(bp); - if (!(location is null)) { + if (location is not null) { bp.GetOrCreateData(() => new BreakpointData(location)); UpdateMarker(bp); continue; @@ -177,10 +177,10 @@ void UpdateMarker(DbgCodeBreakpoint bp) { return; var info = breakpointInfos![(int)BreakpointImageUtilities.GetBreakpointKind(bp)]; - if (data.Info == info && !(data.Marker is null)) + if (data.Info == info && data.Marker is not null) return; data.Info = info; - if (!(data.Marker is null)) + if (data.Marker is not null) glyphTextMarkerService.Value.Remove(data.Marker); data.Marker = glyphTextMarkerService.Value.AddMarker(data.Location, info.ImageReference, info.MarkerTypeName, info.SelectedMarkerTypeName, info.ClassificationType, info.ZIndex, bp, breakpointGlyphTextMarkerHandler, textViewFilter); @@ -203,7 +203,7 @@ void UpdateMarker(DbgCodeBreakpoint bp) { } } } - if (!(locations is null)) + if (locations is not null) return new DbgTextViewBreakpointLocationResult(locations.Select(a => a.Clone()).ToArray(), new VirtualSnapshotSpan(locationSpan)); return null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/TextViewBreakpointService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/TextViewBreakpointService.cs index 0467822f43..c184c306c3 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/TextViewBreakpointService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/TextEditor/TextViewBreakpointService.cs @@ -98,7 +98,7 @@ LocationsResult GetLocations(IDocumentTab? tab, VirtualSnapshotPoint? position) var textView = GetTextView(tab); if (textView is null) return new LocationsResult(dbgManager, null, allLocations); - Debug2.Assert(!(tab is null)); + Debug2.Assert(tab is not null); var pos = position ?? textView.Caret.Position.VirtualBufferPosition; if (pos.Position.Snapshot != textView.TextSnapshot) throw new ArgumentException(); @@ -106,7 +106,7 @@ LocationsResult GetLocations(IDocumentTab? tab, VirtualSnapshotPoint? position) foreach (var loc in dbgTextViewCodeLocationService.Value.CreateLocation(tab, textView, pos)) UpdateResult(allLocations, textView, ref res, loc, useIfSameSpan: false); SnapshotSpan span; - if (!(res is null)) { + if (res is not null) { var resSpan = res.Value.Span.SnapshotSpan; var newStart = Min(pos.Position, resSpan.Start); var newEnd = Max(pos.Position, resSpan.End); @@ -191,7 +191,7 @@ public ToggleCreateBreakpointInfoResult(Lazy dbgManager, ToggleCreat } public void Dispose() { - if (!(locations is null) && locations.Length > 0) + if (locations is not null && locations.Length > 0) dbgManager.Value.Close(locations); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/BreakpointsSerializer.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/BreakpointsSerializer.cs index 7967ee4a1d..8f38d3bcfc 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/BreakpointsSerializer.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/BreakpointsSerializer.cs @@ -61,13 +61,13 @@ public void Save(DbgModuleBreakpoint[] breakpoints) { bpSect.Attribute("IsEnabled", bpSettings.IsEnabled); if (!string.IsNullOrEmpty(bpSettings.ModuleName)) bpSect.Attribute("ModuleName", bpSettings.ModuleName); - if (!(bpSettings.IsDynamic is null)) + if (bpSettings.IsDynamic is not null) bpSect.Attribute("IsDynamic", bpSettings.IsDynamic); - if (!(bpSettings.IsInMemory is null)) + if (bpSettings.IsInMemory is not null) bpSect.Attribute("IsInMemory", bpSettings.IsInMemory); - if (!(bpSettings.IsLoaded is null)) + if (bpSettings.IsLoaded is not null) bpSect.Attribute("IsLoaded", bpSettings.IsLoaded); - if (!(bpSettings.Order is null)) + if (bpSettings.Order is not null) bpSect.Attribute("Order", bpSettings.Order); if (!string.IsNullOrEmpty(bpSettings.AppDomainName)) bpSect.Attribute("AppDomainName", bpSettings.AppDomainName); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/DbgModuleBreakpointImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/DbgModuleBreakpointImpl.cs index fa5d644e27..6f27b8c1b0 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/DbgModuleBreakpointImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/DbgModuleBreakpointImpl.cs @@ -134,13 +134,13 @@ internal bool IsMatch(in DbgModuleBreakpointInfo module) { lock (lockObj) { if (!settings.IsEnabled) return false; - if (!(settings.IsDynamic is null) && settings.IsDynamic.Value != module.IsDynamic) + if (settings.IsDynamic is not null && settings.IsDynamic.Value != module.IsDynamic) return false; - if (!(settings.IsInMemory is null) && settings.IsInMemory.Value != module.IsInMemory) + if (settings.IsInMemory is not null && settings.IsInMemory.Value != module.IsInMemory) return false; - if (!(settings.IsLoaded is null) && settings.IsLoaded.Value != module.IsLoaded) + if (settings.IsLoaded is not null && settings.IsLoaded.Value != module.IsLoaded) return false; - if (!(settings.Order is null) && settings.Order.Value != module.Order) + if (settings.Order is not null && settings.Order.Value != module.Order) return false; if (!WildcardsMatch(settings.ModuleName, module.ModuleName, ref moduleNameRegexWeakRef)) return false; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/DbgModuleBreakpointsServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/DbgModuleBreakpointsServiceImpl.cs index 8b624ae9bf..3a468595f6 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/DbgModuleBreakpointsServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Modules/DbgModuleBreakpointsServiceImpl.cs @@ -65,7 +65,7 @@ void ModifyCore(DbgModuleBreakpointAndSettings[] settings) { lock (lockObj) { foreach (var info in settings) { var bpImpl = info.Breakpoint as DbgModuleBreakpointImpl; - Debug2.Assert(!(bpImpl is null)); + Debug2.Assert(bpImpl is not null); if (bpImpl is null) continue; Debug.Assert(breakpoints.Contains(bpImpl)); @@ -135,7 +135,7 @@ void RemoveCore(DbgModuleBreakpoint[] breakpoints) { lock (lockObj) { foreach (var bp in breakpoints) { var bpImpl = bp as DbgModuleBreakpointImpl; - Debug2.Assert(!(bpImpl is null)); + Debug2.Assert(bpImpl is not null); if (bpImpl is null) continue; Debug.Assert(this.breakpoints.Contains(bpImpl)); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/CallStack/DbgCallStackServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/CallStack/DbgCallStackServiceImpl.cs index 0854c4d7be..78b6693b1a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/CallStack/DbgCallStackServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/CallStack/DbgCallStackServiceImpl.cs @@ -114,17 +114,17 @@ void UpdateCurrentThreadProcess_DbgThread(DbgProcess? process) { dbgManager!.Dispatcher.VerifyAccess(); if (currentThreadProcess == process) return; - if (!(currentThreadProcess is null)) + if (currentThreadProcess is not null) currentThreadProcess.IsRunningChanged -= DbgProcess_IsRunningChanged; currentThreadProcess = process; - if (!(process is null)) + if (process is not null) process.IsRunningChanged += DbgProcess_IsRunningChanged; } void DbgProcess_IsRunningChanged(object? sender, EventArgs e) { if (currentThreadProcess != sender) return; - Debug2.Assert(!(currentThreadProcess is null)); + Debug2.Assert(currentThreadProcess is not null); if (!currentThreadProcess.IsRunning) UpdateFrames_DbgThread(); } @@ -163,7 +163,7 @@ void UpdateFrames_DbgThread() { } finally { stackWalker?.Close(); - if (!(newFrames is null) && frames != newFrames && newFrames.Length > 0) + if (newFrames is not null && frames != newFrames && newFrames.Length > 0) dbgManager.Close(newFrames); } if (raiseFramesChanged || raiseActiveFrameIndexChanged) @@ -172,7 +172,7 @@ void UpdateFrames_DbgThread() { int GetFrameIndex(DbgStackFrame[] newFrames) { for (int i = 0; i < newFrames.Length; i++) { - if (!(newFrames[i].Location is null)) + if (newFrames[i].Location is not null) return i; } return 0; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/CallStack/TextEditor/CallStackMarker.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/CallStack/TextEditor/CallStackMarker.cs index 3aa1332618..9c14894abf 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/CallStack/TextEditor/CallStackMarker.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/CallStack/TextEditor/CallStackMarker.cs @@ -81,10 +81,10 @@ void UpdateMarkers(bool updateActiveStatements) { void SetCurrentProcess(DbgProcess? process) { if (currentProcess == process) return; - if (!(currentProcess is null)) + if (currentProcess is not null) currentProcess.IsRunningChanged -= DbgProcess_IsRunningChanged; currentProcess = process; - if (!(process is null)) + if (process is not null) process.IsRunningChanged += DbgProcess_IsRunningChanged; } @@ -101,11 +101,11 @@ void DbgProcess_IsRunningChanged(object? sender, EventArgs e) { static readonly ReadOnlyCollection emptyStackFrames = new ReadOnlyCollection(Array.Empty()); void ClearMarkers() { - if (!(currentStatementMarker is null) || !(callReturnMarker is null)) { + if (currentStatementMarker is not null || callReturnMarker is not null) { var list = new List(2); - if (!(currentStatementMarker is null)) + if (currentStatementMarker is not null) list.Add(currentStatementMarker); - if (!(callReturnMarker is null)) + if (callReturnMarker is not null) list.Add(callReturnMarker); currentStatementMarker = null; callReturnMarker = null; @@ -116,7 +116,7 @@ void ClearMarkers() { GlyphTextMarkerLocationInfo? GetTextMarkerLocationInfo(DbgStackFrame frame) { foreach (var provider in dbgStackFrameGlyphTextMarkerLocationInfoProviders) { var info = provider.Value.Create(frame); - if (!(info is null)) + if (info is not null) return info; } return null; @@ -129,7 +129,7 @@ void AddMarkers(bool updateActiveStatements) { if (frames.Count != 0) { var markerLocationInfo = GetTextMarkerLocationInfo(frames[0]); - if (!(markerLocationInfo is null)) { + if (markerLocationInfo is not null) { currentStatementMarker = glyphTextMarkerService.Value.AddMarker( markerLocationInfo, DsImages.CurrentInstructionPointer, @@ -144,7 +144,7 @@ void AddMarkers(bool updateActiveStatements) { int activeFrameIndex = dbgCallStackService.ActiveFrameIndex; markerLocationInfo = activeFrameIndex != 0 && (uint)activeFrameIndex < (uint)frames.Count ? GetTextMarkerLocationInfo(frames[activeFrameIndex]) : null; - if (!(markerLocationInfo is null)) { + if (markerLocationInfo is not null) { callReturnMarker = glyphTextMarkerService.Value.AddMarker( markerLocationInfo, DsImages.CallReturnInstructionPointer, diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Code/TextEditor/DbgTextViewCodeLocationService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Code/TextEditor/DbgTextViewCodeLocationService.cs index a9392fe11e..8b60cf1624 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Code/TextEditor/DbgTextViewCodeLocationService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Code/TextEditor/DbgTextViewCodeLocationService.cs @@ -48,7 +48,7 @@ public override IEnumerable CreateLocation( throw new ArgumentException(); foreach (var lz in dbgTextViewCodeLocationProviders) { var res = lz.Value.CreateLocation(tab, textView, position); - if (!(res is null)) + if (res is not null) yield return res.Value; } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/CurrentStatementUpdater.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/CurrentStatementUpdater.cs index 9921082fad..923ab70150 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/CurrentStatementUpdater.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/CurrentStatementUpdater.cs @@ -43,7 +43,7 @@ protected CurrentStatementUpdater(DbgCallStackService dbgCallStackService, Lazy< void DbgManager_ProcessPaused(object? sender, ProcessPausedEventArgs e) { Debug.Assert(dbgCallStackService.Thread == e.Thread); var info = GetLocation(); - if (!(info.location is null)) { + if (info.location is not null) { dbgCallStackService.ActiveFrameIndex = info.frameIndex; referenceNavigatorService.Value.GoTo(info.location); } @@ -55,7 +55,7 @@ void DbgManager_ProcessPaused(object? sender, ProcessPausedEventArgs e) { var frames = dbgCallStackService.Frames.Frames; for (int i = 0; i < frames.Count; i++) { var location = frames[i].Location; - if (!(location is null)) + if (location is not null) return (location, i); } return (null, -1); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DbgProcessStarterService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DbgProcessStarterService.cs index a2201ae2bb..17f3e02ec2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DbgProcessStarterService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DbgProcessStarterService.cs @@ -66,7 +66,7 @@ public override bool TryStart(string filename, [NotNullWhen(false)] out string? if (ok) return true; - Debug2.Assert(!(error is null)); + Debug2.Assert(error is not null); if (error is null) error = ""; return false; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DebuggerImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DebuggerImpl.cs index 8c8849a459..047289d01c 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DebuggerImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DebuggerImpl.cs @@ -127,7 +127,7 @@ public override void DebugProgram(bool pauseAtEntryPoint) { } var errMsg = dbgManager.Value.Start(options); - if (!(errMsg is null)) + if (errMsg is not null) messageBoxService.Value.Show(errMsg); } bool showingDebugProgramDlgBox; @@ -164,7 +164,7 @@ public override void DetachAll() { public override bool CanShowNextStatement => CanExecutePauseCommand; public override void ShowNextStatement() { var info = GetCurrentStatementLocation(); - if (!(info.location is null)) { + if (info.location is not null) { referenceNavigatorService.Value.GoTo(info.location); dbgCallStackService.Value.ActiveFrameIndex = info.frameIndex; } @@ -174,7 +174,7 @@ public override void ShowNextStatement() { var frames = dbgCallStackService.Value.Frames.Frames; for (int i = 0; i < frames.Count; i++) { var location = frames[i].Location; - if (!(location is null)) + if (location is not null) return (location, i); } return (null, -1); @@ -185,7 +185,7 @@ public override bool CanSetNextStatement { if (!CanExecutePauseCommand || dbgManager.Value.CurrentThread.Current is null) return false; using (var res = GetCurrentTextViewStatementLocation()) - return !(res.Location is null); + return res.Location is not null; } } @@ -193,7 +193,7 @@ public override void SetNextStatement() { if (!CanSetNextStatement) return; using (var res = GetCurrentTextViewStatementLocation()) { - if (!(res.Location is null)) + if (res.Location is not null) dbgManager.Value.CurrentThread.Current?.SetIP(res.Location); } } @@ -211,7 +211,7 @@ public TextViewStatementLocationResult(Lazy dbgManager, List 0) + if (allLocations is not null && allLocations.Count > 0) dbgManager.Value.Close(allLocations); } } @@ -308,7 +308,7 @@ public override bool CanGoToDisassembly { if (!CanExecutePauseCommand || dbgManager.Value.CurrentThread.Current is null) return false; using (var res = GetCurrentTextViewStatementLocation()) { - if (!(res.Location is null)) { + if (res.Location is not null) { foreach (var runtime in GetRuntimes()) { if (dbgShowNativeCodeService.Value.CanShowNativeCode(runtime, res.Location)) return true; @@ -323,7 +323,7 @@ public override void GoToDisassembly() { if (!CanGoToDisassembly) return; using (var res = GetCurrentTextViewStatementLocation()) { - if (!(res.Location is null)) { + if (res.Location is not null) { foreach (var runtime in GetRuntimes()) { if (dbgShowNativeCodeService.Value.CanShowNativeCode(runtime, res.Location)) { if (!dbgShowNativeCodeService.Value.ShowNativeCode(runtime, res.Location)) @@ -336,7 +336,7 @@ public override void GoToDisassembly() { } IEnumerable GetRuntimes() { var currentRuntime = dbgManager.Value.CurrentRuntime.Current; - if (!(currentRuntime is null)) + if (currentRuntime is not null) yield return currentRuntime; foreach (var process in dbgManager.Value.Processes) { foreach (var runtime in process.Runtimes) { @@ -357,7 +357,7 @@ IEnumerable GetRuntimes() { public override bool CanDeleteAllBreakpoints => dbgCodeBreakpointsService.Value.VisibleBreakpoints.Any(); public override void DeleteAllBreakpointsAskUser() { var res = messageBoxService.Value.ShowIgnorableMessage(new Guid("37250D26-E844-49F4-904B-29600B90476C"), dnSpy_Debugger_Resources.AskDeleteAllBreakpoints, MsgBoxButton.Yes | MsgBoxButton.No); - if (!(res is null) && res != MsgBoxButton.Yes) + if (res is not null && res != MsgBoxButton.Yes) return; dbgCodeBreakpointsService.Value.Clear(); } @@ -417,7 +417,7 @@ void DbgManager_DbgManagerMessage(object? sender, DbgManagerMessageEventArgs e) } void DbgManager_MessageSetIPComplete(object? sender, DbgMessageSetIPCompleteEventArgs e) { - if (!(e.Error is null)) + if (e.Error is not null) UI(() => ShowError_UI(e.Error)); } @@ -537,7 +537,7 @@ static string GetStatusBarMessage(IList breakInfos) { var bbe = (DbgMessageBoundBreakpointEventArgs)e; var bpMsg = $"{dnSpy_Debugger_Resources.StatusBar_BreakpointHit} #{bbe.BoundBreakpoint.Breakpoint.Id} : pid={bbe.BoundBreakpoint.Process.Id}({GetProcessName(bbe.BoundBreakpoint.Process)})"; module = bbe.BoundBreakpoint.Module; - if (!(module is null)) + if (module is not null) bpMsg += $", {module.Name}"; if (bbe.BoundBreakpoint.HasAddress) bpMsg += $", 0x{bbe.BoundBreakpoint.Address.ToString("X")}"; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DocumentViewerCommands.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DocumentViewerCommands.cs index d9217a5acf..0f2605c0c4 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DocumentViewerCommands.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/DocumentViewerCommands.cs @@ -57,7 +57,7 @@ public DebugProgramDocumentViewerCommand(Lazy debugger) var filename = debugger.Value.GetCurrentExecutableFilename(); if (!File.Exists(filename)) return null; - Debug2.Assert(!(filename is null)); + Debug2.Assert(filename is not null); return string.Format(dnSpy_Debugger_Resources.DebugProgramX, UIUtilities.EscapeMenuItemHeader(Path.GetFileName(filename))); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/StartDebuggingOptionsMru.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/StartDebuggingOptionsMru.cs index a81b660053..f49b93f69a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/StartDebuggingOptionsMru.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/StartDebuggingOptionsMru.cs @@ -56,7 +56,7 @@ public void Add(string filename, StartDebuggingOptions options, Guid pageGuid) { if (filename is null) return; var info = Find(filename); - if (!(info is null)) { + if (info is not null) { bool b = list.Remove(info); Debug.Assert(b); list.Add(info); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/StartDebuggingOptionsProvider.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/StartDebuggingOptionsProvider.cs index f7efedc973..ba821d1a61 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/StartDebuggingOptionsProvider.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/DbgUI/StartDebuggingOptionsProvider.cs @@ -127,7 +127,7 @@ static StartDebuggingOptions WithBreakKind(StartDebuggingOptions options, string var engineGuids = new List(); foreach (var lz in genericDebugEngineGuidProviders) { var engineGuid = lz.Value.GetEngineGuid(filename); - if (!(engineGuid is null)) + if (engineGuid is not null) engineGuids.Add(engineGuid.Value); } @@ -147,7 +147,7 @@ static StartDebuggingOptions WithBreakKind(StartDebuggingOptions options, string } } // The order of the engine guids is important so exit as soon as we find a match - if (!(firstResult is null)) + if (firstResult is not null) break; } return firstResult; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/AttachToProcess/AttachToProcessDlg.xaml.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/AttachToProcess/AttachToProcessDlg.xaml.cs index cc186a34c1..0ed0a93a5c 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/AttachToProcess/AttachToProcessDlg.xaml.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/AttachToProcess/AttachToProcessDlg.xaml.cs @@ -79,7 +79,7 @@ void FocusListViewElement() { void OnLoaded(object? sender, RoutedEventArgs e) { listView.Focus(); var vm = DataContext as AttachToProcessVM; - if (listView.SelectedItem is null && !(vm is null) && vm.AllItems.Count > 0) + if (listView.SelectedItem is null && vm is not null && vm.AllItems.Count > 0) FocusListViewElement(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/AttachToProcess/AttachToProcessVM.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/AttachToProcess/AttachToProcessVM.cs index dcbe6dbd51..b343038d91 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/AttachToProcess/AttachToProcessVM.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/AttachToProcess/AttachToProcessVM.cs @@ -52,7 +52,7 @@ sealed class AttachToProcessVM : ViewModelBase, IGridViewColumnDescsProvider, IC public string SearchHelpToolTip => ToolTipHelper.AddKeyboardShortcut(dnSpy_Debugger_Resources.SearchHelp_ToolTip, null); public ICommand InfoLinkCommand => new RelayCommand(a => ShowInfoLinkPage()); - public bool HasInfoLink => !(InfoLinkToolTip is null) && !(infoLink is null); + public bool HasInfoLink => InfoLinkToolTip is not null && infoLink is not null; public string? InfoLinkToolTip { get; } readonly string? infoLink; @@ -103,7 +103,7 @@ public AttachToProcessVM(ShowAttachToProcessDialogOptions? options, UIDispatcher } Title = GetTitle(options); MessageText = GetMessage(options); - if (!(options.InfoLink is null)) { + if (options.InfoLink is not null) { var l = options.InfoLink.Value; if (!string.IsNullOrEmpty(l.Url)) { InfoLinkToolTip = l.ToolTipMessage; @@ -162,7 +162,7 @@ static string GetTitle(ShowAttachToProcessDialogOptions options) { } static string? GetMessage(ShowAttachToProcessDialogOptions options) { - if (!(options.Message is null)) + if (options.Message is not null) return options.Message; if (!Environment.Is64BitOperatingSystem) return null; @@ -196,7 +196,7 @@ void RemoveAggregator() { uiDispatcher.VerifyAccess(); processProvider?.Dispose(); processProvider = null; - if (!(attachProgramOptionsAggregator is null)) { + if (attachProgramOptionsAggregator is not null) { attachProgramOptionsAggregator.AttachProgramOptionsAdded -= AttachProgramOptionsAggregator_AttachProgramOptionsAdded; attachProgramOptionsAggregator.Completed -= AttachProgramOptionsAggregator_Completed; attachProgramOptionsAggregator.Dispose(); @@ -209,7 +209,7 @@ void AttachProgramOptionsAggregator_AttachProgramOptionsAdded(object? sender, At uiDispatcher.VerifyAccess(); if (attachProgramOptionsAggregator != sender) return; - Debug2.Assert(!(processProvider is null)); + Debug2.Assert(processProvider is not null); foreach (var options in e.AttachProgramOptions) { if (!dbgManager.CanDebugRuntime(options.ProcessId, options.RuntimeId)) continue; @@ -494,7 +494,7 @@ public void Copy(ProgramVM[] programs) { } void ShowInfoLinkPage() { - if (!(infoLink is null)) + if (infoLink is not null) OpenWebPage(infoLink); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/CodeBreakpoints/ShowCodeBreakpointSettingsService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/CodeBreakpoints/ShowCodeBreakpointSettingsService.cs index d02596b04c..828cea4add 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/CodeBreakpoints/ShowCodeBreakpointSettingsService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/CodeBreakpoints/ShowCodeBreakpointSettingsService.cs @@ -62,7 +62,7 @@ public override void Edit(DbgCodeBreakpoint[] breakpoints) { if (breakpoints.Length == 0) return; var newSettings = Show(breakpoints[0].Settings); - if (!(newSettings is null)) + if (newSettings is not null) dbgCodeBreakpointsService.Value.Modify(breakpoints.Select(a => new DbgCodeBreakpointAndSettings(a, newSettings.Value)).ToArray()); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/CodeBreakpoints/ShowCodeBreakpointSettingsVM.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/CodeBreakpoints/ShowCodeBreakpointSettingsVM.cs index a82a5e5083..ba776b5fa4 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/CodeBreakpoints/ShowCodeBreakpointSettingsVM.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Dialogs/CodeBreakpoints/ShowCodeBreakpointSettingsVM.cs @@ -317,12 +317,12 @@ void UpdateFilterAndError() { HasErrorUpdated(); } - public bool HasFilterExpressionError => EnableFilter && !(lastFilterError is null); + public bool HasFilterExpressionError => EnableFilter && lastFilterError is not null; public string? FilterExpressionError => EnableFilter ? lastFilterError : null; string? lastFilterError; void StartVerifyFilterTimer() { - if (!(verifyFilterTimer is null)) + if (verifyFilterTimer is not null) return; verifyFilterTimer = new Timer(1000); verifyFilterTimer.Elapsed += VerifyFilterTimer_Elapsed; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Disassembly/DisassemblyOperations.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Disassembly/DisassemblyOperations.cs index 73cbb53aa9..e9476895f2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Disassembly/DisassemblyOperations.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Disassembly/DisassemblyOperations.cs @@ -50,14 +50,14 @@ sealed class DisassemblyOperationsImpl : DisassemblyOperations { public override bool CanShowDisassembly_CurrentFrame => dbgManager.Value.CurrentThread.Current?.Process.State == DbgProcessState.Paused && - !(dbgCallStackService.Value.ActiveFrame is null); + dbgCallStackService.Value.ActiveFrame is not null; public override void ShowDisassembly_CurrentFrame() { if (!CanShowDisassembly_CurrentFrame) return; var frame = dbgCallStackService.Value.ActiveFrame; - if (!(frame is null)) { + if (frame is not null) { if (!dbgShowNativeCodeService.Value.ShowNativeCode(frame)) messageBoxService.Value.Show(dnSpy_Debugger_Resources.Error_CouldNotShowDisassembly); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgExpressionEvaluatorImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgExpressionEvaluatorImpl.cs index 82e286d9e2..efc3843a26 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgExpressionEvaluatorImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgExpressionEvaluatorImpl.cs @@ -37,9 +37,9 @@ public DbgExpressionEvaluatorImpl(DbgLanguage language, Guid runtimeKindGuid, Db } DbgEvaluationResult CreateResult(DbgRuntime runtime, DbgEngineEvaluationResult result) { - if (!(result.Error is null)) + if (result.Error is not null) return new DbgEvaluationResult(PredefinedEvaluationErrorMessagesHelper.GetErrorMessage(result.Error), result.FormatSpecifiers, result.Flags); - Debug2.Assert(!(result.Value is null)); + Debug2.Assert(result.Value is not null); try { var value = new DbgValueImpl(runtime, result.Value); runtime.CloseOnContinue(value); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgLanguageServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgLanguageServiceImpl.cs index 1136f1c67d..34285a0d1d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgLanguageServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgLanguageServiceImpl.cs @@ -111,7 +111,7 @@ public override RuntimeLanguageInfo[] GetLanguageInfos() { Debug.Assert(langs.Count != 0); if (langs.Count == 0 || langs[0].Name == PredefinedDbgLanguageNames.None) continue; - var runtimeName = kv.Value.Providers.FirstOrDefault(a => !(a.Value.RuntimeDisplayName is null))?.Value.RuntimeDisplayName; + var runtimeName = kv.Value.Providers.FirstOrDefault(a => a.Value.RuntimeDisplayName is not null)?.Value.RuntimeDisplayName; if (runtimeName is null) continue; var languageName = GetCurrentLanguage(kv.Key).Name; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgRuntimeObjectIdService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgRuntimeObjectIdService.cs index 971fbe47d3..44eb84637b 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgRuntimeObjectIdService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgRuntimeObjectIdService.cs @@ -115,7 +115,7 @@ public override bool CanCreateObjectId(DbgValue value, CreateObjectIdOptions opt var value = values[i] as DbgValueImpl; if (value?.Runtime != Runtime) throw new ArgumentException(); - Debug2.Assert(!(value is null)); + Debug2.Assert(value is not null); DbgObjectId? objectId; if (Runtime.IsClosed || value.IsClosed || (!isHidden && objectIds.ContainsKey(value))) objectId = null; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgValueNodeFactoryImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgValueNodeFactoryImpl.cs index 1aa7769791..8eb4c83a58 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgValueNodeFactoryImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgValueNodeFactoryImpl.cs @@ -49,7 +49,7 @@ DbgCreateValueNodeResult[] CreateResult(DbgRuntime runtime, DbgEngineValueNode[] } } catch { - runtime.Process.DbgManager.Close(res.Select(a => a.ValueNode).Where(a => !(a is null))); + runtime.Process.DbgManager.Close(res.Select(a => a.ValueNode).Where(a => a is not null)); throw; } return res; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgValueNodeImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgValueNodeImpl.cs index c2c58d4101..788efefd86 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgValueNodeImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/DbgValueNodeImpl.cs @@ -45,7 +45,7 @@ public DbgValueNodeImpl(DbgLanguage language, DbgRuntime runtime, DbgEngineValue Language = language ?? throw new ArgumentNullException(nameof(language)); this.engineValueNode = engineValueNode ?? throw new ArgumentNullException(nameof(engineValueNode)); var engineValue = engineValueNode.Value; - if (!(engineValue is null)) + if (engineValue is not null) value = new DbgValueImpl(runtime, engineValue); else if (!engineValueNode.IsReadOnly) throw new InvalidOperationException(); @@ -95,7 +95,7 @@ public override void Format(DbgEvaluationInfo evalInfo, IDbgValueNodeFormatParam } DbgValueNodeAssignmentResult CreateResult(DbgEngineValueNodeAssignmentResult result) { - if (!(result.Error is null)) { + if (result.Error is not null) { if (engineValueNode.Value != value?.EngineValue) throw new InvalidOperationException(); return new DbgValueNodeAssignmentResult(result.Flags, PredefinedEvaluationErrorMessagesHelper.GetErrorMessage(result.Error)); @@ -118,7 +118,7 @@ public override DbgValueNodeAssignmentResult Assign(DbgEvaluationInfo evalInfo, throw new ArgumentNullException(nameof(expression)); if (IsReadOnly) throw new InvalidOperationException(); - if (!(engineValueNode.ErrorMessage is null)) + if (engineValueNode.ErrorMessage is not null) throw new NotSupportedException(); return CreateResult(engineValueNode.Assign(evalInfo, expression, options)); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/ValueNodesProviderImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/ValueNodesProviderImpl.cs index 198fd8d415..549ed2e715 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/ValueNodesProviderImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/ValueNodesProviderImpl.cs @@ -148,7 +148,7 @@ public override GetNodesResult GetNodes(DbgEvaluationOptions evalOptions, DbgVal var info = TryGetLanguage(); if (info.frame is null) return new GetNodesResult(variablesWindowValueNodesProvider.GetDefaultNodes(), frameClosed: false, recreateAllNodes: false); - Debug2.Assert(!(info.language is null)); + Debug2.Assert(info.language is not null); var evalInfo = TryGetEvaluationInfo(info); if (evalInfo is null) return new GetNodesResult(variablesWindowValueNodesProvider.GetDefaultNodes(), info.frame.IsClosed, recreateAllNodes: false); @@ -203,12 +203,12 @@ public override void AddExpressions(string[] expressions) { public override DbgEvaluationInfo? TryGetEvaluationInfo() => TryGetEvaluationInfo(TryGetLanguage()); DbgEvaluationInfo? TryGetEvaluationInfo((DbgLanguage? language, DbgStackFrame? frame) info) { - if (!(evalContextInfo.EvalInfo is null) && evalContextInfo.Language == info.language && evalContextInfo.EvalInfo.Frame == info.frame) + if (evalContextInfo.EvalInfo is not null && evalContextInfo.Language == info.language && evalContextInfo.EvalInfo.Frame == info.frame) return evalContextInfo.EvalInfo; evalContextInfo.Language = info.language; - if (!(info.frame is null)) { - Debug2.Assert(!(info.language is null)); + if (info.frame is not null) { + Debug2.Assert(info.language is not null); //TODO: Show a cancel button if the decompiler takes too long to decompile the method var cancellationToken = CancellationToken.None; var context = info.language.CreateContext(info.frame, cancellationToken: cancellationToken); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/VariablesWindowContentBase.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/VariablesWindowContentBase.cs index 7e08778b70..1d3d5e3744 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/VariablesWindowContentBase.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/VariablesWindowContentBase.cs @@ -55,7 +55,7 @@ protected void Initialize(IWpfCommandService wpfCommandService, VariablesWindowV public void Focus() { var listView = variablesWindowControl.ListView; - if (!(listView is null)) + if (listView is not null) UIUtilities.FocusSelector(listView); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/VariablesWindowControl.xaml.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/VariablesWindowControl.xaml.cs index de2081d221..e4f28adf07 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/VariablesWindowControl.xaml.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/VariablesWindowControl.xaml.cs @@ -46,10 +46,10 @@ public void SetTreeView(ITreeView treeView, VariablesWindowKind windowKind) { return; if (treeViewContentPresenter.Content is UIElement oldElem) oldElem.PreviewTextInput -= TreeView_PreviewTextInput; - if (!(listView is null)) + if (listView is not null) listView.PreviewTextInput += TreeView_PreviewTextInput; treeViewContentPresenter.Content = listView; - if (!(listView is null)) { + if (listView is not null) { AutomationPeerMemoryLeakWorkaround.SetEmptyCount(listView, GetEmptyCount(windowKind)); var gridView = (GridView)FindResource("GridView"); listView.View = gridView; @@ -74,7 +74,7 @@ static int GetEmptyCount(VariablesWindowKind windowKind) { } void TreeView_PreviewTextInput(object? sender, TextCompositionEventArgs e) { - Debug2.Assert(!(variablesWindowOperations is null)); + Debug2.Assert(variablesWindowOperations is not null); if (variablesWindowOperations is null) return; if (!(treeViewContentPresenter.Content is ListView listView) || listView.SelectedItems.Count != 1) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/DbgValueNodeReader.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/DbgValueNodeReader.cs index 1500911ebe..47400eef17 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/DbgValueNodeReader.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/DbgValueNodeReader.cs @@ -42,7 +42,7 @@ public DbgValueNodeReaderImpl(Func public override void SetValueNodeEvaluationOptions(DbgValueNodeEvaluationOptions options) => dbgValueNodeEvaluationOptions = options; public override DbgValueNode GetDebuggerNode(ChildDbgValueRawNode valueNode) { - Debug2.Assert(!(evalInfo is null)); + Debug2.Assert(evalInfo is not null); var parent = valueNode.Parent; uint startIndex = valueNode.DbgValueNodeChildIndex; const int count = 1; @@ -52,7 +52,7 @@ public override DbgValueNode GetDebuggerNode(ChildDbgValueRawNode valueNode) { } public override DbgValueNode GetDebuggerNodeForReuse(DebuggerValueRawNode parent, uint startIndex) { - Debug2.Assert(!(evalInfo is null)); + Debug2.Assert(evalInfo is not null); const int count = 1; var newNodes = parent.DebuggerValueNode.GetChildren(evalInfo, startIndex, count, dbgValueNodeEvaluationOptions); Debug.Assert(count == 1); @@ -60,7 +60,7 @@ public override DbgValueNode GetDebuggerNodeForReuse(DebuggerValueRawNode parent } public override DbgValueNodeInfo Evaluate(string expression) { - Debug2.Assert(!(evalInfo is null)); + Debug2.Assert(evalInfo is not null); return evaluate(evalInfo, expression); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/LanguageEditValueProvider.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/LanguageEditValueProvider.cs index 2904bad3e5..e1e6d6d922 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/LanguageEditValueProvider.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/LanguageEditValueProvider.cs @@ -75,7 +75,7 @@ public LanguageEditValueProviderImpl(UIDispatcher uiDispatcher, EditValueProvide } string GetContentType() { - if (!(language is null)) { + if (language is not null) { //TODO: } return defaultContentType; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/RawNode.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/RawNode.cs index 45a63406fd..19be5a074a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/RawNode.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/RawNode.cs @@ -81,9 +81,9 @@ public ErrorRawNode(string expression, string errorMessage) { internal void SetErrorMessage(string errorMessage) => this.errorMessage = errorMessage; public override void Format(DbgEvaluationInfo? evalInfo, IDbgValueNodeFormatParameters options, CultureInfo? cultureInfo) { - if (!(options.NameOutput is null)) + if (options.NameOutput is not null) FormatName(evalInfo, options.NameOutput, options.NameFormatterOptions, cultureInfo); - if (!(options.ValueOutput is null)) + if (options.ValueOutput is not null) FormatValue(evalInfo, options.ValueOutput, options.ValueFormatterOptions, cultureInfo); } @@ -102,13 +102,13 @@ abstract class CachedRawNodeBase : RawNode { protected abstract ref readonly ClassifiedTextCollection CachedActualType { get; } public sealed override void Format(DbgEvaluationInfo? evalInfo, IDbgValueNodeFormatParameters options, CultureInfo? cultureInfo) { - if (!(options.NameOutput is null)) + if (options.NameOutput is not null) FormatName(evalInfo, options.NameOutput, options.NameFormatterOptions, cultureInfo); - if (!(options.ValueOutput is null)) + if (options.ValueOutput is not null) FormatValue(evalInfo, options.ValueOutput, options.ValueFormatterOptions, cultureInfo); - if (!(options.ExpectedTypeOutput is null)) + if (options.ExpectedTypeOutput is not null) WriteTo(options.ExpectedTypeOutput, CachedExpectedType); - if (!(options.ActualTypeOutput is null)) + if (options.ActualTypeOutput is not null) WriteTo(options.ActualTypeOutput, CachedActualType); } @@ -194,25 +194,25 @@ public override RawNode CreateChild(Action debugge new ChildDbgValueRawNode(debuggerValueNodeChanged, debuggerValueNodeChangedData, this, index, reader); public override void Format(DbgEvaluationInfo? evalInfo, IDbgValueNodeFormatParameters options, CultureInfo? cultureInfo) { - if (!(evalInfo is null)) + if (evalInfo is not null) DebuggerValueNode.Format(evalInfo, options, cultureInfo); else { - if (!(options.NameOutput is null)) + if (options.NameOutput is not null) FormatName(evalInfo, options.NameOutput, options.NameFormatterOptions, cultureInfo); - if (!(options.ValueOutput is null)) + if (options.ValueOutput is not null) FormatValue(evalInfo, options.ValueOutput, options.ValueFormatterOptions, cultureInfo); } } public override void FormatName(DbgEvaluationInfo? evalInfo, IDbgTextWriter output, DbgValueFormatterOptions options, CultureInfo? cultureInfo) { - if (!(evalInfo is null)) + if (evalInfo is not null) DebuggerValueNode.FormatName(evalInfo, output, options, cultureInfo); else output.Write(DbgTextColor.Error, "???"); } public override void FormatValue(DbgEvaluationInfo? evalInfo, IDbgTextWriter output, DbgValueFormatterOptions options, CultureInfo? cultureInfo) { - if (!(evalInfo is null)) + if (evalInfo is not null) DebuggerValueNode.FormatValue(evalInfo, output, options, cultureInfo); else output.Write(DbgTextColor.Error, "???"); @@ -233,7 +233,7 @@ public DbgValueRawNode(DbgValueNodeReader reader, DbgValueNode valueNode) } sealed class ChildDbgValueRawNode : DebuggerValueRawNode { - public override bool HasInitializedUnderlyingData => !(__dbgValueNode_DONT_USE is null); + public override bool HasInitializedUnderlyingData => __dbgValueNode_DONT_USE is not null; internal DebuggerValueRawNode Parent => parent; internal uint DbgValueNodeChildIndex { get; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodeFormatter.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodeFormatter.cs index f2af81859b..592c4fc477 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodeFormatter.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodeFormatter.cs @@ -51,24 +51,24 @@ public void WriteValue(IDbgTextWriter output, ValueNode vm, out bool textChanged } public void WriteObjectId(IDbgTextWriter output, ValueNode vm) { - Debug2.Assert(!(ObjectIdService is null)); + Debug2.Assert(ObjectIdService is not null); if (ObjectIdService is null) return; var vmImpl = (ValueNodeImpl)vm; if (vmImpl.RawNode is DebuggerValueRawNode rawNode) { var language = Language; - Debug2.Assert(!(language is null)); + Debug2.Assert(language is not null); if (language is null) return; var value = rawNode.DebuggerValueNode.Value; if (value is null) return; var objectId = ObjectIdService.GetObjectId(value); - if (!(objectId is null)) { + if (objectId is not null) { output.Write(DbgTextColor.Text, " "); output.Write(DbgTextColor.Punctuation, "{"); var evalInfo = vmImpl.Context.EvaluationInfo; - Debug2.Assert(!(evalInfo is null)); + Debug2.Assert(evalInfo is not null); if (evalInfo is null) output.Write(DbgTextColor.Error, "???"); else diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodeImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodeImpl.cs index 11acc65d95..79a02e4356 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodeImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodeImpl.cs @@ -216,14 +216,14 @@ public ValueNodeImpl(IValueNodesContext context, RawNode parent, uint childIndex internal bool IsEditNode => IsRoot && Context.EditValueNodeExpression.SupportsEditExpression && RootId is null; - internal bool CanEditNameExpression() => IsRoot && Context.EditValueNodeExpression.SupportsEditExpression && !Context.IsWindowReadOnly && !(Context.EvaluationInfo is null); + internal bool CanEditNameExpression() => IsRoot && Context.EditValueNodeExpression.SupportsEditExpression && !Context.IsWindowReadOnly && Context.EvaluationInfo is not null; EditableValueTextInfo GetNameExpression() { if (!CanEditNameExpression()) throw new InvalidOperationException(); var text = Context.ExpressionToEdit; Context.ExpressionToEdit = null; - if (!(text is null)) + if (text is not null) return new EditableValueTextInfo(text, EditValueFlags.None); // Always use the expression since the Name column could've been replaced with any random // text if DebuggerDisplayAttribute.Name property isn't null. @@ -244,15 +244,15 @@ void SaveNameExpression(string? expression) { Context.EditValueNodeExpression.EditExpression(RootId, expression); } - internal bool CanEditValue() => !RawNode.IsReadOnly && !Context.IsWindowReadOnly && !(Context.EvaluationInfo is null); + internal bool CanEditValue() => !RawNode.IsReadOnly && !Context.IsWindowReadOnly && Context.EvaluationInfo is not null; EditableValueTextInfo GetEditableValue() { if (!CanEditValue()) throw new InvalidOperationException(); - Debug2.Assert(!(Context.EvaluationInfo is null)); + Debug2.Assert(Context.EvaluationInfo is not null); var text = Context.ExpressionToEdit; Context.ExpressionToEdit = null; - if (!(text is null)) + if (text is not null) return new EditableValueTextInfo(text, EditValueFlags.None); var output = new DbgStringBuilderTextWriter(); var options = Context.ValueNodeFormatParameters.ValueFormatterOptions | DbgValueFormatterOptions.Edit; @@ -265,13 +265,13 @@ void SaveEditableValue(string? expression) { throw new InvalidOperationException(); if (expression is null) expression = string.Empty; - Debug2.Assert(!(Context.EvaluationInfo is null)); + Debug2.Assert(Context.EvaluationInfo is not null); if (GetEditableValue().Text == expression) return; var res = RawNode.Assign(Context.EvaluationInfo, expression, Context.EvaluationOptions); if (res.Error is null) oldCachedValue = cachedValue; - bool retry = !(res.Error is null) && + bool retry = res.Error is not null && (res.Flags & DbgEEAssignmentResultFlags.CompilerError) != 0 && (res.Flags & DbgEEAssignmentResultFlags.ExecutedCode) == 0 && CanEditValue(); @@ -317,7 +317,7 @@ public override IEnumerable CreateChildren() { yield break; } - Debug2.Assert(!(Context.EvaluationInfo is null)); + Debug2.Assert(Context.EvaluationInfo is not null); var childCountTmp = RawNode.GetChildCount(Context.EvaluationInfo); cachedChildCount = childCountTmp; if (childCountTmp is null) { @@ -384,7 +384,7 @@ internal void SetDebuggerValueNode(in DbgValueNodeInfo info) { const int MAX_TREEVIEW_RECURSION = 30; RawNode CreateNewNode(RawNode? newNode) { - if (!(newNode is null)) + if (newNode is not null) return newNode; if (RawNode is ErrorRawNode errorNode) return errorNode; @@ -424,7 +424,7 @@ void InvalidateNodes(RawNode? newNode, int recursionCounter) { } bool SetDebuggerValueNode(DebuggerValueRawNode newNode, int recursionCounter) { - Debug2.Assert(!(newNode is null)); + Debug2.Assert(newNode is not null); var oldNode = __rawNode_DONT_USE; __rawNode_DONT_USE = newNode; oldCachedValue = cachedValue; @@ -447,13 +447,13 @@ bool SetDebuggerValueNode(DebuggerValueRawNode newNode, int recursionCounter) { for (int i = 0; i < count; i++) { var childNode = (ValueNodeImpl)children[i].Data; var childRawNode = childNode.RawNode as ChildDbgValueRawNode; - if (!(childRawNode is null) && !childRawNode.HasInitializedUnderlyingData) { + if (childRawNode is not null && !childRawNode.HasInitializedUnderlyingData) { childRawNode.SetParent(newNode, null); continue; } // Check if we must read the value. If its treenode is expanded, it must be read now, else it can be delayed - if (!(childRawNode is null) && childNode.TreeNode.IsExpanded) { + if (childRawNode is not null && childNode.TreeNode.IsExpanded) { var newChildValue = Context.ValueNodeReader.GetDebuggerNodeForReuse(newNode, (uint)i); // We have to create a new one here and can't reuse the existing ChildDbgValueRawNode by // calling its SetParent() method. Otherwise IsSame() above will compare the same @@ -466,7 +466,7 @@ bool SetDebuggerValueNode(DebuggerValueRawNode newNode, int recursionCounter) { } else { // It's safe to read the underlying data lazily - if (!(childRawNode is null)) + if (childRawNode is not null) childRawNode.SetParent(newNode, null); else childNode.__rawNode_DONT_USE = new ChildDbgValueRawNode(debuggerValueNodeChanged, childNode, newNode, (uint)i, Context.ValueNodeReader); @@ -560,9 +560,9 @@ void RefreshAllColumns() { bool IsEditingValue() => nameEditableValue?.IsEditingValue == true || valueEditableValue?.IsEditingValue == true; internal void ClearEditingValueProperties() { - if (!(nameEditableValue is null)) + if (nameEditableValue is not null) nameEditableValue.IsEditingValue = false; - if (!(valueEditableValue is null)) + if (valueEditableValue is not null) valueEditableValue.IsEditingValue = false; } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodesVM.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodesVM.cs index de21a3f155..cc77d0862d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodesVM.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/ValueNodesVM.cs @@ -109,7 +109,7 @@ public ValueNodesVM(UIDispatcher uiDispatcher, ValueNodesVMOptions options, ITre // UI thread void OnValueNodeAssigned(string? errorMessage, bool retry) { valueNodesContext.UIDispatcher.VerifyAccess(); - if (!(errorMessage is null)) + if (errorMessage is not null) valueNodesContext.ShowMessageBox(errorMessage, ShowMessageBoxButtons.OK); if (!retry) { OnVariableChanged?.Invoke(this, EventArgs.Empty); @@ -237,7 +237,7 @@ internal void RecreateRootChildren_UI() { default: throw new InvalidOperationException(); } selectNodeKind = SelectNodeKind.None; - if (!(node is null)) { + if (node is not null) { treeView.SelectItems(new[] { node.Data }); treeView.ScrollIntoView(); } @@ -263,11 +263,11 @@ void VerifyChildren_UI(DbgValueNodeInfo[] infos) { var node = (ValueNodeImpl)children[i].Data; if (node.RawNode is DbgValueRawNode rootNode) Debug.Assert(rootNode.DebuggerValueNode == infos[i].Node); - else if (!(infos[i].Node is null) && infos[i].CausesSideEffects && infos[i].Node!.HasError) { + else if (infos[i].Node is not null && infos[i].CausesSideEffects && infos[i].Node!.HasError) { } else Debug2.Assert(infos[i].Node is null); - Debug2.Assert(!valueNodesProvider.CanAddRemoveExpressions || !(infos[i].Id is null), "Root IDs are required"); + Debug2.Assert(!valueNodesProvider.CanAddRemoveExpressions || infos[i].Id is not null, "Root IDs are required"); Debug.Assert(infos[i].Id == node.RootId); } } @@ -387,7 +387,7 @@ void SetNewRootChildren_UI(DbgValueNodeInfo[] infos) { if (valueNodesContext.EditValueNodeExpression.SupportsEditExpression) { var children = rootNode.TreeNode.Children; var editNode = TryGetEditNode(); - if (infos.Length == 0 && children.Count == 1 && !(editNode is null)) + if (infos.Length == 0 && children.Count == 1 && editNode is not null) return; if (children.Count < 30) { while (children.Count > 0 && editNode != children[0].Data) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/VariablesWindowOperationsImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/VariablesWindowOperationsImpl.cs index 5b8d9f9f64..95d0e1a320 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/VariablesWindowOperationsImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/VariablesWindowOperationsImpl.cs @@ -209,7 +209,7 @@ static bool HasClipboardExpressions() { return null; } - public override bool SupportsPaste(IValueNodesVM vm) => !(vm is null) && vm.CanAddRemoveExpressions; + public override bool SupportsPaste(IValueNodesVM vm) => vm is not null && vm.CanAddRemoveExpressions; public override bool CanPaste(IValueNodesVM vm) => CanExecCommands(vm) && SupportsPaste(vm) && HasClipboardExpressions(); public override void Paste(IValueNodesVM vm) { if (!CanPaste(vm)) @@ -246,7 +246,7 @@ static string GetExpression(string s) { return s; } - public override bool SupportsDeleteWatch(IValueNodesVM vm) => !(vm is null) && vm.CanAddRemoveExpressions; + public override bool SupportsDeleteWatch(IValueNodesVM vm) => vm is not null && vm.CanAddRemoveExpressions; public override bool CanDeleteWatch(IValueNodesVM vm) => CanExecCommands(vm, isWatch: true) && SupportsDeleteWatch(vm) && HasSelectedNodes(vm); public override void DeleteWatch(IValueNodesVM vm) { if (!CanDeleteWatch(vm)) @@ -254,7 +254,7 @@ public override void DeleteWatch(IValueNodesVM vm) { vm.DeleteExpressions(SelectedNodes(vm).Select(a => a.RootId).OfType().ToArray()); } - public override bool SupportsClearAll(IValueNodesVM vm) => !(vm is null) && vm.CanAddRemoveExpressions; + public override bool SupportsClearAll(IValueNodesVM vm) => vm is not null && vm.CanAddRemoveExpressions; public override bool CanClearAll(IValueNodesVM vm) => CanExecCommands(vm) && SupportsClearAll(vm) && !IsEmpty(vm); public override void ClearAll(IValueNodesVM vm) { if (!CanClearAll(vm)) @@ -285,7 +285,7 @@ public override void Edit(IValueNodesVM vm, string text) { EditValue(vm, text); } - public override bool SupportsEditExpression(IValueNodesVM vm) => !(vm is null) && vm.CanAddRemoveExpressions; + public override bool SupportsEditExpression(IValueNodesVM vm) => vm is not null && vm.CanAddRemoveExpressions; public override bool CanEditExpression(IValueNodesVM vm) => CanExecCommands(vm) && SupportsEditExpression(vm) && SelectedNode(vm)?.CanEditNameExpression() == true; public override void EditExpression(IValueNodesVM vm) { if (!CanEditExpression(vm)) @@ -350,7 +350,7 @@ public override bool IsMakeObjectIdVisible(IValueNodesVM vm) { if (node.RawNode is DebuggerValueRawNode rawNode && rawNode.DebuggerValueNode.Value is DbgValue value) { if (dbgObjectIdService.Value.CanCreateObjectId(value)) return true; - if (!(dbgObjectIdService.Value.GetObjectId(value) is null)) + if (dbgObjectIdService.Value.GetObjectId(value) is not null) removeCount++; } } @@ -365,7 +365,7 @@ public override void MakeObjectId(IValueNodesVM vm) { dbgObjectIdService.Value.CreateObjectIds(values); } - public override bool CanDeleteObjectId(IValueNodesVM vm) => CanExecCommands(vm) && SelectedNodes(vm).Select(a => a.RawNode).OfType().Any(a => a.DebuggerValueNode.Value is DbgValue value && !(dbgObjectIdService.Value.GetObjectId(value) is null)); + public override bool CanDeleteObjectId(IValueNodesVM vm) => CanExecCommands(vm) && SelectedNodes(vm).Select(a => a.RawNode).OfType().Any(a => a.DebuggerValueNode.Value is DbgValue value && dbgObjectIdService.Value.GetObjectId(value) is not null); public override void DeleteObjectId(IValueNodesVM vm) { if (!CanDeleteObjectId(vm)) return; @@ -428,14 +428,14 @@ static void Save(DbgValueNode? valueNode, Lazy pickSaveFilena } } - public override bool CanShowInMemoryWindow(IValueNodesVM vm) => CanExecCommands(vm) && !(GetValue(SelectedNode(vm)?.RawNode)?.GetRawAddressValue(onlyDataAddress: true) is null); + public override bool CanShowInMemoryWindow(IValueNodesVM vm) => CanExecCommands(vm) && GetValue(SelectedNode(vm)?.RawNode)?.GetRawAddressValue(onlyDataAddress: true) is not null; public override void ShowInMemoryWindow(IValueNodesVM vm) { if (!CanShowInMemoryWindow(vm)) return; ShowInMemoryWindowCore(vm, null); } - public override bool CanShowInMemoryWindow(IValueNodesVM vm, int windowIndex) => CanExecCommands(vm) && !(GetValue(SelectedNode(vm)?.RawNode)?.GetRawAddressValue(onlyDataAddress: true) is null); + public override bool CanShowInMemoryWindow(IValueNodesVM vm, int windowIndex) => CanExecCommands(vm) && GetValue(SelectedNode(vm)?.RawNode)?.GetRawAddressValue(onlyDataAddress: true) is not null; public override void ShowInMemoryWindow(IValueNodesVM vm, int windowIndex) { if (!CanShowInMemoryWindow(vm, windowIndex)) return; @@ -454,20 +454,20 @@ void ShowInMemoryWindowCore(IValueNodesVM vm, int? windowIndex) { var addr = valueNode?.Value?.GetRawAddressValue(onlyDataAddress: true); if (addr is null) return; - Debug2.Assert(!(valueNode is null)); + Debug2.Assert(valueNode is not null); var process = valueNode.Process; var start = new HexPosition(addr.Value.Address); var end = start + addr.Value.Length; Debug.Assert(end <= HexPosition.MaxEndPosition); if (end <= HexPosition.MaxEndPosition) { - if (!(windowIndex is null)) + if (windowIndex is not null) memoryWindowService.Value.Show(process.Id, HexSpan.FromBounds(start, end), windowIndex.Value); else memoryWindowService.Value.Show(process.Id, HexSpan.FromBounds(start, end)); } } - public override bool CanToggleExpanded(IValueNodesVM vm) => CanExecCommands(vm) && !(SelectedNode(vm) is null); + public override bool CanToggleExpanded(IValueNodesVM vm) => CanExecCommands(vm) && SelectedNode(vm) is not null; public override void ToggleExpanded(IValueNodesVM vm) { if (!CanToggleExpanded(vm)) return; @@ -479,7 +479,7 @@ public override void ToggleExpanded(IValueNodesVM vm) { } static ValueNode? GetParent(ValueNode? node) => node?.TreeNode.Parent?.Data as ValueNode; - public override bool CanCollapseParent(IValueNodesVM vm) => CanExecCommands(vm) && !(GetParent(SelectedNode(vm)) is null); + public override bool CanCollapseParent(IValueNodesVM vm) => CanExecCommands(vm) && GetParent(SelectedNode(vm)) is not null; public override void CollapseParent(IValueNodesVM vm) { if (!CanCollapseParent(vm)) return; @@ -489,7 +489,7 @@ public override void CollapseParent(IValueNodesVM vm) { parent.TreeNode.IsExpanded = false; } - static bool CanExpand(ValueNodeImpl? node) => !(node is null) && !node.TreeNode.IsExpanded && (node.TreeNode.LazyLoading || node.TreeNode.Children.Count > 0); + static bool CanExpand(ValueNodeImpl? node) => node is not null && !node.TreeNode.IsExpanded && (node.TreeNode.LazyLoading || node.TreeNode.Children.Count > 0); ValueNodeImpl? GetExpandChildrenNode(IValueNodesVM vm) { if (!CanExecCommands(vm)) return null; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/VariablesWindowsCommands.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/VariablesWindowsCommands.cs index 81fe70f16a..33e7eafac0 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/VariablesWindowsCommands.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/ViewModel/Impl/VariablesWindowsCommands.cs @@ -190,7 +190,7 @@ public override void Execute(VariablesWindowCtxMenuContext context) { } IEnumerable IMenuItemProvider.Create(IMenuItemContext context) { var ctx = CreateContext(context); - Debug2.Assert(!(ctx is null)); + Debug2.Assert(ctx is not null); if (ctx is null) yield break; @@ -228,7 +228,7 @@ public override void Execute(VariablesWindowCtxMenuContext context) { } IEnumerable IMenuItemProvider.Create(IMenuItemContext context) { var ctx = CreateContext(context); - Debug2.Assert(!(ctx is null)); + Debug2.Assert(ctx is not null); if (ctx is null) yield break; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/DbgExceptionFormatterService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/DbgExceptionFormatterService.cs index 9f9f7debb3..c9d13d08b2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/DbgExceptionFormatterService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/DbgExceptionFormatterService.cs @@ -62,7 +62,7 @@ public override void WriteName(IDbgTextWriter writer, DbgExceptionDefinition def if (definition.Id.Category is null) throw new ArgumentException(); WriteNameCore(writer, definition); - if (includeDescription && !(definition.Description is null)) { + if (includeDescription && definition.Description is not null) { writer.Write(DbgTextColor.Text, " "); WriteDescription(writer, definition); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/DbgExceptionSettingsServiceImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/DbgExceptionSettingsServiceImpl.cs index e6063ba904..e244e79bb0 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/DbgExceptionSettingsServiceImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/DbgExceptionSettingsServiceImpl.cs @@ -102,7 +102,7 @@ void ModifyCore(DbgExceptionIdAndSettings[] settings) { foreach (var s in settings) { if (!toExceptionInfo.TryGetValue(s.Id, out var info)) continue; - Debug2.Assert(!(s.Settings.Conditions is null)); + Debug2.Assert(s.Settings.Conditions is not null); if (s.Settings.Conditions is null) continue; if (info.Settings == s.Settings) @@ -149,7 +149,7 @@ void AddCore(DbgExceptionSettingsInfo[] settings) { foreach (var s in settings) { if (toExceptionInfo.ContainsKey(s.Definition.Id)) continue; - bool b = !(s.Definition.Id.Category is null) && !(s.Settings.Conditions is null); + bool b = s.Definition.Id.Category is not null && s.Settings.Conditions is not null; Debug.Assert(b); if (!b) continue; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/ExceptionConditionsChecker.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/ExceptionConditionsChecker.cs index 558bf3391d..5b07a23ff8 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/ExceptionConditionsChecker.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/ExceptionConditionsChecker.cs @@ -74,7 +74,7 @@ bool CheckConditions(ReadOnlyCollection condition } bool CheckConditions(DbgExceptionConditionSettings settings, DbgException exception) { - Debug2.Assert(!(settings.Condition is null)); + Debug2.Assert(settings.Condition is not null); if (settings.Condition is null) return false; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/ExceptionsFileReader.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/ExceptionsFileReader.cs index 549229cc21..75be7e3166 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/ExceptionsFileReader.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Exceptions/ExceptionsFileReader.cs @@ -97,7 +97,7 @@ public void Read(string filename) { static readonly char[] flagsSeparators = new char[] { ',' }; static DbgExceptionCategoryDefinitionFlags ParseCategoryFlags(string? flagsAttr) { var flags = DbgExceptionCategoryDefinitionFlags.None; - if (!(flagsAttr is null)) { + if (flagsAttr is not null) { foreach (var name in flagsAttr.Split(flagsSeparators, StringSplitOptions.RemoveEmptyEntries)) { switch (name.Trim().ToLowerInvariant()) { case "code": flags |= DbgExceptionCategoryDefinitionFlags.Code; break; @@ -111,7 +111,7 @@ static DbgExceptionCategoryDefinitionFlags ParseCategoryFlags(string? flagsAttr) static DbgExceptionDefinitionFlags ParseExceptionFlags(string? flagsAttr) { var flags = DbgExceptionDefinitionFlags.None; - if (!(flagsAttr is null)) { + if (flagsAttr is not null) { foreach (var name in flagsAttr.Split(flagsSeparators, StringSplitOptions.RemoveEmptyEntries)) { switch (name.Trim().ToLowerInvariant()) { case "stop1": flags |= DbgExceptionDefinitionFlags.StopFirstChance; break; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgAppDomainImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgAppDomainImpl.cs index 220e4a684e..0db03959c4 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgAppDomainImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgAppDomainImpl.cs @@ -50,7 +50,7 @@ void OnPropertyChanged(string propName) { internal void UpdateName_DbgThread(string? name) { Dispatcher.VerifyAccess(); - if (this.name != name && !(name is null)) { + if (this.name != name && name is not null) { this.name = name; OnPropertyChanged(nameof(Name)); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgEngineBoundCodeBreakpointMessageExtensions.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgEngineBoundCodeBreakpointMessageExtensions.cs index b3d2382729..70bc9ac80d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgEngineBoundCodeBreakpointMessageExtensions.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgEngineBoundCodeBreakpointMessageExtensions.cs @@ -25,23 +25,23 @@ You should have received a copy of the GNU General Public License namespace dnSpy.Debugger.Impl { static class DbgEngineBoundCodeBreakpointMessageExtensions { public static DbgBoundCodeBreakpointMessage ToDbgBoundCodeBreakpointMessage(this DbgEngineBoundCodeBreakpointMessage message) { - if (!(message.Arguments is null)) { + if (message.Arguments is not null) { switch (message.Kind) { case DbgEngineBoundCodeBreakpointMessageKind.None: return DbgBoundCodeBreakpointMessage.None; case DbgEngineBoundCodeBreakpointMessageKind.CustomWarning: - if (message.Arguments.Length == 1 && !(message.Arguments[0] is null)) + if (message.Arguments.Length == 1 && message.Arguments[0] is not null) return new DbgBoundCodeBreakpointMessage(DbgBoundCodeBreakpointSeverity.Warning, message.Arguments[0]); break; case DbgEngineBoundCodeBreakpointMessageKind.CustomError: - if (message.Arguments.Length == 1 && !(message.Arguments[0] is null)) + if (message.Arguments.Length == 1 && message.Arguments[0] is not null) return new DbgBoundCodeBreakpointMessage(DbgBoundCodeBreakpointSeverity.Error, message.Arguments[0]); break; case DbgEngineBoundCodeBreakpointMessageKind.FunctionNotFound: - if (message.Arguments.Length == 1 && !(message.Arguments[0] is null)) + if (message.Arguments.Length == 1 && message.Arguments[0] is not null) return new DbgBoundCodeBreakpointMessage(DbgBoundCodeBreakpointSeverity.Error, string.Format(dnSpy_Debugger_Resources.BreakpointMessage_TheFunctionCanNotBeFound, message.Arguments[0])); break; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.BoundBreakpointsManager.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.BoundBreakpointsManager.cs index 615b33a58f..09e30107f7 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.BoundBreakpointsManager.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.BoundBreakpointsManager.cs @@ -118,9 +118,9 @@ void BoundCodeBreakpointsService_BreakpointsModified(object? sender, DbgBreakpoi newDisabledBreakpoints.Add(info.Breakpoint); } } - if (!(newDisabledBreakpoints is null)) + if (newDisabledBreakpoints is not null) RemoveBoundBreakpoints_DbgThread(newDisabledBreakpoints); - if (!(newEnabledBreakpoints is null)) + if (newEnabledBreakpoints is not null) AddBoundBreakpoints_DbgThread(newEnabledBreakpoints); } @@ -187,7 +187,7 @@ Dictionary> GetEngineModules(IList modules var runtime = module.Runtime; if (runtime != lastRuntime) { var engine = GetEngine_NoLock(runtime); - Debug2.Assert(!(engine is null)); + Debug2.Assert(engine is not null); if (engine is null) continue; lastRuntime = runtime; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.BreakAllHelper.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.BreakAllHelper.cs index c6a5c08fd8..365b1914a9 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.BreakAllHelper.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.BreakAllHelper.cs @@ -62,12 +62,12 @@ public void Start_NoLock() { } void DoneStep1_NoLock(out bool canNotify) { - if (!(timer is null)) { + if (timer is not null) { timer.Tick -= Timer_Tick_DbgThread; timer.Stop(); timer = null; } - canNotify = !(owner.breakAllHelper is null); + canNotify = owner.breakAllHelper is not null; owner.breakAllHelper = null; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.CurrentObjects.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.CurrentObjects.cs index 7e179aa5f7..91109c14a0 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.CurrentObjects.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.CurrentObjects.cs @@ -201,7 +201,7 @@ bool SetCurrentEngineIfCurrentIsNull_DbgThread(DbgEngine engine, bool forceSet) DbgCurrentObjectChangedEventArgs runtimeEventArgs; DbgCurrentObjectChangedEventArgs threadEventArgs; lock (lockObj) { - if (!forceSet && !(dbgCurrentProcess.currentProcess.Current is null)) + if (!forceSet && dbgCurrentProcess.currentProcess.Current is not null) return false; var info = GetEngineInfo_NoLock(engine); var process = info.Process; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.StopDebuggingHelper.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.StopDebuggingHelper.cs index 9ad25cca03..3a6478a329 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.StopDebuggingHelper.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.StopDebuggingHelper.cs @@ -62,7 +62,7 @@ public void Initialize() { // Random thread void StopTimer() { lock (lockObj) { - if (!(timer is null)) { + if (timer is not null) { timer.Tick -= Timer_Tick_DbgThread; timer.Stop(); timer = null; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.cs index f4f27bcf68..841ba23fa1 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgManagerImpl.cs @@ -321,7 +321,7 @@ void RaiseDelayedIsRunningChanged_DbgThread() { try { foreach (var lz in dbgEngineProviders) { var engine = lz.Value.Create(this, options); - if (!(engine is null)) { + if (engine is not null) { DbgThread(() => Start_DbgThread(engine, options, clonedOptions)); return null; } @@ -475,7 +475,7 @@ DbgProcessImpl GetOrCreateProcess_DbgThread(int pid, DbgStartKind startKind, out void OnConnected_DbgThread(DbgEngine engine, DbgMessageConnected e) { Dispatcher.VerifyAccess(); - if (!(e.ErrorMessage is null)) { + if (e.ErrorMessage is not null) { RaiseUserMessage_DbgThread(UserMessageKind.CouldNotConnect, e.ErrorMessage ?? "???"); OnDisconnected_DbgThread(engine); return; @@ -499,7 +499,7 @@ void OnConnected_DbgThread(DbgEngine engine, DbgMessageConnected e) { info.Runtime.SetBreakThread(null); processState = CalculateProcessState(info.Process); // Compare it before notifying the helper since it could clear it - otherPauseProgram = !(breakAllHelper is null); + otherPauseProgram = breakAllHelper is not null; breakAllHelper?.OnConnected_DbgThread_NoLock(info); bool b = debuggedRuntimes.Add(new ProcessKey(e.ProcessId, runtime.Id)); Debug.Assert(b); @@ -533,7 +533,7 @@ void OnConnected_DbgThread(DbgEngine engine, DbgMessageConnected e) { DbgProcessState CalculateProcessState(DbgProcess? process) { lock (lockObj) { int count = 0; - if (!(process is null)) { + if (process is not null) { foreach (var info in engines) { if (info.Process != process) continue; @@ -562,8 +562,8 @@ void OnDisconnected_DbgThread(DbgEngine engine) { lock (lockObj) { var oldIsRunning = cachedIsRunning; var info = TryGetEngineInfo_NoLock(engine); - if (!(info is null)) { - if (!(info.Exception is null)) + if (info is not null) { + if (info.Exception is not null) objectsToClose.Add(info.Exception); engines.Remove(info); raiseIsDebuggingChanged = engines.Count == 0; @@ -579,10 +579,10 @@ void OnDisconnected_DbgThread(DbgEngine engine) { raiseIsRunningChanged = oldIsRunning != cachedIsRunning; engine.Message -= DbgEngine_Message; - if (!(process is null)) { + if (process is not null) { var pinfo = process.Remove_DbgThread(engine); runtime = pinfo.runtime; - Debug2.Assert(!(runtime is null)); + Debug2.Assert(runtime is not null); runtime.SetBreakInfos_DbgThread(Array.Empty()); bool b = debuggedRuntimes.Remove(new ProcessKey(process.Id, runtime.Id)); @@ -599,7 +599,7 @@ void OnDisconnected_DbgThread(DbgEngine engine) { breakAllHelper?.OnDisconnected_DbgThread_NoLock(engine); } - if (!(runtime is null)) + if (runtime is not null) boundBreakpointsManager.RemoveAllBoundBreakpoints_DbgThread(runtime); foreach (var obj in objectsToClose) @@ -608,10 +608,10 @@ void OnDisconnected_DbgThread(DbgEngine engine) { process?.NotifyRuntimesChanged_DbgThread(runtime!); var builder = new DbgBreakInfoCollectionBuilder(); - if (!(runtime is null)) + if (runtime is not null) RaiseMessage_DbgThread(ref builder, new DbgMessageRuntimeExitedEventArgs(runtime)); - if (!(processToDispose is null)) { + if (processToDispose is not null) { processToDispose.UpdateState_DbgThread(DbgProcessState.Terminated); ProcessesChanged?.Invoke(this, new DbgCollectionChangedEventArgs(processToDispose, added: false)); int exitCode = processToDispose.GetExitCode(); @@ -638,9 +638,9 @@ void OnDisconnected_DbgThread(DbgEngine engine) { public override bool CanRestart { get { lock (lockObj) { - if (!(breakAllHelper is null)) + if (breakAllHelper is not null) return false; - if (!(stopDebuggingHelper is null)) + if (stopDebuggingHelper is not null) return false; if (restartOptions.Count == 0) return false; @@ -656,7 +656,7 @@ public override void Restart() { var restartOptionsCopy = restartOptions.ToArray(); stopDebuggingHelper = new StopDebuggingHelper(this, success => { lock (lockObj) { - Debug2.Assert(!(stopDebuggingHelper is null)); + Debug2.Assert(stopDebuggingHelper is not null); stopDebuggingHelper = null; } // Don't restart the programs in this thread since we're inside a ProcessesChanged callback. @@ -679,9 +679,9 @@ public override void Restart() { public override void BreakAll() { lock (lockObj) { - if (!(breakAllHelper is null)) + if (breakAllHelper is not null) return; - if (!(stopDebuggingHelper is null)) + if (stopDebuggingHelper is not null) return; breakAllHelper = new BreakAllHelper(this); breakAllHelper.Start_NoLock(); @@ -724,7 +724,7 @@ void OnBreak_DbgThread(DbgEngine engine, DbgMessageBreak e) { if (e.ErrorMessage is null) { var builder = new DbgBreakInfoCollectionBuilder(); - if (!(info.Runtime is null)) + if (info.Runtime is not null) builder.Add(new DbgMessageBreakEventArgs(info.Runtime, e.Thread)); else builder.Add(new DbgBreakInfo(DbgBreakInfoKind.Unknown, null)); @@ -757,7 +757,7 @@ void OnEnginePaused_DbgThread(DbgEngine engine, DbgProcess? process, DbgThread? } bool didSetCurrentProcess = SetCurrentEngineIfCurrentIsNull_DbgThread(engine, setCurrentProcess); BreakAllProcessesIfNeeded_DbgThread(); - if (didSetCurrentProcess && !(process is null)) + if (didSetCurrentProcess && process is not null) ProcessPaused?.Invoke(this, new ProcessPausedEventArgs(process, thread)); } @@ -776,7 +776,7 @@ void BreakCompleted_DbgThread(bool success) { void OnEntryPointBreak_DbgThread(DbgEngine engine, DbgMessageEntryPointBreak e) { Dispatcher.VerifyAccess(); var runtime = GetRuntime(engine); - Debug2.Assert(!(runtime is null)); + Debug2.Assert(runtime is not null); if (runtime is null) return; var ep = new DbgMessageEntryPointBreakEventArgs(runtime, e.Thread); @@ -786,7 +786,7 @@ void OnEntryPointBreak_DbgThread(DbgEngine engine, DbgMessageEntryPointBreak e) void OnProgramMessage_DbgThread(DbgEngine engine, DbgMessageProgramMessage e) { Dispatcher.VerifyAccess(); var runtime = GetRuntime(engine); - Debug2.Assert(!(runtime is null)); + Debug2.Assert(runtime is not null); if (runtime is null) return; var ep = new DbgMessageProgramMessageEventArgs(e.Message, runtime, e.Thread); @@ -796,7 +796,7 @@ void OnProgramMessage_DbgThread(DbgEngine engine, DbgMessageProgramMessage e) { void OnAsyncProgramMessage_DbgThread(DbgEngine engine, DbgMessageAsyncProgramMessage e) { Dispatcher.VerifyAccess(); var runtime = GetRuntime(engine); - Debug2.Assert(!(runtime is null)); + Debug2.Assert(runtime is not null); if (runtime is null) return; var ep = new DbgMessageAsyncProgramMessageEventArgs(e.Source, e.Message, runtime); @@ -812,7 +812,7 @@ void OnBreakpoint_DbgThread(DbgEngine engine, DbgMessageBreakpoint e) { void OnProgramBreak_DbgThread(DbgEngine engine, DbgMessageProgramBreak e) { Dispatcher.VerifyAccess(); var runtime = GetRuntime(engine); - Debug2.Assert(!(runtime is null)); + Debug2.Assert(runtime is not null); if (runtime is null) return; var eb = new DbgMessageProgramBreakEventArgs(runtime, e.Thread); @@ -914,7 +914,7 @@ void OnConditionalBreak_DbgThread(DbgEngine engine, DbgMessageEventArgs e, DbgTh bool otherPauseProgram = false; if (!pauseProgram && builder.IsEmpty) { lock (lockObj) { - otherPauseProgram |= !(breakAllHelper is null); + otherPauseProgram |= breakAllHelper is not null; // If we're func-eval'ing, don't pause it if (!otherPauseProgram && (messageFlags & DbgEngineMessageFlags.Continue) == 0) otherPauseProgram |= GetEngineInfo_NoLock(engine).EngineState == EngineState.Paused; @@ -939,7 +939,7 @@ void OnConditionalBreak_DbgThread(DbgEngine engine, DbgMessageEventArgs e, DbgTh if (thread is null) thread = newThread; // If we get eg. SetIPComplete, the saved exception shouldn't be cleared - if (!(exception is null)) { + if (exception is not null) { Debug2.Assert(info.Exception is null); info.Exception?.Close(Dispatcher); info.Exception = exception; @@ -995,7 +995,7 @@ void RunEngines_DbgThread(EngineInfo[] engineInfos, Action runEngine List? exceptions = null; lock (lockObj) { foreach (var info in engineInfos) { - if (info.EngineState == EngineState.Paused && !(info.Exception is null)) { + if (info.EngineState == EngineState.Paused && info.Exception is not null) { if (exceptions is null) exceptions = new List(); exceptions.Add(info.Exception); @@ -1003,7 +1003,7 @@ void RunEngines_DbgThread(EngineInfo[] engineInfos, Action runEngine } } } - if (!(exceptions is null)) { + if (exceptions is not null) { foreach (var exception in exceptions) exception.Close(Dispatcher); } @@ -1014,12 +1014,12 @@ void RunEngines_DbgThread(EngineInfo[] engineInfos, Action runEngine var oldIsRunning = cachedIsRunning; // If we're trying to break the processes, don't do a thing - if (!(breakAllHelper is null)) + if (breakAllHelper is not null) return; foreach (var info in engineInfos) { if (info.EngineState == EngineState.Paused) { - if (!(info.Process is null) && !processes.Contains(info.Process)) + if (info.Process is not null && !processes.Contains(info.Process)) processes.Add(info.Process); info.EngineState = EngineState.Running; info.Runtime?.SetBreakInfos_DbgThread(Array.Empty()); @@ -1045,7 +1045,7 @@ internal void SetDelayedIsRunning_DbgThread(DbgEngine[] engines) { lock (lockObj) { foreach (var engine in engines) { var info = TryGetEngineInfo_NoLock(engine); - if (!(info is null)) { + if (info is not null) { info.Runtime?.ClearBreakThread(); info.DelayedIsRunning = true; } @@ -1070,7 +1070,7 @@ void Run_DbgThread(DbgEngine engine) { EngineInfo? engineInfo; lock (lockObj) engineInfo = TryGetEngineInfo_NoLock(engine); - if (!(engineInfo is null)) + if (engineInfo is not null) RunEngines_DbgThread(new[] { engineInfo }); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgModuleImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgModuleImpl.cs index 03590ee8c1..400d671227 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgModuleImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgModuleImpl.cs @@ -147,7 +147,7 @@ internal void UpdateImageLayout_DbgThread(DbgImageLayout imageLayout) { internal void UpdateName_DbgThread(string? name) { Dispatcher.VerifyAccess(); - if (this.name != name && !(name is null)) { + if (this.name != name && name is not null) { this.name = name; OnPropertyChanged(nameof(Name)); } @@ -155,7 +155,7 @@ internal void UpdateName_DbgThread(string? name) { internal void UpdateFilename_DbgThread(string? filename) { Dispatcher.VerifyAccess(); - if (this.filename != filename && !(filename is null)) { + if (this.filename != filename && filename is not null) { this.filename = filename; OnPropertyChanged(nameof(Filename)); } @@ -210,7 +210,7 @@ internal void UpdateTimestamp_DbgThread(DateTime? timestamp) { internal void UpdateVersion_DbgThread(string? version) { Dispatcher.VerifyAccess(); - if (this.version != version && !(version is null)) { + if (this.version != version && version is not null) { this.version = version; OnPropertyChanged(nameof(Version)); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgObjectFactoryImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgObjectFactoryImpl.cs index 162600f8a2..64a4520945 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgObjectFactoryImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgObjectFactoryImpl.cs @@ -53,7 +53,7 @@ public override DbgEngineAppDomain CreateAppDomain(DbgInternalAppDomain inter if (disposed) throw new ObjectDisposedException(nameof(DbgObjectFactoryImpl)); var appDomain = new DbgAppDomainImpl(runtime, internalAppDomain, name, id); - if (!(data is null)) + if (data is not null) appDomain.GetOrCreateData(() => data); var engineAppDomain = new DbgEngineAppDomainImpl(appDomain); onCreated?.Invoke(engineAppDomain); @@ -76,7 +76,7 @@ public override DbgEngineModule CreateModule(DbgAppDomain? appDomain, DbgInte if (disposed) throw new ObjectDisposedException(nameof(DbgObjectFactoryImpl)); var module = new DbgModuleImpl(runtime, VerifyOptionalAppDomain(appDomain), internalModule, isExe, address, size, imageLayout, name, filename, isDynamic, isInMemory, isOptimized, order, timestamp, version); - if (!(data is null)) + if (data is not null) module.GetOrCreateData(() => data); var engineModule = new DbgEngineModuleImpl(module); onCreated?.Invoke(engineModule); @@ -88,7 +88,7 @@ public override DbgEngineThread CreateThread(DbgAppDomain? appDomain, string if (disposed) throw new ObjectDisposedException(nameof(DbgObjectFactoryImpl)); var thread = new DbgThreadImpl(runtime, VerifyOptionalAppDomain(appDomain), kind, id, managedId, name, suspendedCount, state); - if (!(data is null)) + if (data is not null) thread.GetOrCreateData(() => data); var engineThread = new DbgEngineThreadImpl(thread); onCreated?.Invoke(engineThread); @@ -100,7 +100,7 @@ public override DbgException CreateException(DbgExceptionId id, DbgExceptionE if (id.IsDefaultId) throw new ArgumentException(); var exception = new DbgExceptionImpl(runtime, id, flags, message, thread, module); - if (!(data is null)) + if (data is not null) exception.GetOrCreateData(() => data); onCreated?.Invoke(exception); owner.Dispatcher.BeginInvoke(() => owner.AddException_DbgThread(runtime, exception, messageFlags)); @@ -135,16 +135,16 @@ public override DbgEngineBoundCodeBreakpoint[] Create(DbgBoundCodeBreakpointI else { var bp = new DbgBoundCodeBreakpointImpl(runtime, breakpoint, info.Module, info.Address, info.Message.ToDbgBoundCodeBreakpointMessage()); var data = info.Data; - if (!(data is null)) + if (data is not null) bp.GetOrCreateData(() => data); var ebp = new DbgEngineBoundCodeBreakpointImpl(bp); bps.Add(ebp); bpImpls.Add(ebp); } } - if (bpImpls.Count > 0 || !(dataToDispose is null)) { + if (bpImpls.Count > 0 || dataToDispose is not null) { owner.Dispatcher.BeginInvoke(() => { - if (!(dataToDispose is null)) { + if (dataToDispose is not null) { foreach (var id in dataToDispose) id.Dispose(); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgProcessImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgProcessImpl.cs index 8f6c2ab9e6..d0e931c977 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgProcessImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgProcessImpl.cs @@ -178,7 +178,7 @@ void UpdateRuntime_DbgThread(DbgRuntimeImpl? runtime) { } DbgRuntimeImpl? GetRuntime_NoLock(DbgRuntimeImpl? runtime, DbgRuntimeImpl? defaultRuntime) { - if (!(runtime is null)) { + if (runtime is not null) { var info = engineInfos.First(a => a.Runtime == runtime); if (info.IsPaused || owner.GetDelayedIsRunning_DbgThread(info.Engine) == false) return runtime; @@ -499,7 +499,7 @@ internal void NotifyRuntimesChanged_DbgThread(DbgRuntime runtime) { ThreadsChanged?.Invoke(this, new DbgCollectionChangedEventArgs(removedThreads, added: false)); if (raiseDebuggingChanged) OnPropertyChanged(nameof(Debugging)); - if (!(runtime is null)) + if (runtime is not null) RuntimesChanged?.Invoke(this, new DbgCollectionChangedEventArgs(runtime, added: false)); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgRuntimeImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgRuntimeImpl.cs index 954c12bbfa..386e29b83c 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgRuntimeImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgRuntimeImpl.cs @@ -125,7 +125,7 @@ internal void SetCurrentThread_DbgThread(DbgThreadImpl thread) { else newCurrent = newBreak; } - Debug2.Assert((!(newBreak is null)) == (!(newCurrent is null))); + Debug2.Assert((newBreak is not null) == (newCurrent is not null)); currentThread = new CurrentObject(newCurrent, newBreak); return newCurrent; } @@ -175,17 +175,17 @@ internal void Remove_DbgThread(DbgAppDomainImpl appDomain, DbgEngineMessageFlags } } } - if (!(threadsToRemove is null) && threadsToRemove.Count != 0) + if (threadsToRemove is not null && threadsToRemove.Count != 0) ThreadsChanged?.Invoke(this, new DbgCollectionChangedEventArgs(threadsToRemove, added: false)); - if (!(modulesToRemove is null) && modulesToRemove.Count != 0) + if (modulesToRemove is not null && modulesToRemove.Count != 0) ModulesChanged?.Invoke(this, new DbgCollectionChangedEventArgs(modulesToRemove, added: false)); owner.RemoveAppDomain_DbgThread(this, appDomain, messageFlags); AppDomainsChanged?.Invoke(this, new DbgCollectionChangedEventArgs(appDomain, added: false)); - if (!(threadsToRemove is null)) { + if (threadsToRemove is not null) { foreach (var thread in threadsToRemove) thread.Close(Dispatcher); } - if (!(modulesToRemove is null)) { + if (modulesToRemove is not null) { foreach (var module in modulesToRemove) module.Close(Dispatcher); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgThreadImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgThreadImpl.cs index 3c520491a4..0a99421a5a 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgThreadImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DbgThreadImpl.cs @@ -120,7 +120,7 @@ internal void UpdateKind_DbgThread(string? kind) { bool raiseEvent, raiseUINameEvent; lock (lockObj) { var oldUIName = GetUINameNoDefaultName_NoLock(); - raiseEvent = this.kind != kind && !(kind is null); + raiseEvent = this.kind != kind && kind is not null; if (raiseEvent) this.kind = kind!; raiseUINameEvent = oldUIName != GetUINameNoDefaultName_NoLock(); @@ -158,7 +158,7 @@ internal void UpdateName_DbgThread(string? name) { bool raiseEvent, raiseUINameEvent; lock (lockObj) { var oldUIName = GetUINameNoDefaultName_NoLock(); - raiseEvent = this.name != name && !(name is null); + raiseEvent = this.name != name && name is not null; if (raiseEvent) this.name = name!; raiseUINameEvent = oldUIName != GetUINameNoDefaultName_NoLock(); @@ -217,7 +217,7 @@ internal int GetExitCode() { public override bool HasName() { lock (lockObj) - return !(GetUINameNoDefaultName_NoLock() is null); + return GetUINameNoDefaultName_NoLock() is not null; } void WriteUIName_DbgThread(string newUserName) { @@ -231,11 +231,11 @@ void WriteUIName_DbgThread(string newUserName) { } string? GetUINameNoDefaultName_NoLock() { - if (!(userName is null)) + if (userName is not null) return userName; var threadName = name; - if (!(threadName is null)) + if (threadName is not null) return threadName; if (kind == PredefinedThreadKinds.Main) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DebuggerThread.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DebuggerThread.cs index b3f864b9d0..312fe5dc4e 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DebuggerThread.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/DebuggerThread.cs @@ -67,7 +67,7 @@ void DebuggerThreadProc(AutoResetEvent autoResetEvent) { internal void Terminate() { terminate = true; try { callDispatcherRunEvent?.Set(); } catch (ObjectDisposedException) { } - if (!(Dispatcher is null) && !Dispatcher.HasShutdownStarted && !Dispatcher.HasShutdownFinished) + if (Dispatcher is not null && !Dispatcher.HasShutdownStarted && !Dispatcher.HasShutdownFinished) Dispatcher.BeginInvokeShutdown(); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/SwitchToDebuggedProcess.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/SwitchToDebuggedProcess.cs index e2652899f6..4b040f4d43 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/SwitchToDebuggedProcess.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Impl/SwitchToDebuggedProcess.cs @@ -51,7 +51,7 @@ void DbgManager_CurrentProcessChanged(object? sender, DbgCurrentObjectChangedEve if (!e.CurrentChanged) return; var newProcess = ((DbgManager)sender!).CurrentProcess.Current; - if (!(newProcess is null)) + if (newProcess is not null) currentProcess = newProcess; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Settings/DebuggerAppSettingsPage.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Settings/DebuggerAppSettingsPage.cs index b7b483d3a3..7fd314f77b 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Settings/DebuggerAppSettingsPage.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Settings/DebuggerAppSettingsPage.cs @@ -73,7 +73,7 @@ public DebuggerAppSettingsPage(DebuggerSettingsImpl debuggerSettingsImpl, Lazy a.Name == info.languageName); dbgLanguageService.Value.SetCurrentLanguage(info.runtimeKindGuid, language); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Shared/DispatcherTimer.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Shared/DispatcherTimer.cs index 59456af50a..516f6fbe99 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Shared/DispatcherTimer.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Shared/DispatcherTimer.cs @@ -59,7 +59,7 @@ void OnTimerCallback(object? state) { public void Start() { lock (lockObj) { - if (!(timer is null)) + if (timer is not null) return; timer = new Timer(OnTimerCallback, null, interval, interval); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Steppers/DbgStepperImpl.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Steppers/DbgStepperImpl.cs index 963b6ec983..30a953b425 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Steppers/DbgStepperImpl.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Steppers/DbgStepperImpl.cs @@ -34,7 +34,7 @@ sealed class DbgStepperImpl : DbgStepper { public override bool IsStepping { get { lock (lockObj) - return !(stepperTag is null); + return stepperTag is not null; } } @@ -62,7 +62,7 @@ void DbgEngineStepper_StepComplete_DbgThread(DbgEngineStepCompleteEventArgs e) { Dispatcher.VerifyAccess(); bool wasStepping; lock (lockObj) { - wasStepping = !(stepperTag is null) && stepperTag == e.Tag; + wasStepping = stepperTag is not null && stepperTag == e.Tag; stepperTag = null; thread = (DbgThreadImpl?)e.Thread ?? thread; } @@ -89,7 +89,7 @@ internal void RaiseError_DbgThread(string error) { throw new ArgumentNullException(nameof(error)); bool wasStepping; lock (lockObj) { - wasStepping = !(stepperTag is null); + wasStepping = stepperTag is not null; stepperTag = null; } if (wasStepping) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Text/ClassifiedTextWriter.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Text/ClassifiedTextWriter.cs index ccf9dc40da..5d943e4a7c 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/Text/ClassifiedTextWriter.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/Text/ClassifiedTextWriter.cs @@ -39,7 +39,7 @@ public ClassifiedTextCollection GetClassifiedText() { public void Clear() => result.Clear(); public void Write(DbgTextColor color, string? text) { - if (!(text is null)) + if (text is not null) result.Add(new ClassifiedText(color, text)); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/CallStackOperations.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/CallStackOperations.cs index 9da4efd6db..d2c744b57f 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/CallStackOperations.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/CallStackOperations.cs @@ -223,7 +223,7 @@ public override void RunToCursor() { var vm = (NormalStackFrameVM)SelectedItems[0]; var process = vm.Frame.Process; var bp = dbgCodeBreakpointsService.Value.Add(new DbgCodeBreakpointInfo(vm.Frame.Location!.Clone(), new DbgCodeBreakpointSettings { IsEnabled = true }, DbgCodeBreakpointOptions.Hidden | DbgCodeBreakpointOptions.Temporary | DbgCodeBreakpointOptions.OneShot)); - if (!(bp is null)) + if (bp is not null) dbgManager.Value.Run(process); } @@ -287,7 +287,7 @@ void AddBreakpointOrTracepoint(bool addBreakpoint) { var info = GetBreakpoint(); if (info is null) return; - if (!(info.Value.breakpoint is null)) { + if (info.Value.breakpoint is not null) { if (info.Value.breakpoint.IsEnabled) info.Value.breakpoint.Remove(); else @@ -301,13 +301,13 @@ void AddBreakpointOrTracepoint(bool addBreakpoint) { var settings = bp.Settings; settings.Trace = new DbgCodeBreakpointTrace(string.Empty, @continue: true); var newSettings = showCodeBreakpointSettingsService.Value.Show(settings); - if (!(newSettings is null)) + if (newSettings is not null) bp.Settings = newSettings.Value; } } } - public override bool CanEnableBreakpoint => !(GetBreakpoint()?.breakpoint is null); + public override bool CanEnableBreakpoint => GetBreakpoint()?.breakpoint is not null; public override void EnableBreakpoint() { if (!CanEnableBreakpoint) return; @@ -316,7 +316,7 @@ public override void EnableBreakpoint() { bp.IsEnabled = !bp.IsEnabled; } - public override bool CanRemoveBreakpoint => !(GetBreakpoint()?.breakpoint is null); + public override bool CanRemoveBreakpoint => GetBreakpoint()?.breakpoint is not null; public override void RemoveBreakpoint() { if (!CanRemoveBreakpoint) return; @@ -325,7 +325,7 @@ public override void RemoveBreakpoint() { bp.Remove(); } - public override bool CanEditBreakpointSettings => !(GetBreakpoint()?.breakpoint is null); + public override bool CanEditBreakpointSettings => GetBreakpoint()?.breakpoint is not null; public override void EditBreakpointSettings() { if (!CanEditBreakpointSettings) return; @@ -333,12 +333,12 @@ public override void EditBreakpointSettings() { if (info?.breakpoint is DbgCodeBreakpoint bp) { var settings = bp.Settings; var newSettings = showCodeBreakpointSettingsService.Value.Show(settings); - if (!(newSettings is null)) + if (newSettings is not null) bp.Settings = newSettings.Value; } } - public override bool CanExportBreakpoint => !(GetBreakpoint()?.breakpoint is null); + public override bool CanExportBreakpoint => GetBreakpoint()?.breakpoint is not null; public override void ExportBreakpoint() { if (!CanExportBreakpoint) return; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/Commands.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/Commands.cs index 023409c207..01e770b7fb 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/Commands.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/Commands.cs @@ -173,7 +173,7 @@ public override void Execute(CallStackCtxMenuContext context) { } IEnumerable IMenuItemProvider.Create(IMenuItemContext context) { var ctx = CreateContext(context); - Debug2.Assert(!(ctx is null)); + Debug2.Assert(ctx is not null); if (ctx is null) yield break; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/StackFrameVM.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/StackFrameVM.cs index 4211f71100..413e35c646 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/StackFrameVM.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CallStack/StackFrameVM.cs @@ -157,8 +157,8 @@ public void SetFrame_UI(DbgLanguage? language, DbgStackFrame frame) { } protected override ClassifiedTextCollection CreateName() { - Debug2.Assert(!(language is null)); - if (!(language is null) && !frame.IsClosed) { + Debug2.Assert(language is not null); + if (language is not null && !frame.IsClosed) { const CultureInfo? cultureInfo = null; CancellationToken cancellationToken = default; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CodeBreakpoints/CodeBreakpointsOperations.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CodeBreakpoints/CodeBreakpointsOperations.cs index b8394caebb..2bf00b02be 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CodeBreakpoints/CodeBreakpointsOperations.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/CodeBreakpoints/CodeBreakpointsOperations.cs @@ -255,7 +255,7 @@ public override void ImportBreakpoints() { var filename = pickFilename.GetFilename(null, "xml", PickFilenameConstants.XmlFilenameFilter); if (!File.Exists(filename)) return; - Debug2.Assert(!(filename is null)); + Debug2.Assert(filename is not null); var settingsService = settingsServiceFactory.Value.Create(); try { settingsService.Open(filename); @@ -313,7 +313,7 @@ public override void EditLabels() { SelectedItems[0].LabelsEditableValue.IsEditingValue = true; else { var newLabels = messageBoxService.Ask(dnSpy_Debugger_Resources.EditLabelsMsgBoxLabel, SelectedItems[0].GetLabelsString(), dnSpy_Debugger_Resources.EditLabelsTitle); - if (!(newLabels is null)) { + if (newLabels is not null) { var labelsColl = CodeBreakpointVM.CreateLabelsCollection(newLabels); dbgCodeBreakpointsService.Value.Modify(SelectedItems.Select(a => { var bm = a.CodeBreakpoint; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/AddExceptionVM.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/AddExceptionVM.cs index 52ca01b11c..1e029988f5 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/AddExceptionVM.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/AddExceptionVM.cs @@ -63,7 +63,7 @@ public NameOrCodeVM(Action onUpdated) public bool TryGetCode(out int code, [NotNullWhen(false)] out string? error) { code = SimpleTypeConverter.ParseInt32(StringValue, int.MinValue, int.MaxValue, out error); - if (!(error is null)) + if (error is not null) code = (int)SimpleTypeConverter.ParseUInt32(StringValue, uint.MinValue, uint.MaxValue, out error); return error is null; } @@ -128,7 +128,7 @@ public string DescriptionText { } string descriptionText = string.Empty; - bool IsExceptionCode => !(selectedCategory is null) && (selectedCategory.Definition.Flags & DbgExceptionCategoryDefinitionFlags.Code) != 0; + bool IsExceptionCode => selectedCategory is not null && (selectedCategory.Definition.Flags & DbgExceptionCategoryDefinitionFlags.Code) != 0; public bool HasDescriptionText => IsExceptionCode; sealed class ExceptionCategoryVM : ViewModelBase { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/Commands.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/Commands.cs index d8f57f9d20..34644bbec4 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/Commands.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/Commands.cs @@ -196,7 +196,7 @@ public override void Execute(IMenuItemContext context) { } IEnumerable IMenuItemProvider.Create(IMenuItemContext context) { var ctx = ExceptionsContextMenuEntry.CreateContext(exceptionsCommandContext, context); - Debug2.Assert(!(ctx is null)); + Debug2.Assert(ctx is not null); if (ctx is null) yield break; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/ExceptionsVM.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/ExceptionsVM.cs index 773f59e949..13acde9152 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/ExceptionsVM.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Exceptions/ExceptionsVM.cs @@ -499,7 +499,7 @@ IEnumerable GetFilteredItems_UI(ExceptionCategoryVM selectedC exceptionContext.UIDispatcher.VerifyAccess(); var category = selectedCategory?.Definition?.Name; foreach (var item in realAllItems) { - if (!(category is null) && item.Definition.Id.Category != category) + if (category is not null && item.Definition.Id.Category != category) continue; var vmc = CreateCached_UI(item); if (IsMatch_UI(vmc, filterText, showOnlyEnabledExceptions)) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/FormatterUtils.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/FormatterUtils.cs index 62986e060b..a7b20bc786 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/FormatterUtils.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/FormatterUtils.cs @@ -84,7 +84,7 @@ public static T Write(this T output, DbgProcess process, bool useHex) where T } public static T WriteYesNoOrNA(this T output, bool? value) where T : IDbgTextWriter { - if (!(value is null)) + if (value is not null) output.WriteYesNo(value.Value); else output.Write(DbgTextColor.Text, "N/A"); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/LazyToolWindowVMHelper.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/LazyToolWindowVMHelper.cs index 6c53d22de7..3e8238e002 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/LazyToolWindowVMHelper.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/LazyToolWindowVMHelper.cs @@ -101,7 +101,7 @@ void StartTimer() { } void StopTimer() { - if (!(timer is null)) { + if (timer is not null) { timer.Tick -= Timer_Tick_UI; timer.Stop(); timer = null; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Logger/OutputLogger.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Logger/OutputLogger.cs index 649703c338..062634d486 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Logger/OutputLogger.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Logger/OutputLogger.cs @@ -71,7 +71,7 @@ sealed class OutputLogger : IOutputServiceListener2, IDbgManagerStartListener, I void Initialize() => UI(() => Initialize_UI()); void Initialize_UI() { uiDispatcher.VerifyAccess(); - if (!(textPane is null)) + if (textPane is not null) return; textPane = outputService.Value.Create(GUID_OUTPUT_LOGGER_DEBUG, dnSpy_Debugger_Resources.DebugLoggerName, contentTypeRegistryService.Value.GetContentType(ContentTypes.OutputDebug)); } @@ -101,7 +101,7 @@ void DbgManager_IsDebuggingChanged(object? sender, EventArgs e) { if (dbgManager.IsDebugging) { UI(() => { Initialize_UI(); - Debug2.Assert(!(textPane is null)); + Debug2.Assert(textPane is not null); if (outputLoggerSettings.ShowDebugOutputLog) outputService.Value.Select(GUID_OUTPUT_LOGGER_DEBUG); textPane.Clear(); @@ -113,7 +113,7 @@ void WriteLine_UI(object color, string text) { uiDispatcher.VerifyAccess(); if (textPane is null) Initialize_UI(); - Debug2.Assert(!(textPane is null)); + Debug2.Assert(textPane is not null); textPane.WriteLine(color, text); } @@ -121,7 +121,7 @@ void Write_UI(object color, string text) { uiDispatcher.VerifyAccess(); if (textPane is null) Initialize_UI(); - Debug2.Assert(!(textPane is null)); + Debug2.Assert(textPane is not null); textPane.Write(color, text); } @@ -169,7 +169,7 @@ void DbgManager_MessageExceptionThrown(object? sender, DbgMessageExceptionThrown var msg2 = ex.Message is null ? null : string.Format(dnSpy_Debugger_Resources.DebugLogAdditionalInformation, ex.Message); UI(() => { WriteLine_UI(BoxedTextColor.DebugLogMDA, msg1); - if (!(msg2 is null)) + if (msg2 is not null) WriteLine_UI(BoxedTextColor.DebugLogMDA, msg2); }); } @@ -181,7 +181,7 @@ void DbgManager_MessageExceptionThrown(object? sender, DbgMessageExceptionThrown var msg2 = ex.Message is null ? null : string.Format(dnSpy_Debugger_Resources.DebugLogAdditionalInformation, FilterUserMessage(ex.Message)); UI(() => { WriteLine_UI(BoxedTextColor.DebugLogExceptionHandled, msg1); - if (!(msg2 is null)) + if (msg2 is not null) WriteLine_UI(BoxedTextColor.DebugLogExceptionHandled, msg2); }); } @@ -190,7 +190,7 @@ void DbgManager_MessageExceptionThrown(object? sender, DbgMessageExceptionThrown var msg2 = ex.Message is null ? null : string.Format(dnSpy_Debugger_Resources.DebugLogAdditionalInformation, FilterUserMessage(ex.Message)); UI(() => { WriteLine_UI(BoxedTextColor.DebugLogExceptionUnhandled, msg1); - if (!(msg2 is null)) + if (msg2 is not null) WriteLine_UI(BoxedTextColor.DebugLogExceptionUnhandled, msg2); }); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/BufferFileCreator.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/BufferFileCreator.cs index 1ea3822bfa..ea074b737d 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/BufferFileCreator.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/BufferFileCreator.cs @@ -91,7 +91,7 @@ void OnProcessChanged_UI(DbgProcess? newProcess) { Debug.Assert(!hexBufferFileService.Files.Any()); return; } - if (!(process is null)) + if (process is not null) process.RuntimesChanged -= Process_RuntimesChanged; foreach (var r in runtimes) r.ModulesChanged -= DbgRuntime_ModulesChanged; @@ -101,7 +101,7 @@ void OnProcessChanged_UI(DbgProcess? newProcess) { addedModules.Clear(); process = newProcess; - if (!(newProcess is null)) + if (newProcess is not null) newProcess.DbgManager.Dispatcher.BeginInvoke(() => OnNewProcess_DbgThread(newProcess)); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/Commands.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/Commands.cs index 4ae91ac20c..b808855b2b 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/Commands.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/Commands.cs @@ -77,7 +77,7 @@ public override void Execute(IMenuItemContext context) { } IEnumerable IMenuItemProvider.Create(IMenuItemContext context) { var ctx = ProcessesContextMenuEntry.CreateContext(processHexBufferProvider, context); - Debug2.Assert(!(ctx is null)); + Debug2.Assert(ctx is not null); if (ctx is null) yield break; @@ -94,7 +94,7 @@ IEnumerable IMenuItemProvider.Create(IMenuItemContext context) string GetProcessHeader(Process? process, int pid) { try { - if (!(process is null)) { + if (process is not null) { var title = Filter(process.MainWindowTitle, 200); var name = GetProcessName(process); if (string.IsNullOrWhiteSpace(title)) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/DebuggerHexBufferStream.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/DebuggerHexBufferStream.cs index 3d44a5cd0b..61bfb9428e 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/DebuggerHexBufferStream.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/DebuggerHexBufferStream.cs @@ -223,7 +223,7 @@ public override double ReadDoubleBigEndian(HexPosition position) { public override byte[] ReadBytes(HexPosition position, long length) { CheckDisposed(); var streamLocal = stream; - if (!(streamLocal is null)) + if (streamLocal is not null) return streamLocal.ReadBytes(position, length); return new byte[length]; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/MemoryWindowService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/MemoryWindowService.cs index 1a89bfd3ea..041c919047 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/MemoryWindowService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/MemoryWindowService.cs @@ -54,7 +54,7 @@ public override void Show(int pid, HexSpan span) { public override void Show(int pid, HexSpan span, int windowIndex) { var mc = GetMemoryToolWindowContent(windowIndex); - Debug2.Assert(!(mc is null)); + Debug2.Assert(mc is not null); if (mc is null) return; ShowInMemoryWindow(pid, mc, span); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/ProcessHexBufferProvider.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/ProcessHexBufferProvider.cs index a5fa81a3d4..2112e3c113 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/ProcessHexBufferProvider.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Memory/ProcessHexBufferProvider.cs @@ -209,7 +209,7 @@ void InitializeProcesses_DbgManager_UI(IList processes, bool added) else { foreach (var p in processes) { var info = TryGetProcessInfo_UI(p.Id); - Debug2.Assert(!(info is null)); + Debug2.Assert(info is not null); if (info is null) continue; ClearProcessStream_UI(info); @@ -311,7 +311,7 @@ void Buffer_Disposed(object? sender, EventArgs e) { // UI thread public override bool IsValidBuffer(HexBuffer buffer) { uiDispatcher.VerifyAccess(); - return !(TryGetBufferState_UI(buffer) is null); + return TryGetBufferState_UI(buffer) is not null; } // UI thread diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/ModuleBreakpoints/ModuleBreakpointsOperations.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/ModuleBreakpoints/ModuleBreakpointsOperations.cs index e14d5ea96c..6be8c52b76 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/ModuleBreakpoints/ModuleBreakpointsOperations.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/ModuleBreakpoints/ModuleBreakpointsOperations.cs @@ -288,7 +288,7 @@ public override void ImportBreakpoints() { var filename = pickFilename.GetFilename(null, "xml", PickFilenameConstants.XmlFilenameFilter); if (!File.Exists(filename)) return; - Debug2.Assert(!(filename is null)); + Debug2.Assert(filename is not null); var settingsService = settingsServiceFactory.Value.Create(); try { settingsService.Open(filename); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/Commands.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/Commands.cs index beb39dc827..f6a40ac128 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/Commands.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/Commands.cs @@ -186,7 +186,7 @@ public override void Execute(ModulesCtxMenuContext context) { } IEnumerable IMenuItemProvider.Create(IMenuItemContext context) { var ctx = CreateContext(context); - Debug2.Assert(!(ctx is null)); + Debug2.Assert(ctx is not null); if (ctx is null) yield break; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModuleFormatter.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModuleFormatter.cs index c2f7f96e8e..1d91d7b589 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModuleFormatter.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModuleFormatter.cs @@ -63,7 +63,7 @@ void WriteFilename(IDbgTextWriter output, DbgModule module, string filename) { public void WriteVersion(IDbgTextWriter output, DbgModule module) { var versionString = module.Version; - if (!(versionString is null)) { + if (versionString is not null) { const int MAX_VER_LEN = 100; if (versionString.Length <= MAX_VER_LEN) output.Write(DbgTextColor.Text, versionString); @@ -74,7 +74,7 @@ public void WriteVersion(IDbgTextWriter output, DbgModule module) { public void WriteTimestamp(IDbgTextWriter output, DbgModule module) { var date = module.Timestamp; - if (!(date is null)) { + if (date is not null) { var dateString = date.Value.ToLocalTime().ToString(CultureInfo.CurrentUICulture.DateTimeFormat); output.Write(DbgTextColor.Text, dateString); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesOperations.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesOperations.cs index 567dc7e660..62847dbe57 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesOperations.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesOperations.cs @@ -203,7 +203,7 @@ public override void LoadAllModules() { void LoadModules(IList modules) => moduleLoader.Value.LoadModules(modules.Select(a => a.Module).ToArray(), DbgLoadModuleReferenceHandlerOptions.None); - public override bool CanShowInMemoryWindow => !(GetShowInMemoryWindowModule() is null); + public override bool CanShowInMemoryWindow => GetShowInMemoryWindowModule() is not null; public override void ShowInMemoryWindow(int windowIndex) { if ((uint)windowIndex >= (uint)MemoryWindowsHelper.NUMBER_OF_MEMORY_WINDOWS) throw new ArgumentOutOfRangeException(nameof(windowIndex)); @@ -220,12 +220,12 @@ public override void ShowInMemoryWindow(int windowIndex) { public override void ShowInMemoryWindow() => ShowInMemoryWindowCore(null); void ShowInMemoryWindowCore(int? windowIndex) { var vm = GetShowInMemoryWindowModule(); - if (!(vm is null)) { + if (vm is not null) { var start = new HexPosition(vm.Module.Address); var end = start + vm.Module.Size; Debug.Assert(end <= HexPosition.MaxEndPosition); if (end <= HexPosition.MaxEndPosition) { - if (!(windowIndex is null)) + if (windowIndex is not null) memoryWindowService.Value.Show(vm.Module.Process.Id, HexSpan.FromBounds(start, end), windowIndex.Value); else memoryWindowService.Value.Show(vm.Module.Process.Id, HexSpan.FromBounds(start, end)); @@ -240,7 +240,7 @@ public override bool UseHexadecimal { set => debuggerSettings.UseHexadecimal = value; } - public override bool CanOpenContainingFolder => !(GetFilename() is null); + public override bool CanOpenContainingFolder => GetFilename() is not null; public override void OpenContainingFolder() { var filename = GetFilename(); if (filename is null) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesSaver.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesSaver.cs index 8058596480..79eaddb187 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesSaver.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesSaver.cs @@ -60,7 +60,7 @@ public void Save(ModuleVM[] modules) { var dir = new PickDirectory().GetDirectory(null); if (!Directory.Exists(dir)) return; - Debug2.Assert(!(dir is null)); + Debug2.Assert(dir is not null); for (int i = 0; i < modules.Length; i++) { var file = modules[i]; var filename = file.Module.Name; @@ -89,7 +89,7 @@ bool ShowDialog((DbgModule module, string filename)[] list, [NotNullWhen(false)] return true; if (!data.WasError) return true; - Debug2.Assert(!(data.ErrorMessage is null)); + Debug2.Assert(data.ErrorMessage is not null); error = data.ErrorMessage; return false; } @@ -103,7 +103,7 @@ bool ShowDialog((DbgModule module, string filename)[] list, [NotNullWhen(false)] static string GetDefaultExtension(string? name, bool isExe) { try { var ext = Path.GetExtension(name); - if (!(ext is null) && ext.Length > 0 && ext[0] == '.') + if (ext is not null && ext.Length > 0 && ext[0] == '.') return ext.Substring(1); } catch { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesVM.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesVM.cs index 9f4a4ec987..db053276e2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesVM.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Modules/ModulesVM.cs @@ -505,7 +505,7 @@ IEnumerable IModulesVM.Sort(IEnumerable modules) { void InitializeNothingMatched() => InitializeNothingMatched(filterText, selectedProcess); void InitializeNothingMatched(string filterText, SimpleProcessVM? selectedProcess) => - NothingMatched = AllItems.Count == 0 && !(string.IsNullOrWhiteSpace(filterText) && selectedProcess?.Process is null); + NothingMatched = AllItems.Count == 0 && string.IsNullOrWhiteSpace(filterText) && selectedProcess?.Process is not null; public int Compare([AllowNull] ModuleVM x, [AllowNull] ModuleVM y) { Debug.Assert(moduleContext.UIDispatcher.CheckAccess()); @@ -606,7 +606,7 @@ IEnumerable GetFilteredItems_UI(string filterText, SimpleProcessVM? se // UI thread bool IsMatch_UI(ModuleVM vm, string filterText, SimpleProcessVM? selectedProcess) { Debug.Assert(moduleContext.UIDispatcher.CheckAccess()); - if (!(selectedProcess?.Process is null) && selectedProcess.Process != vm.Module.Process) + if (selectedProcess?.Process is not null && selectedProcess.Process != vm.Module.Process) return false; // Common case check, we don't need to allocate any strings if (filterText == string.Empty) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Processes/ProcessesOperations.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Processes/ProcessesOperations.cs index 03c8da7f41..1003920bdc 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Processes/ProcessesOperations.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Processes/ProcessesOperations.cs @@ -234,7 +234,7 @@ public override void SetCurrentProcess(bool newTab) { process.DbgManager.Dispatcher.BeginInvoke(() => { if (process.DbgManager.CurrentProcess.Current == process) { var thread = process.DbgManager.CurrentThread.Current; - if (!(thread is null)) + if (thread is not null) uiDispatcher.UI(() => GoToThread(thread, newTab: newTab)); } }); @@ -243,7 +243,7 @@ public override void SetCurrentProcess(bool newTab) { void GoToThread(DbgThread thread, bool newTab) { var info = Threads.ThreadUtilities.GetFirstFrameLocation(thread); - if (!(info.location is null)) { + if (info.location is not null) { try { var options = newTab ? new object[] { PredefinedReferenceNavigatorOptions.NewTab } : Array.Empty(); referenceNavigatorService.Value.GoTo(info.location, options); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/SimpleProcessVM.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/SimpleProcessVM.cs index bd55201032..e36bcf0d4b 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/SimpleProcessVM.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/SimpleProcessVM.cs @@ -33,7 +33,7 @@ public SimpleProcessVM(DbgProcess process, bool useHex) { static string GetProcessName(DbgProcess process, bool useHex) => "[" + (useHex ? "0x" + process.Id.ToString("X") : process.Id.ToString()) + "]" + (string.IsNullOrEmpty(process.Name) ? string.Empty : " " + process.Name); public void UpdateName(bool useHex) { - if (!(Process is null)) { + if (Process is not null) { var newName = GetProcessName(Process, useHex); if (Name != newName) { Name = newName; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadCategoryService.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadCategoryService.cs index f8c5785d96..299a713f43 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadCategoryService.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadCategoryService.cs @@ -49,7 +49,7 @@ sealed class ThreadCategoryServiceImpl : ThreadCategoryService { public override CategoryInfo GetInfo(string kind) { foreach (var lz in threadCategoryProviders) { var info = lz.Value.GetCategory(kind); - if (!(info is null)) { + if (info is not null) { var imgRef = info.Value.Image as ImageReference? ?? ImageReference.None; return new CategoryInfo(imgRef, info.Value.Category); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadFormatter.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadFormatter.cs index ce50ec1aca..70ab053d03 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadFormatter.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadFormatter.cs @@ -66,7 +66,7 @@ public void WriteImage(IDbgTextWriter output, ThreadVM vm) { public void WriteManagedId(IDbgTextWriter output, DbgThread thread) { var managedId = thread.ManagedId; - if (!(managedId is null)) + if (managedId is not null) WriteUInt64(output, managedId.Value); } @@ -130,7 +130,7 @@ public void WriteAffinityMask(IDbgTextWriter output, ThreadVM vm) { public void WriteAppDomain(IDbgTextWriter output, DbgThread thread) { var appDomain = thread.AppDomain; - if (!(appDomain is null)) + if (appDomain is not null) output.Write(appDomain); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadUtilities.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadUtilities.cs index a27b88c45e..3bca9190e7 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadUtilities.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadUtilities.cs @@ -45,7 +45,7 @@ public static (DbgCodeLocation? location, int frameIndex) GetFirstFrameLocation( break; foreach (var frame in frames) { var location = frame.Location; - if (!(location is null)) + if (location is not null) return (location.Clone(), frameIndex); frameIndex++; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadVM.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadVM.cs index 30677151d1..b0ffbcea3f 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadVM.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadVM.cs @@ -168,7 +168,7 @@ public ThreadVM(DbgLanguageService dbgLanguageService, DbgThread thread, IThread // UI thread ThreadPriority CalculateThreadPriority_UI() { Context.UIDispatcher.VerifyAccess(); - Debug2.Assert(!(hThread is null)); + Debug2.Assert(hThread is not null); if (hThread is null || hThread.IsInvalid) return ThreadPriority.Normal; return (ThreadPriority)NativeMethods.GetThreadPriority(hThread.DangerousGetHandle()); @@ -177,7 +177,7 @@ ThreadPriority CalculateThreadPriority_UI() { // UI thread ulong CalculateAffinityMask_UI() { Context.UIDispatcher.VerifyAccess(); - Debug2.Assert(!(hThread is null)); + Debug2.Assert(hThread is not null); if (hThread is null || hThread.IsInvalid) return 0; var affinityMask = NativeMethods.SetThreadAffinityMask(hThread.DangerousGetHandle(), new IntPtr(-1)); @@ -323,7 +323,7 @@ void CloseThreadHandle_UI() { // UI thread void OpenThread_UI() { Context.UIDispatcher.VerifyAccess(); - if (!(hThread is null)) + if (hThread is not null) return; const int dwDesiredAccess = NativeMethods.THREAD_QUERY_INFORMATION | NativeMethods.THREAD_SET_INFORMATION; hThread = NativeMethods.OpenThread(dwDesiredAccess, false, (uint)Thread.Id); @@ -360,7 +360,7 @@ ClassifiedTextCollection CreateLocationCachedOutput() { } } finally { - if (!(frames is null) && frames.Length != 0) { + if (frames is not null && frames.Length != 0) { Debug.Assert(frames.Length == 1); Thread.Process.DbgManager.Close(new DbgObject[] { stackWalker!, frames[0] }); } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadsOperations.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadsOperations.cs index 256ca07b76..8ad723a7e2 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadsOperations.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadsOperations.cs @@ -172,7 +172,7 @@ public override void SwitchToThread(bool newTab) { var thread = SelectedItems[0].Thread; thread.Process.DbgManager.CurrentThread.Current = thread; var info = ThreadUtilities.GetFirstFrameLocation(thread); - if (!(info.location is null)) { + if (info.location is not null) { try { var options = newTab ? new object[] { PredefinedReferenceNavigatorOptions.NewTab } : Array.Empty(); referenceNavigatorService.Value.GoTo(info.location, options); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadsVM.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadsVM.cs index 29dcf2e887..d1172efefb 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadsVM.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Threads/ThreadsVM.cs @@ -604,7 +604,7 @@ IEnumerable IThreadsVM.Sort(IEnumerable threads) { void InitializeNothingMatched() => InitializeNothingMatched(filterText, selectedProcess); void InitializeNothingMatched(string filterText, SimpleProcessVM? selectedProcess) => - NothingMatched = AllItems.Count == 0 && !(string.IsNullOrWhiteSpace(filterText) && selectedProcess?.Process is null); + NothingMatched = AllItems.Count == 0 && string.IsNullOrWhiteSpace(filterText) && selectedProcess?.Process is not null; public int Compare([AllowNull] ThreadVM x, [AllowNull] ThreadVM y) { Debug.Assert(threadContext.UIDispatcher.CheckAccess()); @@ -703,7 +703,7 @@ IEnumerable GetFilteredItems_UI(string filterText, SimpleProcessVM? se // UI thread bool IsMatch_UI(ThreadVM vm, string filterText, SimpleProcessVM? selectedProcess) { Debug.Assert(threadContext.UIDispatcher.CheckAccess()); - if (!(selectedProcess?.Process is null) && selectedProcess.Process != vm.Thread.Process) + if (selectedProcess?.Process is not null && selectedProcess.Process != vm.Thread.Process) return false; // Common case check, we don't need to allocate any strings if (filterText == string.Empty) diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchContentFactory.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchContentFactory.cs index e70d22d940..39c0592df1 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchContentFactory.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchContentFactory.cs @@ -45,7 +45,7 @@ sealed class WatchContentFactoryImpl : WatchContentFactory { public override bool TryGetContent(int index, out WatchContent watchContent) { watchContent = contents[index]; - return !(watchContent is null); + return watchContent is not null; } public override WatchContent GetContent(int index) { diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchVariablesWindowValueNodesProvider.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchVariablesWindowValueNodesProvider.cs index dbbb3ee2ec..abeaaa96e6 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchVariablesWindowValueNodesProvider.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchVariablesWindowValueNodesProvider.cs @@ -165,7 +165,7 @@ public override void DeleteExpressions(string[] ids) { // IDs are also sortable foreach (var id in ids.OrderByDescending(a => a, StringComparer.Ordinal)) { var (index, info) = FindPrevExpression(lastIndex, id); - Debug2.Assert(!(info is null)); + Debug2.Assert(info is not null); Debug2.Assert((index < 0) == (info is null)); if (index < 0) continue; diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchWindowExpressionsSettings.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchWindowExpressionsSettings.cs index bdadfe7e2c..6f15e12d30 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchWindowExpressionsSettings.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WatchWindowExpressionsSettings.cs @@ -87,7 +87,7 @@ public override void SetExpressions(int windowIndex, string[] expressions) { } void Save(WatchInfo info) { - if (!(info.Section is null)) + if (info.Section is not null) watchSection.RemoveSection(info.Section); var sect = info.Section = watchSection.CreateSection("Watch"); sect.Attribute("Index", info.WindowIndex); diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WpfMemLeakWorkaround.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WpfMemLeakWorkaround.cs index a5bb51ddde..1ad7d9e4f4 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WpfMemLeakWorkaround.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/ToolWindows/Watch/WpfMemLeakWorkaround.cs @@ -48,7 +48,7 @@ void MemLeakFix() { for (int i = 0; i < WatchWindowsHelper.NUMBER_OF_WATCH_WINDOWS; i++) { if (watchContentFactory.TryGetContent(i, out var watchContent)) { var listView = watchContent.VariablesWindowControl.ListView; - if (!(listView is null)) + if (listView is not null) AutomationPeerMemoryLeakWorkaround.ClearAll(listView); } } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/UI/Wpf/SmartTextBlock.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/UI/Wpf/SmartTextBlock.cs index caed969063..6e97c09aeb 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/UI/Wpf/SmartTextBlock.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/UI/Wpf/SmartTextBlock.cs @@ -46,7 +46,7 @@ static void ContentInfoProperty_PropertyChangedCallback(DependencyObject d, Depe } } var newContent = newValue?.TextElementFactory.Create(newValue.ClassificationFormatMap, newValue.Text, newValue.Tags, newValue.TextElementFlags); - if (!(newContent is null) && newValue!.Opacity != 1.0) + if (newContent is not null && newValue!.Opacity != 1.0) newContent.Opacity = newValue.Opacity; tb.Content = newContent; } diff --git a/Extensions/dnSpy.Debugger/dnSpy.Debugger/UI/Wpf/TextBlockContentInfo.cs b/Extensions/dnSpy.Debugger/dnSpy.Debugger/UI/Wpf/TextBlockContentInfo.cs index e9cf2db42a..d9bba21ce8 100644 --- a/Extensions/dnSpy.Debugger/dnSpy.Debugger/UI/Wpf/TextBlockContentInfo.cs +++ b/Extensions/dnSpy.Debugger/dnSpy.Debugger/UI/Wpf/TextBlockContentInfo.cs @@ -72,7 +72,7 @@ public TextBlockContentInfo(ITextElementFactory textElementFactory, int version, } public bool Equals(TextBlockContentInfo? other) => - !(other is null) && + other is not null && TextElementFactory == other.TextElementFactory && Version == other.Version && ClassificationFormatMap == other.ClassificationFormatMap && diff --git a/Extensions/dnSpy.Scripting.Roslyn/Common/ScriptControlVM.cs b/Extensions/dnSpy.Scripting.Roslyn/Common/ScriptControlVM.cs index 92476a077e..c7fa5310e4 100644 --- a/Extensions/dnSpy.Scripting.Roslyn/Common/ScriptControlVM.cs +++ b/Extensions/dnSpy.Scripting.Roslyn/Common/ScriptControlVM.cs @@ -88,7 +88,7 @@ abstract class ScriptControlVM : ViewModelBase, IReplCommandHandler, IScriptGlob public void Reset(bool loadConfig = true) { if (!CanReset) return; - if (!(execState is null)) { + if (execState is not null) { execState.CancellationTokenSource.Cancel(); try { execState.Globals.RaiseScriptResetting(); @@ -212,7 +212,7 @@ void Options_OptionChanged(object? sender, EditorOptionChangedEventArgs e) { } public bool IsCommand(string text) { - if (!(ParseScriptCommand(text) is null)) + if (ParseScriptCommand(text) is not null) return true; return IsCompleteSubmission(text); } @@ -255,7 +255,7 @@ IEnumerable GetDefaultScriptFilePaths() { void InitializeExecutionEngine(bool loadConfig, bool showHelp) { Debug2.Assert(execState is null); - if (!(execState is null)) + if (execState is not null) throw new InvalidOperationException(); execState = new ExecState(this, dispatcher, new CancellationTokenSource()); @@ -315,7 +315,7 @@ public void OnNewCommand() { public Task OnCommandUpdatedAsync(IReplCommandInput command, CancellationToken cancellationToken) { if (isResetting) return Task.CompletedTask; - Debug2.Assert(!(execState is null)); + Debug2.Assert(execState is not null); if (execState is null) throw new InvalidOperationException(); @@ -350,20 +350,20 @@ public Task OnCommandUpdatedAsync(IReplCommandInput command, CancellationToken c protected abstract Compilation CreateScriptCompilation(string assemblyName, SyntaxTree syntaxTree, IEnumerable? references, CompilationOptions options, Compilation previousScriptCompilation, Type returnType, Type globalsType); bool ExecuteCommandInternal(string input) { - Debug2.Assert(!(execState is null) && !execState.IsInitializing); + Debug2.Assert(execState is not null && !execState.IsInitializing); if (execState is null || execState.IsInitializing) return true; lock (lockObj) { Debug2.Assert(execState.ExecTask is null && !execState.Executing); - if (!(execState.ExecTask is null) || execState.Executing) + if (execState.ExecTask is not null || execState.Executing) return true; execState.Executing = true; } try { var scState = ParseScriptCommand(input); - if (!(scState is null)) { - if (!(execState is null)) { + if (scState is not null) { + if (execState is not null) { lock (lockObj) execState.Executing = false; } @@ -397,13 +397,13 @@ bool ExecuteCommandInternal(string input) { } if (isActive) { try { - if (!(ex is null)) + if (ex is not null) ReplEditor.OutputPrint(Format(ex.InnerException!), BoxedTextColor.Error, true); if (!t.IsCanceled && !t.IsFaulted) { oldState.ScriptState = t.Result; var val = t.Result.ReturnValue; - if (!(val is null)) + if (val is not null) ObjectOutputLine(BoxedTextColor.ReplOutputText, oldState.Globals.PrintOptionsImpl, val, true); } } @@ -414,7 +414,7 @@ bool ExecuteCommandInternal(string input) { }, CancellationToken.None, TaskContinuationOptions.None, taskSched); }) .ContinueWith(t => { - if (!(execState is null)) { + if (execState is not null) { lock (lockObj) execState.Executing = false; } @@ -427,7 +427,7 @@ bool ExecuteCommandInternal(string input) { CommandExecuted(); else { var ex = t.Exception; - if (!(ex is null)) { + if (ex is not null) { ReplEditor.OutputPrint(ex.ToString(), BoxedTextColor.Error, true); CommandExecuted(); } @@ -437,7 +437,7 @@ bool ExecuteCommandInternal(string input) { return true; } catch (Exception ex) { - if (!(execState is null)) { + if (execState is not null) { lock (lockObj) execState.Executing = false; } @@ -609,7 +609,7 @@ public void Write(string? text, object? color) { void ObjectOutput(CachedWriter writer, object? color, PrintOptionsImpl printOptions, object? value) { var writable = GetOutputWritable(printOptions, value); - if (!(writable is null)) + if (writable is not null) writable.WriteTo(writer); else writer.Write(Format(value, printOptions.RoslynPrintOptions), color); @@ -619,7 +619,7 @@ void ObjectOutput(object? color, PrintOptionsImpl printOptions, object? value, b if (color is null) return; var writable = GetOutputWritable(printOptions, value); - if (!(writable is null)) + if (writable is not null) writable.WriteTo(OutputWriter.Create(this, startOnNewLine)); else ReplEditor.OutputPrint(Format(value, printOptions.RoslynPrintOptions), color, startOnNewLine); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Compiler/FrameworkDetector.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Compiler/FrameworkDetector.cs index 135a3a8fb4..c6195d8b0d 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Compiler/FrameworkDetector.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Compiler/FrameworkDetector.cs @@ -42,7 +42,7 @@ public static FrameworkKind GetFrameworkKind(ModuleDef module) { } var info = TryGetTargetFrameworkAttribute(module.Assembly); - if (!(info.framework is null)) { + if (info.framework is not null) { if (info.framework == ".NETFramework") { if (info.version.StartsWith("2.") || info.version.StartsWith("3.")) return FrameworkKind.DotNetFramework2; diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Compiler/RoslynLanguageCompiler.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Compiler/RoslynLanguageCompiler.cs index 96af679892..e353929c30 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Compiler/RoslynLanguageCompiler.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Compiler/RoslynLanguageCompiler.cs @@ -132,7 +132,7 @@ public void InitializeProject(CompilerProjectInfo projectInfo) { var compilationOptions = CreateCompilationOptions(GetDefaultOutputKind(kind)) .WithPlatform(GetPlatform(projectInfo.Platform)) .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); - if (!(projectInfo.PublicKey is null)) { + if (projectInfo.PublicKey is not null) { compilationOptions = compilationOptions .WithCryptoPublicKey(ImmutableArray.Create(projectInfo.PublicKey)) .WithDelaySign(true); @@ -205,7 +205,7 @@ RoslynCodeDocument CreateDocument(ProjectId projectId, CompilerDocumentInfo doc) } public ICodeDocument[] AddDocuments(CompilerDocumentInfo[] documents) { - Debug2.Assert(!(workspace is null)); + Debug2.Assert(workspace is not null); var newDocuments = new List(); foreach (var doc in documents) @@ -227,7 +227,7 @@ public ICodeDocument[] AddDocuments(CompilerDocumentInfo[] documents) { } public async Task CompileAsync(CancellationToken cancellationToken) { - Debug2.Assert(!(workspace is null)); + Debug2.Assert(workspace is not null); var project = workspace.CurrentSolution.Projects.First(); Debug.Assert(project.SupportsCompilation); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); @@ -268,7 +268,7 @@ CompilationResult Compile(Compilation compilation, CancellationToken cancellatio protected abstract string GetHelpUri(Diagnostic diagnostic); public bool AddMetadataReferences(CompilerMetadataReference[] metadataReferences) { - Debug2.Assert(!(workspace is null)); + Debug2.Assert(workspace is not null); if (workspace is null) throw new InvalidOperationException(); var newProj = workspace.CurrentSolution.Projects.First().AddMetadataReferences(metadataReferences.Select(a => a.CreateMetadataReference(docFactory))); @@ -279,7 +279,7 @@ public void Dispose() { if (isDisposed) return; isDisposed = true; - if (!(workspace is null)) { + if (workspace is not null) { workspace.WorkspaceChanged -= Workspace_WorkspaceChanged; // This also closes all documents workspace.Dispose(); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/AliasConstants.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/AliasConstants.cs index 1a807e521f..b4cba99514 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/AliasConstants.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/AliasConstants.cs @@ -30,7 +30,7 @@ static class AliasConstants { public const string ObjectIdName = "$"; public static bool TryGetAliasInfo(string aliasName, bool isCaseSensitive, out DbgDotNetParsedAlias aliasInfo) { - if (!(aliasName is null)) { + if (aliasName is not null) { var comparison = isCaseSensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; if (aliasName.Equals(ReturnValueName, comparison)) { aliasInfo = new DbgDotNetParsedAlias(DbgDotNetAliasKind.ReturnValue, DbgDotNetRuntimeConstants.LastReturnValueId); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/CSharp/CSharpExpressionCompiler.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/CSharp/CSharpExpressionCompiler.cs index 6bbe948d12..c64f1bebfa 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/CSharp/CSharpExpressionCompiler.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/CSharp/CSharpExpressionCompiler.cs @@ -47,7 +47,7 @@ protected override ImmutableArray> GetImports(T var importRecordGroupBuilder = ImmutableArray.CreateBuilder>(); var type = declaringType; - while (!(type.DeclaringType is null)) + while (type.DeclaringType is not null) type = type.DeclaringType; var ns = UTF8String.ToSystemStringOrEmpty(type.Namespace); int index = 0; @@ -114,7 +114,7 @@ DbgDotNetCompilationResult CompileExpressionCore(DbgDotNetAlias[] aliases, strin DbgDotNetText name; if ((options & DbgEvaluationOptions.NoName) != 0) name = DbgDotNetText.Empty; - else if (!(errorMessage is null)) + else if (errorMessage is not null) name = CreateErrorName(expression); else name = GetExpressionText(state.MetadataContext.EvaluationContext, state.MetadataContext.Compilation, expression, cancellationToken); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/LanguageExpressionCompiler.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/LanguageExpressionCompiler.cs index 3cc03e6d6b..c0cce5a027 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/LanguageExpressionCompiler.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/LanguageExpressionCompiler.cs @@ -380,15 +380,15 @@ protected ImmutableArray CreateAliases(DbgDotNetAlias[] aliases) { } protected DbgDotNetCompilationResult CreateCompilationResult(string expression, CompileResult compileResult, ResultProperties resultProperties, string? errorMessage, DbgDotNetText name) { - if (!(errorMessage is null)) + if (errorMessage is not null) return new DbgDotNetCompilationResult(errorMessage); - Debug2.Assert(!(compileResult is null)); + Debug2.Assert(compileResult is not null); if (compileResult is null) return new DbgDotNetCompilationResult(PredefinedEvaluationErrorMessages.InternalDebuggerError); var customTypeInfoGuid = compileResult.GetCustomTypeInfo(out var payload); DbgDotNetCustomTypeInfo? customTypeInfo; - if (!(payload is null)) + if (payload is not null) customTypeInfo = new DbgDotNetCustomTypeInfo(customTypeInfoGuid, payload); else customTypeInfo = null; @@ -415,7 +415,7 @@ static DbgEvaluationResultFlags ToEvaluationResultFlags(DkmClrCompilationResultF protected DbgDotNetCompilationResult CreateCompilationResult(EvalContextState state, byte[] assembly, string typeName, DSEELocalAndMethod[] infos, string? errorMessage) { Debug2.Assert(errorMessage is null || (assembly is null || assembly.Length == 0)); - if (!(errorMessage is null)) + if (errorMessage is not null) return new DbgDotNetCompilationResult(errorMessage); if (assembly is null || assembly.Length == 0) return new DbgDotNetCompilationResult(Array.Empty(), Array.Empty()); @@ -488,13 +488,13 @@ protected DbgDotNetCompilationResult CreateCompilationResult(EvalContextState st flags |= DbgEvaluationResultFlags.BooleanExpression; DbgDotNetCustomTypeInfo? customTypeInfo; - if (!(info.CustomTypeInfo is null)) + if (info.CustomTypeInfo is not null) customTypeInfo = new DbgDotNetCustomTypeInfo(info.CustomTypeInfoId, info.CustomTypeInfo); else customTypeInfo = null; var resultFlags = DbgDotNetCompiledExpressionResultFlags.None; - Debug2.Assert(!(state.NotCompilerGenerated is null)); + Debug2.Assert(state.NotCompilerGenerated is not null); if (info.Kind == LocalAndMethodKind.Local && (uint)info.Index < (uint)state.NotCompilerGenerated.Length && !state.NotCompilerGenerated[info.Index]) resultFlags |= DbgDotNetCompiledExpressionResultFlags.CompilerGenerated; compiledExpressions[w++] = DbgDotNetCompiledExpressionResult.Create(typeName, info.MethodName, info.LocalName, displayName, flags, imageName, customTypeInfo, null, resultFlags, info.Index); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/VisualBasic/VisualBasicExpressionCompiler.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/VisualBasic/VisualBasicExpressionCompiler.cs index 457aa2ee1e..c04de56f80 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/VisualBasic/VisualBasicExpressionCompiler.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ExpressionCompiler/VisualBasic/VisualBasicExpressionCompiler.cs @@ -101,7 +101,7 @@ DbgDotNetCompilationResult CompileExpressionCore(DbgDotNetAlias[] aliases, strin DbgDotNetText name; if ((options & DbgEvaluationOptions.NoName) != 0) name = DbgDotNetText.Empty; - else if (!(errorMessage is null)) + else if (errorMessage is not null) name = CreateErrorName(expression); else name = GetExpressionText(state.MetadataContext.EvaluationContext, state.MetadataContext.Compilation, expression, cancellationToken); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/FilterExpressionEvaluator/DbgFilterExpressionEvaluatorImpl.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/FilterExpressionEvaluator/DbgFilterExpressionEvaluatorImpl.cs index 95b4e209cc..3569c5e1ff 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/FilterExpressionEvaluator/DbgFilterExpressionEvaluatorImpl.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/FilterExpressionEvaluator/DbgFilterExpressionEvaluatorImpl.cs @@ -103,9 +103,9 @@ public override DbgFilterExpressionEvaluatorResult Evaluate(string expr, DbgFilt if (variableProvider is null) throw new ArgumentNullException(nameof(variableProvider)); var compiledExpr = GetOrCompile(expr); - if (!(compiledExpr.CompilationError is null)) + if (compiledExpr.CompilationError is not null) return new DbgFilterExpressionEvaluatorResult(compiledExpr.CompilationError); - if (!(compiledExpr.RuntimeError is null)) + if (compiledExpr.RuntimeError is not null) return new DbgFilterExpressionEvaluatorResult(compiledExpr.RuntimeError); bool evalResult; @@ -163,13 +163,13 @@ CompiledExpr GetOrCompile(string expr) { CompiledExpr CreateCompiledExpr(string expr) { var compRes = Compile(expr); - if (!(compRes.error is null)) + if (compRes.error is not null) return new CompiledExpr(compRes.error); try { using (var delCreator = new EvalDelegateCreator(compRes.assembly!, FilterExpressionClassName, EvalMethodName)) { var del = delCreator.CreateDelegate(); - if (!(del is null)) + if (del is not null) return new CompiledExpr(del); } } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/FilterExpressionEvaluator/EvalDelegateCreator.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/FilterExpressionEvaluator/EvalDelegateCreator.cs index 92d43fc64a..2e83a51909 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/FilterExpressionEvaluator/EvalDelegateCreator.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/FilterExpressionEvaluator/EvalDelegateCreator.cs @@ -45,15 +45,15 @@ static EvalDelegateCreator() { switch (value >> 8) { case 0: opCode = OpCodes.OneByteOpCodes[value & 0xFF]; - Debug2.Assert(!(opCode is null)); - if (!(opCode is null)) + Debug2.Assert(opCode is not null); + if (opCode is not null) toReflectionOpCode[opCode] = sreOpCode; break; case 0xFE: opCode = OpCodes.TwoByteOpCodes[value & 0xFF]; - Debug2.Assert(!(opCode is null)); - if (!(opCode is null)) + Debug2.Assert(opCode is not null); + if (opCode is not null) toReflectionOpCode[opCode] = sreOpCode; break; @@ -74,9 +74,9 @@ public EvalDelegateCreator(byte[] assemblyBytes, string evalClassName, string ev static readonly Type[] evalDelegateParamTypes = new Type[] { typeof(string), typeof(int), typeof(string), typeof(ulong), typeof(string) }; public EvalDelegate? CreateDelegate() { var type = module.Find(evalClassName, isReflectionName: true); - Debug2.Assert(!(type is null)); + Debug2.Assert(type is not null); var method = type?.FindMethod(evalMethodName); - Debug2.Assert(!(method?.Body is null)); + Debug2.Assert(method?.Body is not null); if (!(method?.Body is CilBody body)) return null; if (method.ReturnType.ElementType != ElementType.Boolean) @@ -268,7 +268,7 @@ static bool IsBoolean_StringString(MethodSig sig) { return false; if (sig.GenParamCount != 0) return false; - if (!(sig.ParamsAfterSentinel is null)) + if (sig.ParamsAfterSentinel is not null) return false; if (sig.Params.Count != 2) return false; diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpStackFrameFormatter.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpStackFrameFormatter.cs index 113b2afd4c..95d4872665 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpStackFrameFormatter.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpStackFrameFormatter.cs @@ -144,7 +144,7 @@ bool NeedThreadSwitch() { if (runtime.Dispatcher.CheckAccess()) return false; var sig = runtime.GetFrameMethod(evalInfo)?.GetMethodSignature(); - return !(sig is null) && (sig.GetParameterTypes().Count > 0 || sig.GetVarArgsParameterTypes().Count > 0); + return sig is not null && (sig.GetParameterTypes().Count > 0 || sig.GetVarArgsParameterTypes().Count > 0); } public void Format() { @@ -350,7 +350,7 @@ void WriteOffset() { break; } - if (!(loc is null)) { + if (loc is not null) { var addr = loc.NativeAddress; if (addr.Address != 0) { WriteCommaSpace(); @@ -450,7 +450,7 @@ void Format(DmdMethodBase method) { operatorInfo = null; else operatorInfo = Operators.TryGetOperatorInfo(method.Name); - bool isExplicitOrImplicit = !(operatorInfo is null) && (operatorInfo[0] == "explicit" || operatorInfo[0] == "implicit"); + bool isExplicitOrImplicit = operatorInfo is not null && (operatorInfo[0] == "explicit" || operatorInfo[0] == "implicit"); if (!isExplicitOrImplicit) { if (ReturnTypes && !(method is DmdConstructorInfo)) { @@ -491,7 +491,7 @@ void Format(DmdMethodBase method) { void WriteOperatorInfoString(string s) => OutputWrite(s, 'a' <= s[0] && s[0] <= 'z' ? DbgTextColor.Keyword : DbgTextColor.Operator); void WriteMethodName(DmdMethodBase method, string name, string[]? operatorInfo) { - if (!(operatorInfo is null)) { + if (operatorInfo is not null) { for (int i = 0; i < operatorInfo.Length; i++) { if (i > 0) WriteSpace(); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpTypeFormatter.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpTypeFormatter.cs index ad504ed2f8..74b45c7752 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpTypeFormatter.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpTypeFormatter.cs @@ -145,7 +145,7 @@ public void Format(DmdType type, DbgDotNetValue? value) { else { if (aryValue is null || aryValue.IsNull || !aryValue.GetArrayInfo(out elementCount, out var dimensionInfos)) dimensionInfos = null; - if (ShowArrayValueSizes && !(dimensionInfos is null) && dimensionInfos.Length == rank) { + if (ShowArrayValueSizes && dimensionInfos is not null && dimensionInfos.Length == rank) { for (int i = 0; i < rank; i++) { if (i > 0) { OutputWrite(",", DbgTextColor.Punctuation); @@ -171,7 +171,7 @@ public void Format(DmdType type, DbgDotNetValue? value) { else { Debug.Assert(aryType.IsSZArray); OutputWrite(ARRAY_OPEN_PAREN, DbgTextColor.Punctuation); - if (ShowArrayValueSizes && !(aryValue is null) && !aryValue.IsNull) { + if (ShowArrayValueSizes && aryValue is not null && !aryValue.IsNull) { if (aryValue.GetArrayCount(out elementCount)) WriteUInt32(elementCount); } @@ -211,7 +211,7 @@ public void Format(DmdType type, DbgDotNetValue? value) { int tupleIndex = 0; for (;;) { tupleType = WriteTupleFields(tupleType, ref tupleIndex); - if (!(tupleType is null)) + if (tupleType is not null) WriteCommaSpace(); else break; @@ -232,7 +232,7 @@ public void Format(DmdType type, DbgDotNetValue? value) { else { var typesList = new List(); typesList.Add(type); - while (!(type.DeclaringType is null)) { + while (type.DeclaringType is not null) { type = type.DeclaringType; typesList.Add(type); } @@ -279,7 +279,7 @@ public void Format(DmdType type, DbgDotNetValue? value) { } finally { recursionCounter--; - if (!(arrayTypesList is null)) { + if (arrayTypesList is not null) { foreach (var info in arrayTypesList) { if (info.value != value) info.value?.Dispose(); @@ -316,7 +316,7 @@ void WriteGenericArguments(DmdType type, IList genericArgs, ref int gen Format(args[i], null); //TODO: Write tuple name used in source string? fieldName = null; - if (!(fieldName is null)) { + if (fieldName is not null) { WriteSpace(); OutputWrite(fieldName, DbgTextColor.InstanceField); } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpValueFormatter.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpValueFormatter.cs index 50597f944c..a7a06c2b95 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpValueFormatter.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/CSharp/CSharpValueFormatter.cs @@ -118,10 +118,10 @@ bool TryFormatTuple(DbgDotNetValue value, int tupleArity) { DbgDotNetValue? objValue = value; DbgDotNetValueResult valueResult = default; try { - Debug2.Assert(!(info.fields is null)); + Debug2.Assert(info.fields is not null); foreach (var field in info.fields) { valueResult = runtime.LoadField(evalInfo, objValue, field); - if (!(valueResult.Value is null)) + if (valueResult.Value is not null) values.Add(valueResult.Value); if (valueResult.HasError || valueResult.ValueIsException) { objValue = null; @@ -157,10 +157,10 @@ bool TryFormatKeyValuePair(DbgDotNetValue value, (DmdFieldInfo? keyField, DmdFie DbgDotNetValueResult keyResult = default, valueResult = default; try { keyResult = runtime.LoadField(evalInfo, value, info.keyField); - if (!(keyResult.ErrorMessage is null) || keyResult.ValueIsException) + if (keyResult.ErrorMessage is not null || keyResult.ValueIsException) return false; valueResult = runtime.LoadField(evalInfo, value, info.valueField!); - if (!(valueResult.ErrorMessage is null) || valueResult.ValueIsException) + if (valueResult.ErrorMessage is not null || valueResult.ValueIsException) return false; OutputWrite(KeyValuePairTypeOpenParen, DbgTextColor.Punctuation); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/DebuggerDisplayAttributeFormatter.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/DebuggerDisplayAttributeFormatter.cs index 97cf70b43a..0433cf00b9 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/DebuggerDisplayAttributeFormatter.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/DebuggerDisplayAttributeFormatter.cs @@ -76,7 +76,7 @@ public TypeState(DbgEvaluationContext? typeContext, DisplayPart[] nameParts, Dis NameParts = nameParts ?? throw new ArgumentNullException(nameof(nameParts)); ValueParts = valueParts ?? throw new ArgumentNullException(nameof(valueParts)); TypeParts = typeParts ?? throw new ArgumentNullException(nameof(typeParts)); - if (!(typeContext is null)) { + if (typeContext is not null) { lockObj = new object(); eeStates = new Dictionary(StringComparer.Ordinal); } @@ -130,7 +130,7 @@ bool Format(DbgDotNetValue value, TypeState typeState, DisplayPart[] displayPart try { var evalInfo2 = new DbgEvaluationInfo(typeState.TypeContext!, evalInfo.Frame, evalInfo.CancellationToken); evalRes = evaluator.Evaluate(evalInfo2, value, part.Text, DbgEvaluationOptions.Expression, eeState); - if (!(evalRes.Error is null)) { + if (evalRes.Error is not null) { output.Write(DbgTextColor.Error, "<<<"); output.Write(DbgTextColor.Error, evalRes.Error); output.Write(DbgTextColor.Error, ">>>"); @@ -155,7 +155,7 @@ bool Format(DbgDotNetValue value, TypeState typeState, DisplayPart[] displayPart TypeState GetOrCreateTypeState(DmdType type, DbgLanguage language) { var state = StateWithKey.TryGet(type, language); - if (!(state is null)) + if (state is not null) return state; return GetOrCreateTypeStateCore(type, language); } @@ -193,11 +193,11 @@ static bool ShouldIgnoreDebuggerDisplayAttribute(DmdType type) { (DisplayPart[] nameParts, DisplayPart[] valueParts, DisplayPart[] typeParts) GetDisplayParts(DmdType type) { var ddaType = type.AppDomain.GetWellKnownType(DmdWellKnownType.System_Diagnostics_DebuggerDisplayAttribute, isOptional: true); - Debug2.Assert(!(ddaType is null)); + Debug2.Assert(ddaType is not null); bool forceNoAttr = ShouldIgnoreDebuggerDisplayAttribute(type); string? nameDisplayString = null, valueDisplayString = null, typeDisplayString = null; - if (!forceNoAttr && !(ddaType is null)) { + if (!forceNoAttr && ddaType is not null) { var attr = type.FindCustomAttribute(ddaType, inherit: true); if (attr is null) { if (type.CanCastTo(type.AppDomain.System_Type)) { diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/KeyValuePairTypeUtils.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/KeyValuePairTypeUtils.cs index e10d904def..007128ebd3 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/KeyValuePairTypeUtils.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/KeyValuePairTypeUtils.cs @@ -45,12 +45,12 @@ public static (DmdFieldInfo? keyField, DmdFieldInfo? valueField) TryGetFields(Dm if (field.IsStatic || field.IsLiteral) continue; if (field.Name == keyFieldName) { - if (!(keyField is null)) + if (keyField is not null) return (null, null); keyField = field; } else if (field.Name == valueFieldName) { - if (!(valueField is null)) + if (valueField is not null) return (null, null); valueField = field; } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/NullableTypeUtils.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/NullableTypeUtils.cs index 34ea2ebaff..4440de2bc6 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/NullableTypeUtils.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/NullableTypeUtils.cs @@ -35,12 +35,12 @@ public static (DmdFieldInfo? hasValueField, DmdFieldInfo? valueField) TryGetNull switch (field.Name) { case KnownMemberNames.Nullable_HasValue_FieldName: case KnownMemberNames.Nullable_HasValue_FieldName_Mono: - if (!(hasValueField is null)) + if (hasValueField is not null) return (null, null); hasValueField = field; break; case KnownMemberNames.Nullable_Value_FieldName: - if (!(valueField is null)) + if (valueField is not null) return (null, null); valueField = field; break; diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/StateMachineUtils.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/StateMachineUtils.cs index 89960aeef7..2d773a50e3 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/StateMachineUtils.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/StateMachineUtils.cs @@ -33,7 +33,7 @@ public static bool TryGetKickoffMethod(DmdMethodBase method, [NotNullWhen(true)] char c; if (!string2.IsNullOrEmpty(name) && ((c = name[0]) == '<' || (c == 'V' && name.StartsWith(StateMachineTypeNamePrefix, StringComparison.Ordinal)))) { var type = method.DeclaringType.DeclaringType; - if (!(type is null)) { + if (type is not null) { string? attrName; // These attributes could be missing from the type (eg. it's a Unity assembly) if (method.DeclaringType.CanCastTo(type.AppDomain.GetWellKnownType(DmdWellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, isOptional: true))) @@ -42,7 +42,7 @@ public static bool TryGetKickoffMethod(DmdMethodBase method, [NotNullWhen(true)] attrName = "System.Runtime.CompilerServices.IteratorStateMachineAttribute"; else attrName = null; - if (!(attrName is null)) { + if (attrName is not null) { var declTypeDef = method.DeclaringType; if (declTypeDef.IsConstructedGenericType) declTypeDef = declTypeDef.GetGenericTypeDefinition(); @@ -60,7 +60,7 @@ public static bool TryGetKickoffMethod(DmdMethodBase method, [NotNullWhen(true)] } var kickoffMethodName = type is null ? null : GetKickoffMethodName(method.DeclaringType); if (!string2.IsNullOrEmpty(kickoffMethodName)) { - Debug2.Assert(!(type is null)); + Debug2.Assert(type is not null); DmdMethodBase? possibleKickoffMethod = null; int methodGenArgs = method.ReflectedType!.GetGenericArguments().Count - type.GetGenericArguments().Count; foreach (var m in method.DeclaringType!.DeclaringType!.DeclaredMethods) { @@ -70,14 +70,14 @@ public static bool TryGetKickoffMethod(DmdMethodBase method, [NotNullWhen(true)] if (sig.GenericParameterCount != methodGenArgs) continue; - if (!(possibleKickoffMethod is null)) { + if (possibleKickoffMethod is not null) { // More than one method with the same name and partial signature possibleKickoffMethod = null; break; } possibleKickoffMethod = m; } - if (!(possibleKickoffMethod is null)) { + if (possibleKickoffMethod is not null) { CreateMethod(method, possibleKickoffMethod, out kickoffMethod); return true; } @@ -92,7 +92,7 @@ static void CreateMethod(DmdMethodBase method, DmdMethodBase newMethod, out DmdM var smGenArgs = method.ReflectedType!.GetGenericArguments(); Debug.Assert(method.GetGenericArguments().Count == 0, "Generic method args should be part of the state machine type"); createdMethod = AddTypeArguments(newMethod, smGenArgs)!; - Debug2.Assert(!(createdMethod is null)); + Debug2.Assert(createdMethod is not null); if (createdMethod is null) createdMethod = newMethod; } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/ToStringFormatter.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/ToStringFormatter.cs index 1de3bd4225..c8d24d334e 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/ToStringFormatter.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/ToStringFormatter.cs @@ -42,7 +42,7 @@ ToStringState GetToStringState(DmdType type) { ToStringState CreateToStringState(DmdType type2) { var appDomain = type2.AppDomain; var method = type2.GetMethod(nameof(object.ToString), DmdSignatureCallingConvention.Default | DmdSignatureCallingConvention.HasThis, 0, appDomain.System_String, Array.Empty(), throwOnError: false) as DmdMethodInfo; - if (!(method is null)) { + if (method is not null) { if (method.DeclaringType == appDomain.System_Object || method.DeclaringType == appDomain.System_ValueType || method.DeclaringType == appDomain.System_Enum) method = null; } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicStackFrameFormatter.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicStackFrameFormatter.cs index 5c0db717f2..9c80b8d282 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicStackFrameFormatter.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicStackFrameFormatter.cs @@ -135,7 +135,7 @@ bool NeedThreadSwitch() { if (runtime.Dispatcher.CheckAccess()) return false; var sig = runtime.GetFrameMethod(evalInfo)?.GetMethodSignature(); - return !(sig is null) && (sig.GetParameterTypes().Count > 0 || sig.GetVarArgsParameterTypes().Count > 0); + return sig is not null && (sig.GetParameterTypes().Count > 0 || sig.GetVarArgsParameterTypes().Count > 0); } public void Format() { @@ -334,7 +334,7 @@ void WriteOffset() { break; } - if (!(loc is null)) { + if (loc is not null) { var addr = loc.NativeAddress; if (addr.Address != 0) { WriteCommaSpace(); @@ -441,7 +441,7 @@ void Format(DmdMethodBase method) { else operatorInfo = Operators.TryGetOperatorInfo(method.Name); - if (!(operatorInfo is null)) { + if (operatorInfo is not null) { for (int i = 0; i < operatorInfo.Length - 1; i++) { WriteOperatorInfoString(operatorInfo[i]); WriteSpace(); @@ -494,7 +494,7 @@ void WriteReturnType(DmdMethodBase method) { void WriteOperatorInfoString(string s) => OutputWrite(s, 'A' <= s[0] && s[0] <= 'Z' ? DbgTextColor.Keyword : DbgTextColor.Operator); void WriteMethodName(DmdMethodBase method, string name, string[]? operatorInfo) { - if (!(operatorInfo is null)) + if (operatorInfo is not null) WriteOperatorInfoString(operatorInfo[operatorInfo.Length - 1]); else WriteIdentifier(name, TypeFormatterUtils.GetColor(method, canBeModule: true)); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicTypeFormatter.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicTypeFormatter.cs index 9c88bb8335..991868bd93 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicTypeFormatter.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicTypeFormatter.cs @@ -157,7 +157,7 @@ public void Format(DmdType type, DbgDotNetValue? value) { else { if (aryValue is null || aryValue.IsNull || !aryValue.GetArrayInfo(out elementCount, out var dimensionInfos)) dimensionInfos = null; - if (ShowArrayValueSizes && !(dimensionInfos is null) && dimensionInfos.Length == rank) { + if (ShowArrayValueSizes && dimensionInfos is not null && dimensionInfos.Length == rank) { for (int i = 0; i < rank; i++) { if (i > 0) { OutputWrite(",", DbgTextColor.Punctuation); @@ -183,7 +183,7 @@ public void Format(DmdType type, DbgDotNetValue? value) { else { Debug.Assert(aryType.IsSZArray); OutputWrite(ARRAY_OPEN_PAREN, DbgTextColor.Punctuation); - if (ShowArrayValueSizes && !(aryValue is null) && !aryValue.IsNull) { + if (ShowArrayValueSizes && aryValue is not null && !aryValue.IsNull) { if (aryValue.GetArrayCount(out elementCount)) WriteUInt32(elementCount); } @@ -223,7 +223,7 @@ public void Format(DmdType type, DbgDotNetValue? value) { int tupleIndex = 0; for (;;) { tupleType = WriteTupleFields(tupleType, ref tupleIndex); - if (!(tupleType is null)) + if (tupleType is not null) WriteCommaSpace(); else break; @@ -244,7 +244,7 @@ public void Format(DmdType type, DbgDotNetValue? value) { else { var typesList = new List(); typesList.Add(type); - while (!(type.DeclaringType is null)) { + while (type.DeclaringType is not null) { type = type.DeclaringType; typesList.Add(type); } @@ -291,7 +291,7 @@ public void Format(DmdType type, DbgDotNetValue? value) { } finally { recursionCounter--; - if (!(arrayTypesList is null)) { + if (arrayTypesList is not null) { foreach (var info in arrayTypesList) { if (info.value != value) info.value?.Dispose(); @@ -329,7 +329,7 @@ void WriteGenericArguments(DmdType type, IList genericArgs, ref int gen WriteCommaSpace(); //TODO: Write tuple name used in source string? fieldName = null; - if (!(fieldName is null)) { + if (fieldName is not null) { OutputWrite(fieldName, DbgTextColor.InstanceField); WriteSpace(); OutputWrite("As", DbgTextColor.Keyword); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicValueFormatter.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicValueFormatter.cs index 873c26334e..ae06f8beb7 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicValueFormatter.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/Formatters/VisualBasic/VisualBasicValueFormatter.cs @@ -118,10 +118,10 @@ bool TryFormatTuple(DbgDotNetValue value, int tupleArity) { DbgDotNetValue? objValue = value; DbgDotNetValueResult valueResult = default; try { - Debug2.Assert(!(info.fields is null)); + Debug2.Assert(info.fields is not null); foreach (var field in info.fields) { valueResult = runtime.LoadField(evalInfo, objValue, field); - if (!(valueResult.Value is null)) + if (valueResult.Value is not null) values.Add(valueResult.Value); if (valueResult.HasError || valueResult.ValueIsException) { objValue = null; @@ -157,10 +157,10 @@ bool TryFormatKeyValuePair(DbgDotNetValue value, (DmdFieldInfo? keyField, DmdFie DbgDotNetValueResult keyResult = default, valueResult = default; try { keyResult = runtime.LoadField(evalInfo, value, info.keyField); - if (!(keyResult.ErrorMessage is null) || keyResult.ValueIsException) + if (keyResult.ErrorMessage is not null || keyResult.ValueIsException) return false; valueResult = runtime.LoadField(evalInfo, value, info.valueField!); - if (!(valueResult.ErrorMessage is null) || valueResult.ValueIsException) + if (valueResult.ErrorMessage is not null || valueResult.ValueIsException) return false; OutputWrite(KeyValuePairTypeOpenParen, DbgTextColor.Punctuation); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/GetLocalsAssemblyBuilder.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/GetLocalsAssemblyBuilder.cs index c651de533d..c85a6f4350 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/GetLocalsAssemblyBuilder.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/GetLocalsAssemblyBuilder.cs @@ -90,7 +90,7 @@ public byte[] Compile(out DSEELocalAndMethod[] locals, out string typeName, out errorMessage = null; return Array.Empty(); } - Debug2.Assert(!(getLocalsType is null)); + Debug2.Assert(getLocalsType is not null); foreach (var p in sourceMethod.Parameters) { var name = language.GetVariableName(GetName(p), isThis: p.IsHiddenThisParameter); @@ -100,7 +100,7 @@ public byte[] Compile(out DSEELocalAndMethod[] locals, out string typeName, out } var body = sourceMethod.Body; - if (!(body is null)) { + if (body is not null) { foreach (var l in body.Variables) { var name = language.GetVariableName(GetName(l), isThis: false); const LocalAndMethodKind kind = LocalAndMethodKind.Local; @@ -140,8 +140,8 @@ string GetName(Local l) { } (string methodName, DkmClrCompilationResultFlags flags) AddMethod(TypeSig type, int index, bool isLocal) { - Debug2.Assert(!(generatedModule is null)); - Debug2.Assert(!(getLocalsType is null)); + Debug2.Assert(generatedModule is not null); + Debug2.Assert(getLocalsType is not null); var methodName = methodNamePrefix + methodNameIndex++.ToString(); var callConv = CallingConvention.Default; @@ -152,7 +152,7 @@ string GetName(Local l) { if (methodSig.RetType.IsByRef) methodSig.RetType = methodSig.RetType.Next.RemovePinnedAndModifiers(); - if (!(lastMethodSig is null)) { + if (lastMethodSig is not null) { foreach (var p in lastMethodSig.Params) methodSig.Params.Add(p); } @@ -220,7 +220,7 @@ static Instruction CreateLoadVariable(MethodDef method, IList locals, int } Instruction LoadIndirect(TypeSig? type) { - Debug2.Assert(!(generatedModule is null)); + Debug2.Assert(generatedModule is not null); switch (type.GetElementType()) { case ElementType.Boolean: return Instruction.Create(OpCodes.Ldind_I1); case ElementType.Char: return Instruction.Create(OpCodes.Ldind_U2); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/StateWithKey.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/StateWithKey.cs index 6f277ac572..40722632a9 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/StateWithKey.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/StateWithKey.cs @@ -28,8 +28,8 @@ sealed class StateWithKey where T : class { readonly List<(object key, T data)> list = new List<(object, T)>(); public static T? TryGet(DmdObject obj, object key) { - Debug2.Assert(!(obj is null)); - Debug2.Assert(!(key is null)); + Debug2.Assert(obj is not null); + Debug2.Assert(key is not null); var state = obj.GetOrCreateData>(); lock (state.lockObj) { var list = state.list; @@ -43,8 +43,8 @@ sealed class StateWithKey where T : class { } public static T GetOrCreate(DmdObject obj, object key, Func create) { - Debug2.Assert(!(obj is null)); - Debug2.Assert(!(key is null)); + Debug2.Assert(obj is not null); + Debug2.Assert(key is not null); var state = obj.GetOrCreateData>(); lock (state.lockObj) { var list = state.list; diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/AggregateValueNodeProvider.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/AggregateValueNodeProvider.cs index 05e7919908..5f6e5e5697 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/AggregateValueNodeProvider.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/AggregateValueNodeProvider.cs @@ -69,7 +69,7 @@ public override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory valueN return res; } catch { - evalInfo.Context.Runtime.Process.DbgManager.Close(res.Where(a => !(a is null))); + evalInfo.Context.Runtime.Process.DbgManager.Close(res.Where(a => a is not null)); throw; } } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ArrayValueNodeProvider.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ArrayValueNodeProvider.cs index fa06fc1ecb..37452c59cb 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ArrayValueNodeProvider.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ArrayValueNodeProvider.cs @@ -82,7 +82,7 @@ public override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory valueN } else { uint indexLeft = arrayIndex; - Debug2.Assert(!(indexes is null)); + Debug2.Assert(indexes is not null); for (int j = dimensionInfos.Length - 1; j >= 0; j--) { indexes[j] = (int)(indexLeft % dimensionInfos[j].Length) + dimensionInfos[j].BaseIndex; indexLeft = indexLeft / dimensionInfos[j].Length; @@ -99,7 +99,7 @@ public override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory valueN newNode = null; if (CSharpDynamicPropertyHelper.IsCSharpDynamicProperty(newValue.Value!.Type)) { var info = CSharpDynamicPropertyHelper.GetRealValue(evalInfo, newValue.Value); - if (!(info.name is null)) { + if (info.name is not null) { newValue.Value.Dispose(); name = new DbgDotNetText(new DbgDotNetTextPart(DbgTextColor.DebugViewPropertyName, info.name)); expression = valueNodeFactory.GetFieldExpression(expression, info.valueField.Name, null, false); @@ -115,7 +115,7 @@ public override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory valueN ObjectCache.Free(ref output); } catch { - evalInfo.Context.Process.DbgManager.Close(res.Where(a => !(a is null))); + evalInfo.Context.Process.DbgManager.Close(res.Where(a => a is not null)); newValue.Value?.Dispose(); throw; } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/CSharp/CSharpValueNodeFactory.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/CSharp/CSharpValueNodeFactory.cs index 1ecd90d44b..cf45defc24 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/CSharp/CSharpValueNodeFactory.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/CSharp/CSharpValueNodeFactory.cs @@ -116,7 +116,7 @@ protected override void FormatReturnValueMethodName(DbgEvaluationInfo evalInfo, typeFormatter.Format(method.DeclaringType!, null); var valueFormatter = new Formatters.CSharp.CSharpPrimitiveValueFormatter(output, valueOptions.ToValueFormatterOptions(), cultureInfo); output.Write(DbgTextColor.Operator, "."); - if (!(property is null)) { + if (property is not null) { if (property.GetIndexParameters().Count != 0) { output.Write(DbgTextColor.Keyword, Keyword_this); WriteMethodParameterList(output, method, typeFormatter, GetAllMethodParameterTypes(property.GetMethodSignature()), IndexerParenOpen, IndexerParenClose); @@ -139,7 +139,7 @@ protected override void FormatReturnValueMethodName(DbgEvaluationInfo evalInfo, } else { var operatorInfo = Formatters.CSharp.Operators.TryGetOperatorInfo(method.Name); - if (!(operatorInfo is null) && method is DmdMethodInfo methodInfo) { + if (operatorInfo is not null && method is DmdMethodInfo methodInfo) { bool isExplicitOrImplicit = operatorInfo[0] == "explicit" || operatorInfo[0] == "implicit"; for (int i = 0; i < operatorInfo.Length; i++) { diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetTypeVariablesNode.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetTypeVariablesNode.cs index 47ebda84a9..ef20fcf7b9 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetTypeVariablesNode.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetTypeVariablesNode.cs @@ -62,7 +62,7 @@ public override DbgDotNetValueNode[] GetChildren(DbgEvaluationInfo evalInfo, ulo res[i] = new TypeVariableValueNode(valueNodeFactory, typeVariableInfos[j]); } catch { - evalInfo.Context.Process.DbgManager.Close(res.Where(a => !(a is null))); + evalInfo.Context.Process.DbgManager.Close(res.Where(a => a is not null)); throw; } return res; @@ -88,7 +88,7 @@ public TypeVariableValueNode(LanguageValueNodeFactory valueNodeFactory, DbgDotNe ExpectedType = info.GenericArgumentType; Value = new TypeVariableValue(info.GenericArgumentType); var paramType = info.GenericParameterType; - bool isMethodParam = !(paramType.DeclaringMethod is null); + bool isMethodParam = paramType.DeclaringMethod is not null; ImageName = isMethodParam ? PredefinedDbgValueNodeImageNames.GenericMethodParameter : PredefinedDbgValueNodeImageNames.GenericTypeParameter; Name = valueNodeFactory.GetTypeParameterName(paramType); } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetValueNodeImpl.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetValueNodeImpl.cs index 029b1c15f2..66d3edd760 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetValueNodeImpl.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetValueNodeImpl.cs @@ -82,7 +82,7 @@ public override bool FormatName(DbgEvaluationInfo evalInfo, IDbgTextWriter outpu if ((options & DbgValueFormatterOptions.NoDebuggerDisplay) != 0) return false; var languageFormatter = formatter as LanguageFormatter; - Debug2.Assert(!(languageFormatter is null)); + Debug2.Assert(languageFormatter is not null); if (languageFormatter is null) return false; var displayAttrFormatter = new DebuggerDisplayAttributeFormatter(evalInfo, languageFormatter, output, options, cultureInfo); @@ -93,7 +93,7 @@ public override bool FormatValue(DbgEvaluationInfo evalInfo, IDbgTextWriter outp if (columnFormatter?.FormatValue(evalInfo, output, formatter, options, cultureInfo) == true) return true; - if (!(valueText.Parts is null)) { + if (valueText.Parts is not null) { valueText.WriteTo(output); return true; } @@ -114,7 +114,7 @@ bool FormatDebuggerDisplayAttributeType(DbgEvaluationInfo evalInfo, IDbgTextWrit if ((options & DbgValueFormatterOptions.NoDebuggerDisplay) != 0) return false; var languageFormatter = formatter as LanguageFormatter; - Debug2.Assert(!(languageFormatter is null)); + Debug2.Assert(languageFormatter is not null); if (languageFormatter is null) return false; var displayAttrFormatter = new DebuggerDisplayAttributeFormatter(evalInfo, languageFormatter, output, options, cultureInfo); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetValueNodeProviderFactory.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetValueNodeProviderFactory.cs index ef27968ea2..2a428fbbb5 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetValueNodeProviderFactory.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DbgDotNetValueNodeProviderFactory.cs @@ -209,7 +209,7 @@ public DbgDotNetValueNodeProviderResult Create(DbgEvaluationInfo evalInfo, bool public DbgDotNetValueNodeProviderResult CreateDynamicView(DbgEvaluationInfo evalInfo, bool addParens, DmdType slotType, DbgDotNetValueNodeInfo nodeInfo, DbgValueNodeEvaluationOptions options) { var state = GetTypeState(nodeInfo); var provider = TryCreateDynamicView(state, nodeInfo.Expression, nodeInfo.Value, slotType, options); - if (!(provider is null)) + if (provider is not null) return new DbgDotNetValueNodeProviderResult(provider); return new DbgDotNetValueNodeProviderResult(dnSpy_Roslyn_Resources.DynamicView_MustBeDynamicOrComType); } @@ -217,7 +217,7 @@ public DbgDotNetValueNodeProviderResult CreateDynamicView(DbgEvaluationInfo eval public DbgDotNetValueNodeProviderResult CreateResultsView(DbgEvaluationInfo evalInfo, bool addParens, DmdType slotType, DbgDotNetValueNodeInfo nodeInfo, DbgValueNodeEvaluationOptions options) { var state = GetTypeState(nodeInfo); var provider = TryCreateResultsView(state, nodeInfo.Expression, nodeInfo.Value, slotType, options); - if (!(provider is null)) + if (provider is not null) return new DbgDotNetValueNodeProviderResult(provider); return new DbgDotNetValueNodeProviderResult(dnSpy_Roslyn_Resources.ResultsView_MustBeEnumerableType); } @@ -234,7 +234,7 @@ void Create(DbgEvaluationInfo evalInfo, List provide TypeState GetOrCreateTypeState(DmdType type) { var state = StateWithKey.TryGet(type, this); - if (!(state is null)) + if (state is not null) return state; return CreateTypeState(type); @@ -322,7 +322,7 @@ TypeState CreateTypeStateCore(DmdType type) { foreach (var field in type.Fields) { var declType = field.DeclaringType; while (declType != currentType) { - Debug2.Assert(!(currentType.BaseType is null)); + Debug2.Assert(currentType.BaseType is not null); currentType = currentType.BaseType; if (inheritanceLevel != byte.MaxValue) inheritanceLevel++; @@ -348,7 +348,7 @@ TypeState CreateTypeStateCore(DmdType type) { continue; var declType = property.DeclaringType; while (declType != currentType) { - Debug2.Assert(!(currentType.BaseType is null)); + Debug2.Assert(currentType.BaseType is not null); currentType = currentType.BaseType; if (inheritanceLevel != byte.MaxValue) inheritanceLevel++; @@ -460,7 +460,7 @@ bool TryCreateNullable(DbgEvaluationInfo evalInfo, List pro if (!forceRawView && (creationOptions & CreationOptions.NoProxy) == 0 && funcEval && !nodeInfo.Value.IsNull) { var proxyCtor = DebuggerTypeProxyFinder.GetDebuggerTypeProxyConstructor(state.Type); - if (!(proxyCtor is null)) { + if (proxyCtor is not null) { var runtime = evalInfo.Runtime.GetDotNetRuntime(); var proxyTypeResult = runtime.CreateInstance(evalInfo, proxyCtor, new[] { nodeInfo.Value }, DbgDotNetInvokeOptions.None); // Use the result even if the constructor threw an exception @@ -558,7 +558,7 @@ void CreateCore(DbgEvaluationInfo evalInfo, List pro } DbgDotNetValueNodeProvider? TryCreateResultsView(TypeState state, string expression, DbgDotNetValue value, DmdType expectedType, DbgValueNodeEvaluationOptions evalOptions) { - if (!(state.EnumerableType is null) && !value.IsNull) + if (state.EnumerableType is not null && !value.IsNull) return new ResultsViewMembersValueNodeProvider(this, valueNodeFactory, state.EnumerableType, value, expectedType, expression, evalOptions); return null; } @@ -618,10 +618,10 @@ void AddProviders(List providers, TypeState state, s providers.Add(new StaticMembersValueNodeProvider(this, valueNodeFactory, StaticMembersName, state.TypeExpression, staticMembersInfos, membersEvalOptions)); var provider = TryCreateResultsView(state, expression, value, slotType, evalOptions); - if (!(provider is null)) + if (provider is not null) providers.Add(provider); provider = TryCreateDynamicView(state, expression, value, slotType, evalOptions); - if (!(provider is null)) + if (provider is not null) providers.Add(provider); } static readonly DbgDotNetText rawViewName = new DbgDotNetText(new DbgDotNetTextPart(DbgTextColor.Text, dnSpy_Roslyn_Resources.DebuggerVarsWindow_RawView)); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DebuggerTypeProxyFinder.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DebuggerTypeProxyFinder.cs index 085845386a..c3bfe29473 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DebuggerTypeProxyFinder.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DebuggerTypeProxyFinder.cs @@ -42,8 +42,8 @@ public TypeKey(DmdType type) { public AssemblyState(DmdAssembly assembly) { dict = new Dictionary(); var proxyAttr = assembly.AppDomain.GetWellKnownType(DmdWellKnownType.System_Diagnostics_DebuggerTypeProxyAttribute, isOptional: true); - Debug2.Assert(!(proxyAttr is null)); - if (!(proxyAttr is null)) { + Debug2.Assert(proxyAttr is not null); + if (proxyAttr is not null) { foreach (var ca in assembly.CustomAttributes) { if (ca.AttributeType != proxyAttr) continue; @@ -102,7 +102,7 @@ ProxyState CreateProxyState(DmdType targetType, DmdConstructorInfo? proxyCtor) = static DmdConstructorInfo? GetProxyTypeConstructor(DmdType targetType) { var proxyAttr = targetType.AppDomain.GetWellKnownType(DmdWellKnownType.System_Diagnostics_DebuggerTypeProxyAttribute, isOptional: true); - Debug2.Assert(!(proxyAttr is null)); + Debug2.Assert(proxyAttr is not null); if (proxyAttr is null) return null; DmdType? currentType = targetType; @@ -110,15 +110,15 @@ ProxyState CreateProxyState(DmdType targetType, DmdConstructorInfo? proxyCtor) = DmdConstructorInfo? proxyCtor; var ca = currentType.FindCustomAttribute(proxyAttr, inherit: false); - if (!(ca is null) && ca.ConstructorArguments.Count == 1) { + if (ca is not null && ca.ConstructorArguments.Count == 1) { proxyCtor = GetConstructor(GetType(currentType.Assembly, ca.ConstructorArguments[0].Value), currentType); - if (!(proxyCtor is null)) + if (proxyCtor is not null) return proxyCtor; } var asmState = GetAssemblyState(currentType.Assembly); proxyCtor = GetConstructor(asmState.GetProxyType(currentType), currentType); - if (!(proxyCtor is null)) + if (proxyCtor is not null) return proxyCtor; currentType = currentType.BaseType; diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DynamicViewMembersValueNodeProvider.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DynamicViewMembersValueNodeProvider.cs index 9a6101a510..8091dd1e35 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DynamicViewMembersValueNodeProvider.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/DynamicViewMembersValueNodeProvider.cs @@ -105,7 +105,7 @@ protected override (DbgDotNetValueNode node, bool canHide) CreateValueNode(DbgEv protected override (DbgDotNetValueNode? node, bool canHide) TryCreateInstanceValueNode(DbgEvaluationInfo evalInfo, DbgDotNetValueResult valueResult) { var noResultsNode = DebugViewNoResultsValueNode.TryCreate(evalInfo, Expression, valueResult); - if (!(noResultsNode is null)) { + if (noResultsNode is not null) { valueResult.Value?.Dispose(); return (noResultsNode, false); } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/EnumerableDebugViewHelper.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/EnumerableDebugViewHelper.cs index 877cdeaf4c..0e0f57a6aa 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/EnumerableDebugViewHelper.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/EnumerableDebugViewHelper.cs @@ -56,7 +56,7 @@ static class EnumerableDebugViewHelper { } var ctor = debugViewType.GetConstructor(DmdBindingFlags.Public | DmdBindingFlags.NonPublic | DmdBindingFlags.Instance, DmdCallingConventions.Standard | DmdCallingConventions.HasThis, new[] { enumerableType }); - Debug2.Assert(!(ctor is null)); + Debug2.Assert(ctor is not null); return ctor; } @@ -83,7 +83,7 @@ public static (DmdConstructorInfo ctor, DmdMethodInfo toArrayMethod) GetListEnum var toArrayMethd = type.GetMethod(nameof(List.ToArray), DmdSignatureCallingConvention.HasThis, 0, genArgs[0].MakeArrayType(), Array.Empty(), throwOnError: false) as DmdMethodInfo; - Debug2.Assert((!(ctor is null)) == (!(toArrayMethd is null))); + Debug2.Assert((ctor is not null) == (toArrayMethd is not null)); if (ctor is null || toArrayMethd is null) return default; return (ctor, toArrayMethd); @@ -92,7 +92,7 @@ public static (DmdConstructorInfo ctor, DmdMethodInfo toArrayMethod) GetListEnum var icollectionType = appDomain.GetWellKnownType(DmdWellKnownType.System_Collections_ICollection, isOptional: true); if (!objType.CanCastTo(icollectionType)) return default; - Debug2.Assert(!(icollectionType is null)); + Debug2.Assert(icollectionType is not null); var type = appDomain.CorLib?.GetType("System.Collections." + nameof(ArrayList)); var ctor = type?.GetMethod(DmdConstructorInfo.ConstructorName, DmdSignatureCallingConvention.HasThis, @@ -100,7 +100,7 @@ public static (DmdConstructorInfo ctor, DmdMethodInfo toArrayMethod) GetListEnum var toArrayMethd = type?.GetMethod(nameof(ArrayList.ToArray), DmdSignatureCallingConvention.HasThis, 0, appDomain.System_Object.MakeArrayType(), Array.Empty(), throwOnError: false) as DmdMethodInfo; - Debug2.Assert((!(ctor is null)) == (!(toArrayMethd is null))); + Debug2.Assert((ctor is not null) == (toArrayMethd is not null)); if (ctor is null || toArrayMethd is null) return default; return (ctor, toArrayMethd); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/LanguageValueNodeFactory.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/LanguageValueNodeFactory.cs index 396609d6cf..5c2f6c09e7 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/LanguageValueNodeFactory.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/LanguageValueNodeFactory.cs @@ -45,7 +45,7 @@ abstract class LanguageValueNodeFactory : DbgDotNetValueNodeFactory { protected abstract bool SupportsModuleTypes { get; } public DbgDotNetText GetTypeParameterName(DmdType typeParameter) { - bool isMethodParam = !(typeParameter.DeclaringMethod is null); + bool isMethodParam = typeParameter.DeclaringMethod is not null; var name = typeParameter.MetadataName ?? string.Empty; // Added by vbc const string StateMachineTypeParameterPrefix = "SM$"; @@ -81,7 +81,7 @@ DbgDotNetValueNode CreateValue(DbgEvaluationInfo evalInfo, DbgDotNetText name, D var specialViewOptions = (options & ~(DbgValueNodeEvaluationOptions.ResultsView | DbgValueNodeEvaluationOptions.DynamicView)); if ((options & DbgValueNodeEvaluationOptions.ResultsView) != 0) { info = valueNodeProviderFactory.CreateResultsView(evalInfo, addParens, expectedType, nodeInfo, specialViewOptions); - useProvider = !(info.ErrorMessage is null); + useProvider = info.ErrorMessage is not null; } else if ((options & DbgValueNodeEvaluationOptions.DynamicView) != 0) { info = valueNodeProviderFactory.CreateDynamicView(evalInfo, addParens, expectedType, nodeInfo, specialViewOptions); @@ -90,9 +90,9 @@ DbgDotNetValueNode CreateValue(DbgEvaluationInfo evalInfo, DbgDotNetText name, D else info = valueNodeProviderFactory.Create(evalInfo, addParens, expectedType, nodeInfo, options); if (useProvider) { - if (!(info.ErrorMessage is null)) + if (info.ErrorMessage is not null) return new DbgDotNetValueNodeImpl(this, info.Provider, name, nodeInfo, expression, PredefinedDbgValueNodeImageNames.Error, true, false, null, null, info.ErrorMessage, new DbgDotNetText(new DbgDotNetTextPart(DbgTextColor.Error, info.ErrorMessage)), formatSpecifiers, columnFormatter); - Debug2.Assert(!(info.Provider is null)); + Debug2.Assert(info.Provider is not null); return new DbgDotNetValueNodeImpl(this, info.Provider, name, nodeInfo, expression, info.Provider?.ImageName ?? imageName, true, false, null, null, info.ErrorMessage, info.Provider?.ValueText ?? default, formatSpecifiers, columnFormatter); } return new DbgDotNetValueNodeImpl(this, info.Provider, name, nodeInfo, expression, imageName, isReadOnly, causesSideEffects, expectedType, value.Type, info.ErrorMessage, default, formatSpecifiers, columnFormatter); @@ -134,7 +134,7 @@ public sealed override DbgDotNetValueNode CreateReturnValue(DbgEvaluationInfo ev const bool isReadOnly = true; const bool causesSideEffects = false; var property = PropertyState.TryGetProperty(method); - var imageName = !(property is null) ? ImageNameUtils.GetImageName(property) : ImageNameUtils.GetImageName(method, SupportsModuleTypes); + var imageName = property is not null ? ImageNameUtils.GetImageName(property) : ImageNameUtils.GetImageName(method, SupportsModuleTypes); return CreateValue(evalInfo, default, value, formatSpecifiers, options, expression, imageName, isReadOnly, causesSideEffects, value.Type, false, columnFormatter); } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/MemberValueNodeInfo.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/MemberValueNodeInfo.cs index c4e15af302..a3ec2fa9da 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/MemberValueNodeInfo.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/MemberValueNodeInfo.cs @@ -138,7 +138,7 @@ static MemberValueNodeInfoFlags GetInfoFlags(DmdMemberInfo member) { case DmdMemberTypes.Property: var prop = (DmdPropertyInfo)member; var accessor = prop.GetGetMethod(DmdGetAccessorOptions.All) ?? prop.GetSetMethod(DmdGetAccessorOptions.All); - if (!(accessor is null)) { + if (accessor is not null) { if (accessor.IsPublic) res |= MemberValueNodeInfoFlags.Public; else if ((accessor.IsPrivate || accessor.IsPrivateScope) && accessor.DeclaringType != accessor.ReflectedType) diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/MembersValueNodeProvider.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/MembersValueNodeProvider.cs index beae5fa618..d589d16517 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/MembersValueNodeProvider.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/MembersValueNodeProvider.cs @@ -93,8 +93,8 @@ protected MembersValueNodeProvider(LanguageValueNodeFactory valueNodeFactory, Db public sealed override ulong GetChildCount(DbgEvaluationInfo evalInfo) { if (!hasInitialized) Initialize(evalInfo); - Debug2.Assert(!(childNodeProviderInfos is null)); - if (!(realProvider is null)) + Debug2.Assert(childNodeProviderInfos is not null); + if (realProvider is not null) return realProvider.GetChildCount(evalInfo); return childNodeProviderInfos[childNodeProviderInfos.Length - 1].EndIndex; } @@ -105,13 +105,13 @@ void Initialize(DbgEvaluationInfo evalInfo) { if (hasInitialized) return; errorMessage = InitializeCore(evalInfo); - if (!(realProvider is null)) + if (realProvider is not null) return; - Debug2.Assert(!(errorMessage is null) || !(membersCollection.Members is null)); + Debug2.Assert(errorMessage is not null || membersCollection.Members is not null); if (errorMessage is null && membersCollection.Members is null) errorMessage = PredefinedEvaluationErrorMessages.InternalDebuggerError; dbgManager = evalInfo.Runtime.Process.DbgManager; - if (!(errorMessage is null)) + if (errorMessage is not null) childNodeProviderInfos = new ChildNodeProviderInfo[] { new ChildNodeProviderInfo(0, 1, 0) }; else if ((evalOptions & DbgValueNodeEvaluationOptions.NoHideRoots) != 0 || !membersCollection.HasHideRoot || (evalOptions & DbgValueNodeEvaluationOptions.RawView) != 0 || membersCollection.Members!.Length == 0) childNodeProviderInfos = new ChildNodeProviderInfo[] { new ChildNodeProviderInfo(0, (uint)membersCollection.Members!.Length, 0) }; @@ -150,7 +150,7 @@ void Initialize(DbgEvaluationInfo evalInfo) { childNodeProviderInfos = Cache.FreeAndToArray(ref list); } catch { - if (!(valueNode is null)) + if (valueNode is not null) dbgManager.Close(valueNode); dbgManager.Close(list.Select(a => a.ValueNode).OfType()); throw; @@ -207,7 +207,7 @@ void Initialize(DbgEvaluationInfo evalInfo) { DbgDotNetValueNode newNode; bool canHide = true; var customInfo = TryCreateInstanceValueNode(evalInfo, valueResult); - if (!(customInfo.node is null)) + if (customInfo.node is not null) (newNode, canHide) = customInfo; else if (valueResult.HasError) { newNode = valueNodeFactory.CreateError(evalInfo, info.Name, valueResult.ErrorMessage!, expression, false); @@ -249,7 +249,7 @@ static DmdType GetMemberDeclaringType(DmdMemberInfo member) { int lastProviderIndex; int GetProviderIndex(ulong childIndex) { - Debug2.Assert(!(childNodeProviderInfos is null)); + Debug2.Assert(childNodeProviderInfos is not null); var infos = childNodeProviderInfos; ref readonly var last = ref infos[lastProviderIndex]; if (last.StartIndex <= childIndex && childIndex < last.EndIndex) @@ -274,8 +274,8 @@ public sealed override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory Debug.Assert(this.valueNodeFactory == valueNodeFactory); if (!hasInitialized) Initialize(evalInfo); - Debug2.Assert(!(childNodeProviderInfos is null)); - if (!(realProvider is null)) + Debug2.Assert(childNodeProviderInfos is not null); + if (realProvider is not null) return realProvider.GetChildren(valueNodeFactory, evalInfo, index, count, options, formatSpecifiers); DbgDotNetValueNode[]? children = null; var res = count == 0 ? Array.Empty() : new DbgDotNetValueNode[count]; @@ -285,7 +285,7 @@ public sealed override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory for (int i = 0; i < res.Length && providerIndex < childNodeProviderInfos.Length; providerIndex++) { evalInfo.CancellationToken.ThrowIfCancellationRequested(); ref readonly var providerInfo = ref childNodeProviderInfos[providerIndex]; - if (!(providerInfo.ValueNode is null)) { + if (providerInfo.ValueNode is not null) { UpdateFormatSpecifiers(providerInfo.ValueNode, formatSpecifiers); if (providerInfo.CanHide) { ulong childCount = providerInfo.EndIndex - providerInfo.StartIndex; @@ -304,7 +304,7 @@ public sealed override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory else { while (index + (uint)i < providerInfo.EndIndex && i < res.Length) { evalInfo.CancellationToken.ThrowIfCancellationRequested(); - res[i] = !(errorMessage is null) ? + res[i] = errorMessage is not null ? valueNodeFactory.CreateError(evalInfo, errorPropertyName, errorMessage, Expression, false) : CreateValueNode(evalInfo, (int)(index + (uint)i - providerInfo.StartIndex + providerInfo.BaseIndex), options, formatSpecifiers).node; i++; @@ -313,9 +313,9 @@ public sealed override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory } } catch { - if (!(children is null)) + if (children is not null) evalInfo.Runtime.Process.DbgManager.Close(children); - evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => !(a is null))); + evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => a is not null)); throw; } return res; @@ -328,12 +328,12 @@ void UpdateFormatSpecifiers(DbgDotNetValueNode valueNode, ReadOnlyCollection= 1); - if (childNodeProviderInfos.Length > 1 || !(childNodeProviderInfos[0].ValueNode is null)) + if (childNodeProviderInfos.Length > 1 || childNodeProviderInfos[0].ValueNode is not null) dbgManager?.Close(childNodeProviderInfos.Select(a => a.ValueNode).OfType()); } } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/PointerValueNodeProvider.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/PointerValueNodeProvider.cs index 85ccda97b7..eaef802730 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/PointerValueNodeProvider.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/PointerValueNodeProvider.cs @@ -55,7 +55,7 @@ public override ulong GetChildCount(DbgEvaluationInfo evalInfo) { derefValue = value.LoadIndirect().Value; Debug2.Assert((derefValue is null) == ((evalInfo.Runtime.GetDotNetRuntime().Features & DbgDotNetRuntimeFeatures.NoDereferencePointers) != 0)); } - return !(derefValue is null) ? 1UL : 0; + return derefValue is not null ? 1UL : 0; } public override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory valueNodeFactory, DbgEvaluationInfo evalInfo, ulong index, int count, DbgValueNodeEvaluationOptions options, ReadOnlyCollection? formatSpecifiers) { @@ -66,7 +66,7 @@ public override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory valueN var nodeInfo = new DbgDotNetValueNodeInfo(derefValue, derefExpr); var res = valueNodeProviderFactory.Create(evalInfo, true, derefValue.Type, nodeInfo, options); DbgDotNetValueNode valueNode; - if (!(res.ErrorMessage is null)) + if (res.ErrorMessage is not null) valueNode = valueNodeFactory.CreateError(evalInfo, DbgDotNetText.Empty, res.ErrorMessage, derefExpr, false); else valueNode = valueNodeFactory.Create(res.Provider!, derefName, nodeInfo, derefExpr, PredefinedDbgValueNodeImageNames.DereferencedPointer, false, false, value.Type.GetElementType()!, derefValue.Type, null, default, formatSpecifiers); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ReflectionAssemblyLoader.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ReflectionAssemblyLoader.cs index 5d93e52f71..463eb7db1b 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ReflectionAssemblyLoader.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ReflectionAssemblyLoader.cs @@ -39,7 +39,7 @@ public ReflectionAssemblyLoader(DbgEvaluationInfo evalInfo, DmdAppDomain appDoma // Try System.Reflection.Assembly.Load(string) bool Try_Assembly_Load_String(string assemblyFullName) { var systemAssemblyType = appDomain.GetWellKnownType(DmdWellKnownType.System_Reflection_Assembly, isOptional: true); - Debug2.Assert(!(systemAssemblyType is null)); + Debug2.Assert(systemAssemblyType is not null); if (systemAssemblyType is null) return false; diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ResultsViewMembersValueNodeProvider.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ResultsViewMembersValueNodeProvider.cs index 920d9333be..604990a7cc 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ResultsViewMembersValueNodeProvider.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/ResultsViewMembersValueNodeProvider.cs @@ -66,7 +66,7 @@ sealed class ForceLoadAssemblyState { return PredefinedEvaluationErrorMessages.FuncEvalDisabled; var errorMessage = InitializeEnumerableDebugView(evalInfo); - if (!(errorMessage is null)) { + if (errorMessage is not null) { if (InitializeListDebugView(evalInfo)) errorMessage = null; } @@ -175,7 +175,7 @@ protected override (DbgDotNetValueNode node, bool canHide) CreateValueNode(DbgEv protected override (DbgDotNetValueNode? node, bool canHide) TryCreateInstanceValueNode(DbgEvaluationInfo evalInfo, DbgDotNetValueResult valueResult) { var noResultsNode = DebugViewNoResultsValueNode.TryCreate(evalInfo, Expression, valueResult); - if (!(noResultsNode is null)) { + if (noResultsNode is not null) { valueResult.Value?.Dispose(); return (noResultsNode, false); } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/TupleValueNodeProvider.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/TupleValueNodeProvider.cs index ab0764a1fb..28ce2949d2 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/TupleValueNodeProvider.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/TupleValueNodeProvider.cs @@ -91,7 +91,7 @@ public override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory valueN var name = new DbgDotNetText(new DbgDotNetTextPart(DbgTextColor.InstanceField, info.DefaultName)); DbgDotNetValueNode newNode; - if (!(errorMessage is null)) + if (errorMessage is not null) newNode = valueNodeFactory.CreateError(evalInfo, name, errorMessage, expression, false); else if (valueIsException) newNode = valueNodeFactory.Create(evalInfo, name, objValue, formatSpecifiers, options, expression, PredefinedDbgValueNodeImageNames.Error, true, false, expectedType, false); @@ -105,7 +105,7 @@ public override DbgDotNetValueNode[] GetChildren(LanguageValueNodeFactory valueN } } catch { - evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => !(a is null))); + evalInfo.Runtime.Process.DbgManager.Close(res.Where(a => a is not null)); foreach (var vr in valueResults) vr.Value?.Dispose(); valueResult.Value?.Dispose(); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/VisualBasic/VisualBasicValueNodeFactory.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/VisualBasic/VisualBasicValueNodeFactory.cs index a59cac766f..c50882cc62 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/VisualBasic/VisualBasicValueNodeFactory.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Debugger/ValueNodes/VisualBasic/VisualBasicValueNodeFactory.cs @@ -109,7 +109,7 @@ protected override void FormatReturnValueMethodName(DbgEvaluationInfo evalInfo, typeFormatter.Format(method.DeclaringType!, null); var valueFormatter = new Formatters.VisualBasic.VisualBasicPrimitiveValueFormatter(output, valueOptions.ToValueFormatterOptions(), cultureInfo); output.Write(DbgTextColor.Operator, "."); - if (!(property is null)) { + if (property is not null) { output.Write(MemberUtils.GetColor(property), Formatters.VisualBasic.VisualBasicTypeFormatter.GetFormattedIdentifier(property.Name)); valueFormatter.WriteTokenComment(property.MetadataToken); output.Write(DbgTextColor.Operator, "."); @@ -118,7 +118,7 @@ protected override void FormatReturnValueMethodName(DbgEvaluationInfo evalInfo, } else { var operatorInfo = Formatters.VisualBasic.Operators.TryGetOperatorInfo(method.Name); - if (!(operatorInfo is null) && method is DmdMethodInfo methodInfo) { + if (operatorInfo is not null && method is DmdMethodInfo methodInfo) { for (int i = 0; i < operatorInfo.Length; i++) { if (i > 0) output.Write(DbgTextColor.Text, " "); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Documentation/RoslynDocumentationProvider.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Documentation/RoslynDocumentationProvider.cs index 540584bd26..743b204d79 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Documentation/RoslynDocumentationProvider.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Documentation/RoslynDocumentationProvider.cs @@ -52,7 +52,7 @@ sealed class RoslynDocumentationProvider : DocumentationProvider { public override bool Equals(object? obj) { var other = obj as RoslynDocumentationProvider; - return !(other is null) && stringComparer.Equals(filename, other.filename); + return other is not null && stringComparer.Equals(filename, other.filename); } } } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/Classification/CompletionClassifier.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/Classification/CompletionClassifier.cs index f623f46642..75505741a2 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/Classification/CompletionClassifier.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/Classification/CompletionClassifier.cs @@ -104,8 +104,8 @@ public IEnumerable GetTags(TextClassifierContext context) // The text is usually identical to the description and it's classified var description = completionSet.GetDescriptionAsync(completion).GetAwaiter().GetResult(); var indexes = GetMatchIndexes(completion, description); - if (!(indexes is null)) { - Debug2.Assert(!(description is null)); + if (indexes is not null) { + Debug2.Assert(description is not null); int pos = 0; var parts = description.TaggedParts; int endIndex = indexes.Value.endIndex; diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/CommandTargetFilter.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/CommandTargetFilter.cs index b9bd42d5fd..64fa6a0c8a 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/CommandTargetFilter.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/CommandTargetFilter.cs @@ -63,7 +63,7 @@ public CommandTargetFilter(ITextView textView, Lazy completio EnterKeyRule? TryGetEnterKeyRule() { if (!HasSession) return null; - Debug2.Assert(!(completionSession is null)); + Debug2.Assert(completionSession is not null); if (completionSession.SelectedCompletionSet?.SelectionStatus.Completion is RoslynCompletion completion) return completion.CompletionItem.Rules.EnterKeyRule; @@ -108,7 +108,7 @@ bool ShouldPassThroughEnterKey(EnterKeyRule enterKeyRule) { case EnterKeyRule.AfterFullyTypedWord: if (!HasSession) return false; - Debug2.Assert(!(completionSession is null)); + Debug2.Assert(completionSession is not null); var completion = completionSession.SelectedCompletionSet?.SelectionStatus.Completion; if (completion is null) return false; @@ -128,7 +128,7 @@ bool ShouldPassThroughEnterKey(EnterKeyRule enterKeyRule) { bool TryCommitCharacter(char c) { if (!HasSession) return false; - Debug2.Assert(!(completionSession is null)); + Debug2.Assert(completionSession is not null); var completionService = TryGetRoslynCompletionService(); if (completionService is null) return false; @@ -145,7 +145,7 @@ public CommandTargetStatus Execute(Guid group, int cmdId, object? args, ref obje return CommandTargetStatus.NotHandled; if (HasSession) { - Debug2.Assert(!(completionSession is null)); + Debug2.Assert(completionSession is not null); if (group == CommandConstants.TextEditorGroup) { switch ((TextEditorIds)cmdId) { case TextEditorIds.RETURN: @@ -196,7 +196,7 @@ public CommandTargetStatus Execute(Guid group, int cmdId, object? args, ref obje case TextEditorIds.COMPLETEWORD: StartSession(); if (HasSession) { - Debug2.Assert(!(completionSession is null)); + Debug2.Assert(completionSession is not null); if (completionSession.SelectedCompletionSet?.SelectionStatus.IsUnique == true) completionSession.Commit(); } @@ -226,14 +226,14 @@ bool TryStartSession(char c, bool isDelete) { return HasSession; } - bool HasSession => !(completionSession is null); + bool HasSession => completionSession is not null; void StartSession(CompletionInfo? info = null, CompletionTrigger? completionTrigger = null) { if (HasSession) return; var triggerPoint = textView.TextSnapshot.CreateTrackingPoint(textView.Caret.Position.BufferPosition.Position, PointTrackingMode.Negative, TrackingFidelityMode.Forward); completionSession = completionBroker.Value.CreateCompletionSession(textView, triggerPoint, trackCaret: true); - if (!(completionTrigger is null)) + if (completionTrigger is not null) completionSession.Properties.AddProperty(typeof(CompletionTrigger), completionTrigger); completionSession.Dismissed += CompletionSession_Dismissed; completionSession.Start(); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/CompletionToolTipProvider.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/CompletionToolTipProvider.cs index 0041a4ccef..f3774962f9 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/CompletionToolTipProvider.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/Completions/CompletionToolTipProvider.cs @@ -61,7 +61,7 @@ sealed class CompletionToolTipProvider : IUIElementProvider completions) { foreach (var c in completions) { var rc = c as RoslynCompletion; - Debug2.Assert(!(rc is null)); - if (!(rc is null)) + Debug2.Assert(rc is not null); + if (rc is not null) rc.CompletionSet = this; } } @@ -102,12 +102,12 @@ protected override void Filter(List filteredResult, IList? filteredTags = null; var filters = Filters; - Debug2.Assert(!(filters is null)); - if (!(filters is null)) { + Debug2.Assert(filters is not null); + if (filters is not null) { foreach (var tmpFilter in filters) { var filter = tmpFilter as RoslynIntellisenseFilter; - Debug2.Assert(!(filter is null)); - if (!(filter is null) && filter.IsChecked) { + Debug2.Assert(filter is not null); + if (filter is not null && filter.IsChecked) { if (filteredTags is null) filteredTags = new List(); filteredTags.AddRange(filter.Tags); @@ -139,7 +139,7 @@ public void Commit(RoslynCompletion completion) { mruCompletionService.AddText(completion.DisplayText); var info = CompletionInfo.Create(ApplicableTo.TextBuffer.CurrentSnapshot); - Debug2.Assert(!(info is null)); + Debug2.Assert(info is not null); if (info is null) return; @@ -156,7 +156,7 @@ public void Commit(RoslynCompletion completion) { return; ed.Apply(); } - if (!(change.NewPosition is null)) { + if (change.NewPosition is not null) { var snapshot = buffer.CurrentSnapshot; Debug.Assert(change.NewPosition.Value <= snapshot.Length); if (change.NewPosition.Value <= snapshot.Length) { diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/QuickInfo/InformationQuickInfoContentVM.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/QuickInfo/InformationQuickInfoContentVM.cs index 31ee94c25d..11a9f548c2 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/QuickInfo/InformationQuickInfoContentVM.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/QuickInfo/InformationQuickInfoContentVM.cs @@ -41,15 +41,15 @@ sealed class InformationQuickInfoContentVM : ViewModelBase { public bool HasWarningImageReference => !WarningImageReference.IsDefault; public object? MainDescriptionObject { get; } public object? DocumentationObject { get; } - public bool HasDocumentationObject => !(DocumentationObject is null); + public bool HasDocumentationObject => DocumentationObject is not null; public object? UsageObject { get; } - public bool HasUsageObject => !(UsageObject is null); + public bool HasUsageObject => UsageObject is not null; public object? TypeParameterMapObject { get; } - public bool HasTypeParameterMapObject => !(TypeParameterMapObject is null); + public bool HasTypeParameterMapObject => TypeParameterMapObject is not null; public object? AnonymousTypesObject { get; } - public bool HasAnonymousTypesObject => !(AnonymousTypesObject is null); + public bool HasAnonymousTypesObject => AnonymousTypesObject is not null; public object? ExceptionObject { get; } - public bool HasExceptionObject => !(ExceptionObject is null); + public bool HasExceptionObject => ExceptionObject is not null; public InformationQuickInfoContentVM(ITextView textView, InformationQuickInfoContent content, IClassificationFormatMap classificationFormatMap, IThemeClassificationTypeService themeClassificationTypeService) { if (textView is null) @@ -61,9 +61,9 @@ public InformationQuickInfoContentVM(ITextView textView, InformationQuickInfoCon if (themeClassificationTypeService is null) throw new ArgumentNullException(nameof(themeClassificationTypeService)); var sb = new StringBuilder(); - if (!(content.SymbolGlyph is null)) + if (content.SymbolGlyph is not null) SymbolImageReference = content.SymbolGlyph.Value.GetImageReference() ?? default; - if (!(content.WarningGlyph is null)) + if (content.WarningGlyph is not null) WarningImageReference = content.WarningGlyph.Value.GetImageReference() ?? default; MainDescriptionObject = TryCreateObject(sb, content.MainDescription, classificationFormatMap, themeClassificationTypeService); DocumentationObject = TryCreateObject(sb, content.Documentation, classificationFormatMap, themeClassificationTypeService); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/QuickInfo/QuickInfoSource.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/QuickInfo/QuickInfoSource.cs index 11910b253f..6b6d5325b4 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/QuickInfo/QuickInfoSource.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/QuickInfo/QuickInfoSource.cs @@ -70,7 +70,7 @@ public void AugmentQuickInfoSession(IQuickInfoSession session, IList qui session.Properties.AddProperty(hasTriggeredQuickInfoKey, null); var point = session.GetTriggerPoint(session.TextView.TextSnapshot); - if (!(point is null)) + if (point is not null) quickInfoTriggerServiceProvider.Create(session.TextView).TryTrigger(point.Value, session.TrackMouse); return; } @@ -81,7 +81,7 @@ public void AugmentQuickInfoSession(IQuickInfoSession session, IList qui quickInfoTriggerServiceProvider.CloseOtherSessions(session); var item = qiSession.Item; - Debug2.Assert(!(item is null)); + Debug2.Assert(item is not null); if (item is null) return; var info = qiSession.State; diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/CommandTargetFilter.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/CommandTargetFilter.cs index 136805f075..f7d0eddf83 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/CommandTargetFilter.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/CommandTargetFilter.cs @@ -93,7 +93,7 @@ public CommandTargetStatus Execute(Guid group, int cmdId, object? args, ref obje var s = args as string; if (s is null || s.Length != 1) break; - if (!(session is null)) { + if (session is not null) { if (session.IsRetriggerCharacter(s[0])) TriggerSession(new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.RetriggerCommand, s[0])); else if (session.IsTriggerCharacter(s[0])) @@ -111,7 +111,7 @@ public CommandTargetStatus Execute(Guid group, int cmdId, object? args, ref obje // Need to retrigger it if user backspaced and deleted a comma. We need to check for it // here because Caret-pos-changed handler doesn't retrigger it for perf reasons. - if (!(session is null) && oldSnapshot != textView.TextSnapshot) + if (session is not null && oldSnapshot != textView.TextSnapshot) TriggerSession(new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.RetriggerCommand)); return CommandTargetStatus.Handled; @@ -163,7 +163,7 @@ bool ShouldRetrigger(CaretPositionChangedEventArgs e) { } bool IsRetriggerCharacter(CaretPosition caretPos) { - Debug2.Assert(!(session is null)); + Debug2.Assert(session is not null); if (session is null) return false; if (caretPos.VirtualSpaces > 0) diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/Parameter.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/Parameter.cs index c1b2de1152..c7318186b7 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/Parameter.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/Parameter.cs @@ -38,7 +38,7 @@ public TaggedText[] DocumentationTaggedText { get { if (documentationTaggedText is null) InitializeDocumentation(); - Debug2.Assert(!(documentationTaggedText is null)); + Debug2.Assert(documentationTaggedText is not null); return documentationTaggedText; } } @@ -48,7 +48,7 @@ public string Documentation { get { if (documentation is null) InitializeDocumentation(); - Debug2.Assert(!(documentation is null)); + Debug2.Assert(documentation is not null); return documentation; } } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/Signature.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/Signature.cs index 00acf24354..68c6a0566e 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/Signature.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/Signature.cs @@ -99,7 +99,7 @@ public Builder(Signature signature, SignatureHelpItem item, int? selectedParamet Parameters.Add(new Parameter(signature, parameter, locus, prettyPrintedLocus)); } Add(item.SuffixDisplayParts); - if (!(selectedParameter is null) && (uint)selectedParameter.Value < (uint)item.Parameters.Length) { + if (selectedParameter is not null && (uint)selectedParameter.Value < (uint)item.Parameters.Length) { var parameter = item.Parameters[selectedParameter.Value]; Add(parameter.SelectedDisplayParts); } @@ -152,7 +152,7 @@ public Signature(ITrackingSpan applicableToSpan, SignatureHelpItem item, bool is PrettyPrintedContentTaggedText = builder.PrettyPrintedContentTaggedText; Parameters = new ReadOnlyCollection(builder.Parameters); - if (!(selectedParameter is null)) { + if (selectedParameter is not null) { if ((uint)selectedParameter.Value < (uint)Parameters.Count) CurrentParameter = Parameters[selectedParameter.Value]; else if (item.IsVariadic && Parameters.Count > 0) diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/SignatureHelpSession.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/SignatureHelpSession.cs index 6c9c61a2c4..650b25acc5 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/SignatureHelpSession.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/SignatureHelpSession.cs @@ -67,12 +67,12 @@ sealed class SignatureHelpSession { if (info is null) return null; if (triggerInfo.TriggerReason == SignatureHelpTriggerReason.TypeCharCommand) { - Debug2.Assert(!(triggerInfo.TriggerCharacter is null)); - if (!(triggerInfo.TriggerCharacter is null) && !info.Value.SignatureHelpService.IsTriggerCharacter(triggerInfo.TriggerCharacter.Value)) + Debug2.Assert(triggerInfo.TriggerCharacter is not null); + if (triggerInfo.TriggerCharacter is not null && !info.Value.SignatureHelpService.IsTriggerCharacter(triggerInfo.TriggerCharacter.Value)) return null; } else if (triggerInfo.TriggerReason == SignatureHelpTriggerReason.RetriggerCommand) { - if (!(triggerInfo.TriggerCharacter is null) && !info.Value.SignatureHelpService.IsRetriggerCharacter(triggerInfo.TriggerCharacter.Value)) + if (triggerInfo.TriggerCharacter is not null && !info.Value.SignatureHelpService.IsRetriggerCharacter(triggerInfo.TriggerCharacter.Value)) return null; } @@ -165,14 +165,14 @@ void StartSession(SnapshotPoint triggerPosition, SignatureHelpResult signatureHe } var selectedSig = signatures.FirstOrDefault(a => a.IsSelected); - if (!(selectedSig is null)) + if (selectedSig is not null) session.SelectedSignature = selectedSig; } void Session_Dismissed(object? sender, EventArgs e) => Dispose(); void InitializeSignatures(ITrackingSpan applicableToSpan, SignatureHelpResult signatureHelpResult) { - Debug2.Assert(!(signatureHelpResult.Items is null)); + Debug2.Assert(signatureHelpResult.Items is not null); signatures.Clear(); foreach (var item in signatureHelpResult.Items.Items) { bool isSelected = signatureHelpResult.SelectedItem == item; @@ -194,7 +194,7 @@ public void Dispose() { return; isDisposed = true; CancelFetchItems(); - if (!(session is null)) { + if (session is not null) { session.Dismissed -= Session_Dismissed; session.Dismiss(); } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/SignatureHelpTaggerEx.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/SignatureHelpTaggerEx.cs index 17667448fe..2fa56a3395 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/SignatureHelpTaggerEx.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Intellisense/SignatureHelp/SignatureHelpTaggerEx.cs @@ -90,14 +90,14 @@ public SignatureHelpTaggerEx(ITextBuffer buffer, IThemeClassificationTypeService public IEnumerable> GetTags(NormalizedSnapshotSpanCollection spans) { var context = buffer.TryGetSignatureHelpClassifierContext(); - Debug2.Assert(!(context is null)); + Debug2.Assert(context is not null); if (context is null || context.Session.IsDismissed) yield break; if (context.Type == SignatureHelpClassifierContextTypes.ParameterName) { var paramContext = (ParameterNameSignatureHelpClassifierContext)context; var parameter = paramContext.Parameter as Parameter; - if (!(parameter?.Name is null)) { + if (parameter?.Name is not null) { var snapshot = buffer.CurrentSnapshot; var span = new Span(paramContext.NameOffset, parameter.Name.Length); Debug.Assert(span.End <= snapshot.Length); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Optimizations/FirstUseOptimization.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Optimizations/FirstUseOptimization.cs index 5923649d0f..bcc2db01dc 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Optimizations/FirstUseOptimization.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Optimizations/FirstUseOptimization.cs @@ -137,8 +137,8 @@ async Task InitializeAsync(ITextBuffer buffer, string code, MetadataReference[] { // Initialize completion code paths var info = CompletionInfo.Create(buffer.CurrentSnapshot); - Debug2.Assert(!(info is null)); - if (!(info is null)) { + Debug2.Assert(info is not null); + if (info is not null) { var completionTrigger = CompletionTrigger.Invoke; var completionList = await info.Value.CompletionService.GetCompletionsAsync(info.Value.Document, 0, completionTrigger); } @@ -147,8 +147,8 @@ async Task InitializeAsync(ITextBuffer buffer, string code, MetadataReference[] { // Initialize signature help code paths var info = SignatureHelpInfo.Create(buffer.CurrentSnapshot); - Debug2.Assert(!(info is null)); - if (!(info is null)) { + Debug2.Assert(info is not null); + if (info is not null) { int sigHelpIndex = code.IndexOf("sighelp"); Debug.Assert(sigHelpIndex >= 0); var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand); @@ -159,8 +159,8 @@ async Task InitializeAsync(ITextBuffer buffer, string code, MetadataReference[] { // Initialize quick info code paths var info = QuickInfoState.Create(buffer.CurrentSnapshot); - Debug2.Assert(!(info is null)); - if (!(info is null)) { + Debug2.Assert(info is not null); + if (info is not null) { int quickInfoIndex = code.IndexOf("Equals"); Debug.Assert(quickInfoIndex >= 0); var item = await info.Value.QuickInfoService.GetItemAsync(info.Value.Document, quickInfoIndex); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Text/Classification/RoslynClassificationTypes.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Text/Classification/RoslynClassificationTypes.cs index 15341767c2..89e2c4bb55 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Text/Classification/RoslynClassificationTypes.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Text/Classification/RoslynClassificationTypes.cs @@ -160,7 +160,7 @@ public sealed class RoslynClassificationTypes { public static RoslynClassificationTypes GetClassificationTypeInstance(IThemeClassificationTypeService themeClassificationTypeService) { if (classificationTypeInstance is null) Interlocked.CompareExchange(ref classificationTypeInstance, new RoslynClassificationTypes(themeClassificationTypeService), null); - Debug2.Assert(!(classificationTypeInstance is null)); + Debug2.Assert(classificationTypeInstance is not null); return classificationTypeInstance; } static RoslynClassificationTypes? classificationTypeInstance; diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Text/Classification/RoslynClassifier.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Text/Classification/RoslynClassifier.cs index 9ad5527af6..da3555073c 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Text/Classification/RoslynClassifier.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Text/Classification/RoslynClassifier.cs @@ -89,7 +89,7 @@ public RoslynClassifier(SyntaxNode syntaxRoot, SemanticModel semanticModel, Work public IEnumerable GetColors(TextSpan textSpan) { foreach (var cspan in Classifier.GetClassifiedSpans(semanticModel, textSpan, workspace)) { var color = GetClassificationType(cspan) ?? defaultColor; - if (!(color is null)) + if (color is not null) yield return new ClassifierResult(Span.FromBounds(cspan.TextSpan.Start, cspan.TextSpan.End), color); } } @@ -125,7 +125,7 @@ SymbolResult GetSymbolResult(TextSpan span) { object? GetClassificationType2(ClassifiedSpan cspan) { var symRes = GetSymbolResult(cspan.TextSpan); - if (!(symRes.Color is null)) + if (symRes.Color is not null) return symRes.Color; var symbol = symRes.Symbol; if (symbol is null) @@ -223,7 +223,7 @@ SymbolResult GetSymbolResult(TextSpan span) { return roslynClassificationTypes.ValueType; case TypeKind.TypeParameter: - if (!((symbol as ITypeParameterSymbol)?.DeclaringMethod is null)) + if ((symbol as ITypeParameterSymbol)?.DeclaringMethod is not null) return roslynClassificationTypes.MethodGenericParameter; return roslynClassificationTypes.TypeGenericParameter; @@ -256,7 +256,7 @@ SymbolResult GetSymbolResult(TextSpan span) { return roslynClassificationTypes.Local; case SymbolKind.TypeParameter: - return !((symbol as ITypeParameterSymbol)?.DeclaringMethod is null) ? + return (symbol as ITypeParameterSymbol)?.DeclaringMethod is not null ? roslynClassificationTypes.MethodGenericParameter : roslynClassificationTypes.TypeGenericParameter; case SymbolKind.Preprocessing: @@ -300,7 +300,7 @@ SymbolResult GetSymbolResult(TextSpan span) { case ClassificationTypeNames.ClassName: symRes = GetSymbolResult(cspan.TextSpan); - if (!(symRes.Color is null)) + if (symRes.Color is not null) return symRes.Color; if (symRes.Symbol?.IsStatic == true) return roslynClassificationTypes.StaticType; diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Text/RoslynMefHostServices.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Text/RoslynMefHostServices.cs index e76025c37b..4e9d4bab75 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Text/RoslynMefHostServices.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Text/RoslynMefHostServices.cs @@ -37,7 +37,7 @@ public static MefHostServices DefaultServices { get { if (defaultServices is null) Interlocked.CompareExchange(ref defaultServices, CreateDefaultServices(), null); - Debug2.Assert(!(defaultServices is null)); + Debug2.Assert(defaultServices is not null); return defaultServices; } } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/AsyncTagger.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/AsyncTagger.cs index 64996fb118..a34c6765a9 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/AsyncTagger.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/AsyncTagger.cs @@ -189,7 +189,7 @@ protected AsyncTagger() { } protected void RefreshAllTags(ITextSnapshot snapshot) { - Debug2.Assert(!(snapshot is null)); + Debug2.Assert(snapshot is not null); if (snapshot is null) return; lock (lockObj) { @@ -221,7 +221,7 @@ public IEnumerable> GetTags(NormalizedSnapshotSpanCollection lastSnapshotState = new SnapshotState(snapshot); lastSnapshotState.AddRef(); } - Debug2.Assert(!(lastSnapshotState is null)); + Debug2.Assert(lastSnapshotState is not null); foreach (var span in spans) { if (cachedTags.TryGetValue(span.Start.Position, out var tags)) { @@ -247,9 +247,9 @@ public IEnumerable> GetTags(NormalizedSnapshotSpanCollection Debug2.Assert(multipleResults is null || multipleResults.Count >= 2); Debug2.Assert(multipleMissingSpans is null || multipleMissingSpans.Count >= 2); - if (!(singleMissingSpan is null)) { + if (singleMissingSpan is not null) { if (spans.Count != (multipleMissingSpans?.Count ?? 1)) { - spans = !(multipleMissingSpans is null) ? + spans = multipleMissingSpans is not null ? new NormalizedSnapshotSpanCollection(multipleMissingSpans) : new NormalizedSnapshotSpanCollection(singleMissingSpan.Value); } diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/RoslynTagger.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/RoslynTagger.cs index fa6d68c2be..90c614e4c4 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/RoslynTagger.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/RoslynTagger.cs @@ -62,7 +62,7 @@ public IEnumerable> GetTags(NormalizedSnapshotSpanC Initialize(asyncState, snapshot, cancellationToken).Wait(cancellationToken); if (!asyncState.IsValid) yield break; - Debug2.Assert(!(asyncState.SyntaxRoot is null) && !(asyncState.SemanticModel is null) && !(asyncState.Workspace is null)); + Debug2.Assert(asyncState.SyntaxRoot is not null && asyncState.SemanticModel is not null && asyncState.Workspace is not null); var classifier = new RoslynClassifier(asyncState.SyntaxRoot, asyncState.SemanticModel, asyncState.Workspace, roslynClassificationTypes, defaultClassificationType, cancellationToken); foreach (var span in spans) { @@ -80,7 +80,7 @@ protected override async Task GetTagsAsync(GetTagsState state, NormalizedSnapsho await Initialize(state.UserAsyncState, snapshot, state.CancellationToken).ConfigureAwait(false); if (!state.UserAsyncState.IsValid) return; - Debug2.Assert(!(state.UserAsyncState.SyntaxRoot is null) && !(state.UserAsyncState.SemanticModel is null) && !(state.UserAsyncState.Workspace is null)); + Debug2.Assert(state.UserAsyncState.SyntaxRoot is not null && state.UserAsyncState.SemanticModel is not null && state.UserAsyncState.Workspace is not null); var classifier = new RoslynClassifier(state.UserAsyncState.SyntaxRoot, state.UserAsyncState.SemanticModel, state.UserAsyncState.Workspace, roslynClassificationTypes, defaultClassificationType, state.CancellationToken); state.UserAsyncState.TagsList.Clear(); diff --git a/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/RoslynTaggerAsyncState.cs b/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/RoslynTaggerAsyncState.cs index ea22a5e90e..6d5c1883d5 100644 --- a/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/RoslynTaggerAsyncState.cs +++ b/dnSpy/Roslyn/dnSpy.Roslyn/Text/Tagging/RoslynTaggerAsyncState.cs @@ -25,7 +25,7 @@ namespace dnSpy.Roslyn.Text.Tagging { sealed class RoslynTaggerAsyncState { public RoslynTaggerAsyncState() { } - public bool IsValid => !(SyntaxRoot is null) && !(SemanticModel is null) && !(Workspace is null); + public bool IsValid => SyntaxRoot is not null && SemanticModel is not null && Workspace is not null; public bool IsInitialized { get; private set; } public SyntaxNode? SyntaxRoot { get; private set; } public SemanticModel? SemanticModel { get; private set; } diff --git a/dnSpy/dnSpy.Console/Program.cs b/dnSpy/dnSpy.Console/Program.cs index e074a29445..92369d3e87 100644 --- a/dnSpy/dnSpy.Console/Program.cs +++ b/dnSpy/dnSpy.Console/Program.cs @@ -80,7 +80,7 @@ sealed class ColorProvider { readonly Dictionary colors = new Dictionary(); public void Add(TextColor color, ConsoleColor? foreground, ConsoleColor? background = null) { - if (!(foreground is null) || !(background is null)) + if (foreground is not null || background is not null) colors[color] = new ConsoleColorPair(foreground, background); } @@ -134,10 +134,10 @@ void AddText(string text, object color) { if (addIndent) AddIndent(); var colorPair = colorProvider.GetColor(color as TextColor?); - if (!(colorPair is null)) { - if (!(colorPair.Value.Foreground is null)) + if (colorPair is not null) { + if (colorPair.Value.Foreground is not null) Console.ForegroundColor = colorPair.Value.Foreground.Value; - if (!(colorPair.Value.Background is null)) + if (colorPair.Value.Background is not null) Console.BackgroundColor = colorPair.Value.Background.Value; writer.Write(text); Console.ResetColor(); @@ -212,7 +212,7 @@ public DnSpyDecompiler() { assemblyResolver.FindExactMatch = true; // Same as dnSpy.exe assemblyResolver.EnableTypeDefCache = true; bamlDecompiler = TryLoadBamlDecompiler(); - decompileBaml = !(bamlDecompiler is null); + decompileBaml = bamlDecompiler is not null; reservedOptions = GetReservedOptions(); colorizeOutput = !Console.IsOutputRedirected; @@ -234,7 +234,7 @@ static IEnumerable GetAllLanguages() { static IEnumerable GetLanguagesInAssembly(string asmName) { var asm = TryLoad(asmName); - if (!(asm is null)) { + if (asm is not null) { foreach (var type in asm.GetTypes()) { if (!type.IsAbstract && !type.IsInterface && typeof(IDecompilerProvider).IsAssignableFrom(type)) { var p = (IDecompilerProvider)Activator.CreateInstance(type)!; @@ -290,7 +290,7 @@ void PrintHelp() { Console.WriteLine(); foreach (var info in usageInfos) { var arg = info.Option; - if (!(info.OptionArgument is null)) + if (info.OptionArgument is not null) arg = arg + " " + info.OptionArgument; Console.WriteLine(" {0,-12} {1}", arg, string.Format(info.Description, PATHS_SEP)); } @@ -372,7 +372,7 @@ public HelpInfo(string description, string commandLine) { string GetOptionName(IDecompilerOption opt, string? extraPrefix = null) { var prefix = "--" + extraPrefix; - var o = prefix + FixInvalidSwitchChars((!(opt.Name is null) ? opt.Name : opt.Guid.ToString())); + var o = prefix + FixInvalidSwitchChars((opt.Name is not null ? opt.Name : opt.Guid.ToString())); if (reservedOptions.Contains(o)) o = prefix + FixInvalidSwitchChars(opt.Guid.ToString()); return o; @@ -394,7 +394,7 @@ List> GetLanguageOptions() { } void Dump(Exception? ex) { - while (!(ex is null)) { + while (ex is not null) { Console.WriteLine(dnSpy_Console_Resources.Error1, ex.GetType()); Console.WriteLine(" {0}", ex.Message); Console.WriteLine(" {0}", ex.StackTrace); @@ -621,7 +621,7 @@ void ParseCommandLine(string[] args) { default: (IDecompilerOption option, Action setOptionValue) tuple; - Debug2.Assert(!(langDict is null)); + Debug2.Assert(langDict is not null); if (langDict.TryGetValue(arg, out tuple)) { bool hasArg = tuple.option.Type != typeof(bool); if (hasArg && next is null) @@ -695,19 +695,19 @@ void Decompile() { foreach (var file in files.OrderBy(a => a.Module.Location, StringComparer.InvariantCultureIgnoreCase)) file.ProjectGuid = new Guid(string.Format(guidFormat, guidNum++)); - if (mdToken != 0 || !(typeName is null)) { + if (mdToken != 0 || typeName is not null) { if (files.Count == 0) throw new ErrorException(dnSpy_Console_Resources.MissingDotNetFilename); if (files.Count != 1) throw new ErrorException(dnSpy_Console_Resources.OnlyOneFileCanBeDecompiled); IMemberDef? member; - if (!(typeName is null)) + if (typeName is not null) member = FindType(files[0].Module, typeName); else member = files[0].Module.ResolveToken(mdToken) as IMemberDef; if (member is null) { - if (!(typeName is null)) + if (typeName is not null) throw new ErrorException(string.Format(dnSpy_Console_Resources.CouldNotFindTypeX, typeName)); throw new ErrorException(dnSpy_Console_Resources.InvalidToken); } @@ -825,7 +825,7 @@ IEnumerable GetDotNetFiles() { var path = Path.GetDirectoryName(file); var name = Path.GetFileName(file); if (Directory.Exists(path)) { - Debug2.Assert(!(path is null)); + Debug2.Assert(path is not null); foreach (var info in DumpDir(path, name)) yield return info; } @@ -889,7 +889,7 @@ IEnumerable GetDirs(string path) { } catch (SecurityException) { } - if (!(di is null)) + if (di is not null) yield return di; } } @@ -898,7 +898,7 @@ IEnumerable DumpDir2(string path, string pattern) { pattern ??= "*"; foreach (var fi in GetFiles(path, pattern)) { var info = OpenNetFile(fi.FullName); - if (!(info is null)) + if (info is not null) yield return info; } } @@ -930,7 +930,7 @@ IEnumerable GetFiles(string path, string pattern) { } catch (SecurityException) { } - if (!(fi is null)) + if (fi is not null) yield return fi; } } @@ -955,14 +955,14 @@ ProjectModuleOptions CreateProjectModuleOptions(ModuleDef mod) { proj.DontReferenceStdLib = !addCorlibRef; proj.UnpackResources = unpackResources; proj.CreateResX = createResX; - proj.DecompileXaml = decompileBaml && !(bamlDecompiler is null); + proj.DecompileXaml = decompileBaml && bamlDecompiler is not null; var o = BamlDecompilerOptions.Create(GetLanguage()); var outputOptions = new XamlOutputOptions { IndentChars = "\t", NewLineChars = Environment.NewLine, NewLineOnAttributes = true, }; - if (!(bamlDecompiler is null)) + if (bamlDecompiler is not null) proj.DecompileBaml = (a, b, c, d) => bamlDecompiler.Decompile(a, b, c, o, d, outputOptions); return proj; } diff --git a/dnSpy/dnSpy.Contracts.Debugger.DotNet/Code/DbgMethodDebugInfo.cs b/dnSpy/dnSpy.Contracts.Debugger.DotNet/Code/DbgMethodDebugInfo.cs index f415d21be5..795a758398 100644 --- a/dnSpy/dnSpy.Contracts.Debugger.DotNet/Code/DbgMethodDebugInfo.cs +++ b/dnSpy/dnSpy.Contracts.Debugger.DotNet/Code/DbgMethodDebugInfo.cs @@ -108,7 +108,7 @@ public DbgILSpan[] GetRanges(DbgILSpan[] sourceILSpans) { public DbgILSpan[] GetUnusedRanges() => GetUnusedILSpans(); DbgILSpan[] GetUnusedILSpans() { - if (!(cachedUnusedILSpans is null)) + if (cachedUnusedILSpans is not null) return cachedUnusedILSpans; var list = new List(Statements.Length); foreach (var s in Statements) @@ -169,7 +169,7 @@ static int GetCodeSize(CilBody? body) { public DbgILSpan[] GetILSpansOfStatement(DbgTextSpan statementSpan) { if (statementsDict is null) Interlocked.CompareExchange(ref statementsDict, CreateStatementsDict(Statements), null); - Debug2.Assert(!(statementsDict is null)); + Debug2.Assert(statementsDict is not null); if (statementsDict.TryGetValue(statementSpan, out var list)) { var spans = list.ToArray(); #if DEBUG @@ -211,7 +211,7 @@ public void Add(T value) { } public T[] ToArray() { - if (!(list is null)) + if (list is not null) return list.ToArray(); if (hasFirstValue) return new[] { firstValue }; diff --git a/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/DbgDotNetRuntimeExtensions.cs b/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/DbgDotNetRuntimeExtensions.cs index 8415b245bc..c9b08de28c 100644 --- a/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/DbgDotNetRuntimeExtensions.cs +++ b/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/DbgDotNetRuntimeExtensions.cs @@ -33,7 +33,7 @@ public static class DbgDotNetRuntimeExtensions { /// public static IDbgDotNetRuntime GetDotNetRuntime(this DbgRuntime runtime) { var dnRuntime = runtime.InternalRuntime as IDbgDotNetRuntime; - Debug2.Assert(!(dnRuntime is null)); + Debug2.Assert(dnRuntime is not null); if (dnRuntime is null) throw new InvalidOperationException(nameof(DbgRuntime.InternalRuntime) + " must implement " + nameof(IDbgDotNetRuntime)); return dnRuntime; diff --git a/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/DbgDotNetValueResult.cs b/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/DbgDotNetValueResult.cs index 6816dd5645..e728530b77 100644 --- a/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/DbgDotNetValueResult.cs +++ b/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/DbgDotNetValueResult.cs @@ -43,7 +43,7 @@ public readonly struct DbgDotNetValueResult { /// /// true if there was an error, see /// - public bool HasError => !(ErrorMessage is null); + public bool HasError => ErrorMessage is not null; /// /// true if there's no error and no exception was thrown diff --git a/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/ExpressionCompiler/DbgDotNetCompilationResult.cs b/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/ExpressionCompiler/DbgDotNetCompilationResult.cs index 7fb221e913..a17ca14ed1 100644 --- a/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/ExpressionCompiler/DbgDotNetCompilationResult.cs +++ b/dnSpy/dnSpy.Contracts.Debugger.DotNet/Evaluation/ExpressionCompiler/DbgDotNetCompilationResult.cs @@ -31,7 +31,7 @@ public readonly struct DbgDotNetCompilationResult { /// /// true if it has an error message () /// - public bool IsError => !(ErrorMessage is null); + public bool IsError => ErrorMessage is not null; /// /// Gets the error message or null if there was no error diff --git a/dnSpy/dnSpy.Contracts.Debugger.DotNet/Text/DbgDotNetTextOutput.cs b/dnSpy/dnSpy.Contracts.Debugger.DotNet/Text/DbgDotNetTextOutput.cs index e69292b482..d28f97c515 100644 --- a/dnSpy/dnSpy.Contracts.Debugger.DotNet/Text/DbgDotNetTextOutput.cs +++ b/dnSpy/dnSpy.Contracts.Debugger.DotNet/Text/DbgDotNetTextOutput.cs @@ -38,7 +38,7 @@ public sealed class DbgDotNetTextOutput : IDbgTextWriter { /// Color /// Text public void Write(DbgTextColor color, string? text) { - if (!(text is null)) + if (text is not null) list.Add(new DbgDotNetTextPart(color, text)); } diff --git a/dnSpy/dnSpy.Contracts.Debugger/Breakpoints/Code/FilterExpressionEvaluator/DbgFilterExpressionEvaluator.cs b/dnSpy/dnSpy.Contracts.Debugger/Breakpoints/Code/FilterExpressionEvaluator/DbgFilterExpressionEvaluator.cs index 3d4c464da4..9faa8ec210 100644 --- a/dnSpy/dnSpy.Contracts.Debugger/Breakpoints/Code/FilterExpressionEvaluator/DbgFilterExpressionEvaluator.cs +++ b/dnSpy/dnSpy.Contracts.Debugger/Breakpoints/Code/FilterExpressionEvaluator/DbgFilterExpressionEvaluator.cs @@ -68,7 +68,7 @@ public readonly struct DbgFilterExpressionEvaluatorResult { /// /// true if there was an error /// - public bool HasError => !(Error is null); + public bool HasError => Error is not null; /// /// Constructor diff --git a/dnSpy/dnSpy.Contracts.Debugger/DbgMessageEventArgs.cs b/dnSpy/dnSpy.Contracts.Debugger/DbgMessageEventArgs.cs index 93a72ca316..a849279d6b 100644 --- a/dnSpy/dnSpy.Contracts.Debugger/DbgMessageEventArgs.cs +++ b/dnSpy/dnSpy.Contracts.Debugger/DbgMessageEventArgs.cs @@ -601,7 +601,7 @@ public sealed class DbgMessageStepCompleteEventArgs : DbgMessageEventArgs { /// /// true if there was an error. Error message is in /// - public bool HasError => !(Error is null); + public bool HasError => Error is not null; /// /// Constructor @@ -646,7 +646,7 @@ public sealed class DbgMessageSetIPCompleteEventArgs : DbgMessageEventArgs { /// /// true if there was an error. Error message is in /// - public bool HasError => !(Error is null); + public bool HasError => Error is not null; /// /// Constructor diff --git a/dnSpy/dnSpy.Contracts.Debugger/DbgObject.cs b/dnSpy/dnSpy.Contracts.Debugger/DbgObject.cs index 791c9e9939..c94ccb1e60 100644 --- a/dnSpy/dnSpy.Contracts.Debugger/DbgObject.cs +++ b/dnSpy/dnSpy.Contracts.Debugger/DbgObject.cs @@ -119,7 +119,7 @@ public void Close(DbgDispatcher dispatcher) { /// public bool TryGetData([NotNullWhen(true)] out T? value) where T : class { lock (lockObj) { - if (!(dataList is null)) { + if (dataList is not null) { var type = typeof(T).TypeHandle; foreach (var kv in dataList) { if (kv.key.Equals(type)) { diff --git a/dnSpy/dnSpy.Contracts.Debugger/Evaluation/DbgValueNode.cs b/dnSpy/dnSpy.Contracts.Debugger/Evaluation/DbgValueNode.cs index 1ec36a7d0f..5a21bf4a11 100644 --- a/dnSpy/dnSpy.Contracts.Debugger/Evaluation/DbgValueNode.cs +++ b/dnSpy/dnSpy.Contracts.Debugger/Evaluation/DbgValueNode.cs @@ -44,7 +44,7 @@ public abstract class DbgValueNode : DbgObject { /// /// true if this is an error value node /// - public bool HasError => !(ErrorMessage is null); + public bool HasError => ErrorMessage is not null; /// /// Gets the error message or null @@ -54,7 +54,7 @@ public abstract class DbgValueNode : DbgObject { /// /// true if is not null /// - public bool HasValue => !(Value is null); + public bool HasValue => Value is not null; /// /// Gets the value or null if there's none diff --git a/dnSpy/dnSpy.Contracts.Debugger/Evaluation/PredefinedFormatSpecifiers.cs b/dnSpy/dnSpy.Contracts.Debugger/Evaluation/PredefinedFormatSpecifiers.cs index 83257dd2a6..270b3f655c 100644 --- a/dnSpy/dnSpy.Contracts.Debugger/Evaluation/PredefinedFormatSpecifiers.cs +++ b/dnSpy/dnSpy.Contracts.Debugger/Evaluation/PredefinedFormatSpecifiers.cs @@ -182,7 +182,7 @@ public static class PredefinedFormatSpecifiers { /// Default options /// public static DbgValueFormatterOptions GetValueFormatterOptions(ReadOnlyCollection? formatSpecifiers, DbgValueFormatterOptions options) { - if (!(formatSpecifiers is null)) { + if (formatSpecifiers is not null) { for (int i = 0; i < formatSpecifiers.Count; i++) { switch (formatSpecifiers[i]) { case Decimal: @@ -252,7 +252,7 @@ public static DbgValueFormatterOptions GetValueFormatterOptions(ReadOnlyCollecti /// Default options /// public static DbgValueFormatterTypeOptions GetValueFormatterTypeOptions(ReadOnlyCollection? formatSpecifiers, DbgValueFormatterTypeOptions options) { - if (!(formatSpecifiers is null)) { + if (formatSpecifiers is not null) { for (int i = 0; i < formatSpecifiers.Count; i++) { switch (formatSpecifiers[i]) { case Decimal: @@ -298,7 +298,7 @@ public static DbgValueFormatterTypeOptions GetValueFormatterTypeOptions(ReadOnly /// Default options /// public static DbgValueNodeEvaluationOptions GetValueNodeEvaluationOptions(ReadOnlyCollection? formatSpecifiers, DbgValueNodeEvaluationOptions options) { - if (!(formatSpecifiers is null)) { + if (formatSpecifiers is not null) { for (int i = 0; i < formatSpecifiers.Count; i++) { switch (formatSpecifiers[i]) { case DynamicView: diff --git a/dnSpy/dnSpy.Contracts.Debugger/Exceptions/DbgExceptionSettings.cs b/dnSpy/dnSpy.Contracts.Debugger/Exceptions/DbgExceptionSettings.cs index a429a811bb..922f1f96aa 100644 --- a/dnSpy/dnSpy.Contracts.Debugger/Exceptions/DbgExceptionSettings.cs +++ b/dnSpy/dnSpy.Contracts.Debugger/Exceptions/DbgExceptionSettings.cs @@ -91,7 +91,7 @@ static bool Equals(ReadOnlyCollection? a, ReadOnl /// public override int GetHashCode() { int hc = (int)Flags; - if (!(Conditions is null)) { + if (Conditions is not null) { foreach (var c in Conditions) hc ^= (int)c.ConditionType ^ StringComparer.Ordinal.GetHashCode(c.Condition ?? string.Empty); } diff --git a/dnSpy/dnSpy.Contracts.Debugger/Steppers/DbgStepper.cs b/dnSpy/dnSpy.Contracts.Debugger/Steppers/DbgStepper.cs index 36532f12f9..6cde6f6a74 100644 --- a/dnSpy/dnSpy.Contracts.Debugger/Steppers/DbgStepper.cs +++ b/dnSpy/dnSpy.Contracts.Debugger/Steppers/DbgStepper.cs @@ -90,7 +90,7 @@ public readonly struct DbgStepCompleteEventArgs { /// /// true if there was an error /// - public bool HasError => !(Error is null); + public bool HasError => Error is not null; /// /// Constructor diff --git a/dnSpy/dnSpy.Contracts.DnSpy/App/MsgBox.cs b/dnSpy/dnSpy.Contracts.DnSpy/App/MsgBox.cs index 6f8ec6cf54..4caff2ff1b 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/App/MsgBox.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/App/MsgBox.cs @@ -30,7 +30,7 @@ public static class MsgBox { // "MessageBox" is used by WPF public static IMessageBoxService Instance { get => messageBoxService ?? throw new InvalidOperationException(); internal set { - if (!(messageBoxService is null)) + if (messageBoxService is not null) throw new InvalidOperationException(); messageBoxService = value ?? throw new ArgumentNullException(nameof(value)); } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/AsmEditor/Compiler/CompilationResult.cs b/dnSpy/dnSpy.Contracts.DnSpy/AsmEditor/Compiler/CompilationResult.cs index 2ed2df1042..d50db72680 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/AsmEditor/Compiler/CompilationResult.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/AsmEditor/Compiler/CompilationResult.cs @@ -28,7 +28,7 @@ public readonly struct CompilationResult { /// /// true if the compilation succeeded /// - public bool Success => !(RawFile is null); + public bool Success => RawFile is not null; /// /// Result of compilation or null if compilation failed diff --git a/dnSpy/dnSpy.Contracts.DnSpy/AsmEditor/Compiler/CompilerDiagnostic.cs b/dnSpy/dnSpy.Contracts.DnSpy/AsmEditor/Compiler/CompilerDiagnostic.cs index 170cee3aed..ef24d87e84 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/AsmEditor/Compiler/CompilerDiagnostic.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/AsmEditor/Compiler/CompilerDiagnostic.cs @@ -80,7 +80,7 @@ public CompilerDiagnostic(CompilerDiagnosticSeverity severity, string descriptio public override string ToString() { var sb = new StringBuilder(); sb.Append(Filename ?? "???"); - if (!(LineLocationSpan is null)) + if (LineLocationSpan is not null) sb.Append(LineLocationSpan.Value.StartLinePosition.ToString()); sb.Append(": "); switch (Severity) { diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Bookmarks/BMObject.cs b/dnSpy/dnSpy.Contracts.DnSpy/Bookmarks/BMObject.cs index 79d7ab3734..c70514e4be 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Bookmarks/BMObject.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Bookmarks/BMObject.cs @@ -114,7 +114,7 @@ public void Close() { /// public bool TryGetData([NotNullWhen(true)] out T? value) where T : class { lock (lockObj) { - if (!(dataList is null)) { + if (dataList is not null) { var type = typeof(T).TypeHandle; foreach (var kv in dataList) { if (kv.key.Equals(type)) { diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Controls/FastTextBlock.cs b/dnSpy/dnSpy.Contracts.DnSpy/Controls/FastTextBlock.cs index a708f9f371..3c5ff63d0a 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Controls/FastTextBlock.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Controls/FastTextBlock.cs @@ -124,8 +124,8 @@ class TextSrc : TextSource, IFastTextSource { #pragma warning restore CS8618 // Non-nullable field is uninitialized. public override TextRun GetTextRun(int textSourceCharacterIndex) { - Debug2.Assert(!(text is null)); - Debug2.Assert(!(props is null)); + Debug2.Assert(text is not null); + Debug2.Assert(props is not null); if (textSourceCharacterIndex >= text.Length) { return new TextEndOfParagraph(1); } @@ -182,7 +182,7 @@ void MakeNewText() { if (fmt is null) fmt = TextFormatterFactory.GetTextFormatter(this); - if (!(line is null)) + if (line is not null) line.Dispose(); src.UpdateParent(this); @@ -200,13 +200,13 @@ void EnsureText() { protected override Size MeasureOverride(Size availableSize) { EnsureText(); - Debug2.Assert(!(line is null)); + Debug2.Assert(line is not null); return new Size(line.Width, line.Height); } protected override void OnRender(DrawingContext drawingContext) { EnsureText(); - Debug2.Assert(!(line is null)); + Debug2.Assert(line is not null); line.Draw(drawingContext, new Point(0, 0), InvertAxes.None); } } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Controls/MetroWindow.cs b/dnSpy/dnSpy.Contracts.DnSpy/Controls/MetroWindow.cs index 6fa775164e..5f7bb10c11 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Controls/MetroWindow.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Controls/MetroWindow.cs @@ -61,8 +61,8 @@ protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); var hwndSource = PresentationSource.FromVisual(this) as HwndSource; - Debug2.Assert(!(hwndSource is null)); - if (!(hwndSource is null)) { + Debug2.Assert(hwndSource is not null); + if (hwndSource is not null) { hwndSource.AddHook(WndProc); wpfDpi = new Size(96.0 * hwndSource.CompositionTarget.TransformToDevice.M11, 96.0 * hwndSource.CompositionTarget.TransformToDevice.M22); @@ -218,7 +218,7 @@ public ImageReference SystemMenuImage { static void OnMaximizedElementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var border = d as Border; - Debug2.Assert(!(border is null)); + Debug2.Assert(border is not null); if (border is null) return; var win = Window.GetWindow(border) as MetroWindow; @@ -252,7 +252,7 @@ void border_Loaded(object? sender, RoutedEventArgs e) { void MetroWindow_StateChanged(object? sender, EventArgs e) => UpdatePadding((MetroWindow)sender!); void UpdatePadding(MetroWindow window) { - Debug2.Assert(!(window is null)); + Debug2.Assert(window is not null); var state = window.IsFullScreen ? WindowState.Maximized : window.WindowState; switch (state) { diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Controls/ToolWindows/EditValueControl.xaml.cs b/dnSpy/dnSpy.Contracts.DnSpy/Controls/ToolWindows/EditValueControl.xaml.cs index a69507764c..a692a0d7ed 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Controls/ToolWindows/EditValueControl.xaml.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Controls/ToolWindows/EditValueControl.xaml.cs @@ -177,7 +177,7 @@ void OnIsEditingValueChanged(IEditableValue? editableValue) { static UIElement GetUIElement(object? obj) => obj as UIElement ?? new ContentPresenter { Content = obj }; void CancelEdit(IEditableValue? editableValue) { - if (!(editableValue is null)) + if (editableValue is not null) editableValue.IsEditingValue = false; RemoveEditControl(); } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Controls/ToolWindows/ListBoxSelectedItemsAP.cs b/dnSpy/dnSpy.Contracts.DnSpy/Controls/ToolWindows/ListBoxSelectedItemsAP.cs index 8c8a65e008..8f34ca6b40 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Controls/ToolWindows/ListBoxSelectedItemsAP.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Controls/ToolWindows/ListBoxSelectedItemsAP.cs @@ -70,31 +70,31 @@ void Initialize(ListBox listBox, IList vmColl, INotifyCollectionChanged vmCollNc } void UnregisterEvents() { - if (!(listBox is null)) + if (listBox is not null) listBox.SelectionChanged -= ListBox_SelectionChanged; - if (!(vmCollNcc is null)) + if (vmCollNcc is not null) vmCollNcc.CollectionChanged -= VmCollNcc_CollectionChanged; } void RegisterEvents() { - Debug2.Assert(!(listBox is null)); - Debug2.Assert(!(vmCollNcc is null)); + Debug2.Assert(listBox is not null); + Debug2.Assert(vmCollNcc is not null); listBox.SelectionChanged += ListBox_SelectionChanged; vmCollNcc.CollectionChanged += VmCollNcc_CollectionChanged; } void ListBox_SelectionChanged(object? sender, SelectionChangedEventArgs e) { - Debug2.Assert(!(listBox is null)); - Debug2.Assert(!(vmColl is null)); + Debug2.Assert(listBox is not null); + Debug2.Assert(vmColl is not null); if (ListBox_SelectionChanged_ignoreCalls) return; try { VmCollNcc_CollectionChanged_ignoreCalls = true; - if (!(e.AddedItems is null)) { + if (e.AddedItems is not null) { foreach (var vmItem in e.AddedItems) vmColl.Add(vmItem); } - if (!(e.RemovedItems is null)) { + if (e.RemovedItems is not null) { foreach (var vmItem in e.RemovedItems) vmColl.Remove(vmItem); } @@ -107,23 +107,23 @@ void ListBox_SelectionChanged(object? sender, SelectionChangedEventArgs e) { bool VmCollNcc_CollectionChanged_ignoreCalls; void VmCollNcc_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { - Debug2.Assert(!(listBox is null)); + Debug2.Assert(listBox is not null); if (VmCollNcc_CollectionChanged_ignoreCalls) return; try { ListBox_SelectionChanged_ignoreCalls = true; switch (e.Action) { case NotifyCollectionChangedAction.Add: - Debug2.Assert(!(e.NewItems is null)); - if (!(e.NewItems is null)) { + Debug2.Assert(e.NewItems is not null); + if (e.NewItems is not null) { foreach (var item in e.NewItems) listBox.SelectedItems.Add(item); } break; case NotifyCollectionChangedAction.Remove: - Debug2.Assert(!(e.OldItems is null)); - if (!(e.OldItems is null)) { + Debug2.Assert(e.OldItems is not null); + if (e.OldItems is not null) { foreach (var item in e.OldItems) listBox.SelectedItems.Remove(item); } @@ -131,7 +131,7 @@ void VmCollNcc_CollectionChanged(object? sender, NotifyCollectionChangedEventArg case NotifyCollectionChangedAction.Reset: listBox.SelectedItems.Clear(); - if (!(e.NewItems is null)) { + if (e.NewItems is not null) { foreach (var item in e.NewItems) listBox.SelectedItems.Add(item); } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/AnnotationsImpl.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/AnnotationsImpl.cs index 6b8e4a6145..65c0c4351b 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/AnnotationsImpl.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/AnnotationsImpl.cs @@ -23,7 +23,7 @@ You should have received a copy of the GNU General Public License namespace dnSpy.Contracts.Documents { sealed class AnnotationsImpl : IAnnotations { public T? AddAnnotation(T? annotation) where T : class { - if (!(annotation is null)) + if (annotation is not null) list.Add(annotation); return annotation; } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/DsDocument.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/DsDocument.cs index 1155960f68..3187ec5053 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/DsDocument.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/DsDocument.cs @@ -69,7 +69,7 @@ public TList Children { lock (lockObj) { if (children is null) { children = CreateChildren(); - Debug2.Assert(!(children is null)); + Debug2.Assert(children is not null); if (children is null) children = new TList(); } @@ -82,7 +82,7 @@ public TList Children { TList? children; /// - public bool ChildrenLoaded => !(children is null); + public bool ChildrenLoaded => children is not null; /// /// Creates the children @@ -197,10 +197,10 @@ public static ModuleContext CreateModuleContext(IAssemblyResolver asmResolver) { } void LoadSymbols() { - Debug2.Assert(!(ModuleDef is null)); + Debug2.Assert(ModuleDef is not null); // Happens if a module has been removed but then the exact same instance // was re-added. - if (!(ModuleDef.PdbState is null)) + if (ModuleDef.PdbState is not null) return; var m = ModuleDef as ModuleDefMD; @@ -275,7 +275,7 @@ protected override void OnPropertyChanged(string propName) { protected override TList CreateChildren() { var asm = AssemblyDef; var list = new TList(asm is null ? 1 : asm.Modules.Count); - if (isAsmNode && !(asm is null)) { + if (isAsmNode && asm is not null) { bool foundThis = false; foreach (var module in asm.Modules) { if (ModuleDef == module) { @@ -300,9 +300,9 @@ public DsDotNetDocumentAsmWithMod(IDsDotNetDocument modmodule) : base(modmodule.SerializedDocument ?? new DsDocumentInfo(), modmodule.ModuleDef!, false, true) => module = modmodule; protected override TList CreateChildren() { - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); var list = new TList(); - if (!(module is null)) + if (module is not null) list.Add(module); module = null; return list; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/FilenameKey.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/FilenameKey.cs index 1c9a467ac1..0857ae9bbd 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/FilenameKey.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/FilenameKey.cs @@ -55,7 +55,7 @@ static string GetFullPath(string filename) { /// /// Other instance /// - public bool Equals(FilenameKey? other) => !(other is null) && StringComparer.OrdinalIgnoreCase.Equals(filename, other.filename); + public bool Equals(FilenameKey? other) => other is not null && StringComparer.OrdinalIgnoreCase.Equals(filename, other.filename); /// /// Equals() diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/IDsDocument.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/IDsDocument.cs index 2a17252c60..7165fbcaec 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/IDsDocument.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/IDsDocument.cs @@ -158,7 +158,7 @@ public static IEnumerable NonLoadedDescendantsAndSelf(this IDsDocum static IEnumerable GetModules(HashSet hash, IEnumerable documents) where T : ModuleDef { foreach (var f in documents.SelectMany(f => f.NonLoadedDescendantsAndSelf())) { var mod = f.ModuleDef as T; - if (!(mod is null) && !hash.Contains(mod)) { + if (mod is not null && !hash.Contains(mod)) { hash.Add(mod); yield return mod; } @@ -167,7 +167,7 @@ static IEnumerable GetModules(HashSet hash, IEnumerable do continue; foreach (var m in asm.Modules) { mod = m as T; - if (!(mod is null) && !hash.Contains(mod)) { + if (mod is not null && !hash.Contains(mod)) { hash.Add(mod); yield return mod; } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/DocumentTreeNodeData.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/DocumentTreeNodeData.cs index 1e314bac03..bd01a1f6f7 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/DocumentTreeNodeData.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/DocumentTreeNodeData.cs @@ -233,7 +233,7 @@ static void Filter(DocumentTreeNodeData? node) { node.FilterVersion = node.Context.FilterVersion; node.TreeNode.IsHidden = false; var fnode = node as DocumentTreeNodeData; - if (!(fnode is null) && fnode.refilter && node.TreeNode.Children.Count > 0) + if (fnode is not null && fnode.refilter && node.TreeNode.Children.Count > 0) node.OnEnsureChildrenLoaded(); break; @@ -388,7 +388,7 @@ protected void WriteMemberRef(ITextColorWriter output, IDecompiler decompiler, I /// Updated with the data if successful /// public bool TryGetData([NotNullWhen(true)] out T? data) where T : class { - if (!(dataList is null)) { + if (dataList is not null) { foreach (var obj in dataList) { if (obj is T t) { data = t; @@ -448,7 +448,7 @@ public static class DocumentTreeNodeDataExtensionMethods { /// public static DsDocumentNode? GetTopNode(this TreeNodeData? self) { var root = self is null ? null : self.TreeNode.TreeView.Root; - while (!(self is null)) { + while (self is not null) { if (self is DsDocumentNode found) { var p = found.TreeNode.Parent; if (p is null || p == root) diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/ModuleDocumentNode.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/ModuleDocumentNode.cs index 171bc95102..dd91cbc463 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/ModuleDocumentNode.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/ModuleDocumentNode.cs @@ -38,7 +38,7 @@ public abstract class ModuleDocumentNode : DsDocumentNode, IMDTokenNode { /// /// Document protected ModuleDocumentNode(IDsDotNetDocument document) - : base(document) => Debug2.Assert(!(document.ModuleDef is null)); + : base(document) => Debug2.Assert(document.ModuleDef is not null); /// /// Creates a diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/NodeFormatter.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/NodeFormatter.cs index db532f9d42..5be142e9a8 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/NodeFormatter.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/NodeFormatter.cs @@ -31,8 +31,8 @@ namespace dnSpy.Contracts.Documents.TreeView { /// Node formatter /// public readonly struct NodeFormatter { - static bool IsExe(ModuleDef? mod) => !(mod is null) && (mod.Characteristics & Characteristics.Dll) == 0; - static bool IsExe(IPEImage? peImage) => !(peImage is null) && (peImage.ImageNTHeaders.FileHeader.Characteristics & Characteristics.Dll) == 0; + static bool IsExe(ModuleDef? mod) => mod is not null && (mod.Characteristics & Characteristics.Dll) == 0; + static bool IsExe(IPEImage? peImage) => peImage is not null && (peImage.ImageNTHeaders.FileHeader.Characteristics & Characteristics.Dll) == 0; static string GetFilename(IDsDocument document) { string? filename = null; @@ -63,7 +63,7 @@ static string GetFilename(IDsDocument document) { public void Write(ITextColorWriter output, IDecompiler decompiler, IDsDocument document) { var filename = GetFilename(document); var peImage = document.PEImage; - if (!(peImage is null)) + if (peImage is not null) output.Write(IsExe(peImage) ? BoxedTextColor.AssemblyExe : BoxedTextColor.Assembly, NameUtilities.CleanName(filename)); else output.Write(BoxedTextColor.Text, NameUtilities.CleanName(filename)); @@ -264,7 +264,7 @@ void Write(ITextColorWriter output, IDecompiler decompiler, MethodDef? md, IMeth if (md is null) md = m?.ResolveMethodDef(); var method = (md ?? m)!; - Debug2.Assert(!(method is null)); + Debug2.Assert(method is not null); var name = method.Name; if (name == ".ctor") @@ -283,7 +283,7 @@ void Write(ITextColorWriter output, IDecompiler decompiler, MethodDef? md, IMeth } output.Write(BoxedTextColor.Punctuation, ">"); } - else if (!(md is null) && md.GenericParameters.Count > 0) { + else if (md is not null && md.GenericParameters.Count > 0) { output.Write(BoxedTextColor.Punctuation, "<"); var genericArgs = md.GenericParameters; for (int i = 0; i < genericArgs.Count; i++) { @@ -296,7 +296,7 @@ void Write(ITextColorWriter output, IDecompiler decompiler, MethodDef? md, IMeth } output.Write(BoxedTextColor.Punctuation, "("); - if (!(msig is null)) { + if (msig is not null) { var ps = msig.Params; var parameters = md?.Parameters; int paramBaseIndex = md is null || md.IsStatic ? 0 : 1; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/NotifyDocumentTreeViewCollectionChangedEventArgs.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/NotifyDocumentTreeViewCollectionChangedEventArgs.cs index 9864e114d7..fefd59b774 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/NotifyDocumentTreeViewCollectionChangedEventArgs.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/NotifyDocumentTreeViewCollectionChangedEventArgs.cs @@ -43,7 +43,7 @@ public sealed class NotifyDocumentTreeViewCollectionChangedEventArgs : EventArgs /// All cleared documents /// public static NotifyDocumentTreeViewCollectionChangedEventArgs CreateClear(DsDocumentNode[] clearedDocuments) { - Debug2.Assert(!(clearedDocuments is null)); + Debug2.Assert(clearedDocuments is not null); var e = new NotifyDocumentTreeViewCollectionChangedEventArgs(clearedDocuments); e.Type = NotifyDocumentTreeViewCollection.Clear; return e; @@ -55,7 +55,7 @@ public static NotifyDocumentTreeViewCollectionChangedEventArgs CreateClear(DsDoc /// Added document /// public static NotifyDocumentTreeViewCollectionChangedEventArgs CreateAdd(DsDocumentNode document) { - Debug2.Assert(!(document is null)); + Debug2.Assert(document is not null); var e = new NotifyDocumentTreeViewCollectionChangedEventArgs(new DsDocumentNode[] { document }); e.Type = NotifyDocumentTreeViewCollection.Add; return e; @@ -67,7 +67,7 @@ public static NotifyDocumentTreeViewCollectionChangedEventArgs CreateAdd(DsDocum /// Removed documents /// public static NotifyDocumentTreeViewCollectionChangedEventArgs CreateRemove(DsDocumentNode[] documents) { - Debug2.Assert(!(documents is null)); + Debug2.Assert(documents is not null); var e = new NotifyDocumentTreeViewCollectionChangedEventArgs(documents); e.Type = NotifyDocumentTreeViewCollection.Remove; return e; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/PEDocumentNode.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/PEDocumentNode.cs index 05e25831ae..b0f713e5d4 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/PEDocumentNode.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/PEDocumentNode.cs @@ -35,6 +35,6 @@ public abstract class PEDocumentNode : DsDocumentNode { /// /// Document protected PEDocumentNode(IDsDocument document) - : base(document) => Debug2.Assert(!(document.PEImage is null) && document.ModuleDef is null); + : base(document) => Debug2.Assert(document.PEImage is not null && document.ModuleDef is null); } } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/Deserializer.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/Deserializer.cs index 3b30754354..263bfb0b6d 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/Deserializer.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/Deserializer.cs @@ -92,7 +92,7 @@ public static Dictionary Deserialize(string asmNam #pragma warning disable SYSLIB0011 var obj = fmt.Deserialize(new MemoryStream(data)) as DeserializedType; #pragma warning restore SYSLIB0011 - Debug2.Assert(!(obj is null)); + Debug2.Assert(obj is not null); if (obj is null) return new Dictionary(); return obj.DeserializedDataInfos; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/ResourceElementNode.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/ResourceElementNode.cs index aa120eb8ac..3f45a5bd72 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/ResourceElementNode.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/ResourceElementNode.cs @@ -212,7 +212,7 @@ protected virtual string ValueString { default: var binData = resourceElement.ResourceData as BinaryResourceData; - if (!(binData is null)) + if (binData is not null) return string.Format(dnSpy_Contracts_DnSpy_Resources.NumberOfBytesAndType, binData.Data.Length, binData.TypeName); return resourceElement.ResourceData.ToString() ?? string.Empty; } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/SerializedImageUtilities.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/SerializedImageUtilities.cs index 84e0a416af..f9bcf38ee9 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/SerializedImageUtilities.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/SerializedImageUtilities.cs @@ -58,7 +58,7 @@ public static bool GetImageData(ModuleDef? module, string typeName, byte[] seria if (!dict.TryGetValue("IconData", out var info)) return false; imageData = info.Value as byte[]; - return !(imageData is null); + return imageData is not null; } return false; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/SerializedResourceElementNode.cs b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/SerializedResourceElementNode.cs index bafa92ab79..8560f692fb 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/SerializedResourceElementNode.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/Resources/SerializedResourceElementNode.cs @@ -68,7 +68,7 @@ void DeserializeIfPossible() { protected override IEnumerable GetDeserializedData() { var dd = deserializedData; var re = ResourceElement; - if (!(dd is null)) + if (dd is not null) yield return new ResourceData(re.Name, token => ResourceUtilities.StringToStream(ConvertObjectToString(dd))); else yield return new ResourceData(re.Name, token => new MemoryStream(((BinaryResourceData)re.ResourceData).Data)); diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Editor/HexGroups/LocalGroupOptions.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Editor/HexGroups/LocalGroupOptions.cs index 27b10a87fa..a6600f0415 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Editor/HexGroups/LocalGroupOptions.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Editor/HexGroups/LocalGroupOptions.cs @@ -132,7 +132,7 @@ public LocalGroupOptions CopyTo(LocalGroupOptions destination) { /// /// public bool Equals(LocalGroupOptions? other) => - !(other is null) && + other is not null && ShowOffsetColumn == other.ShowOffsetColumn && ShowValuesColumn == other.ShowValuesColumn && ShowAsciiColumn == other.ShowAsciiColumn && diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Editor/HexStructureInfoAggregator.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Editor/HexStructureInfoAggregator.cs index ed99b793fb..e73cc3cd75 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Editor/HexStructureInfoAggregator.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Editor/HexStructureInfoAggregator.cs @@ -54,7 +54,7 @@ public IEnumerable> GetFields public IEnumerable> GetToolTips(HexPosition position) { foreach (var provider in Providers) { var toolTip = provider.GetToolTip(position); - if (!(toolTip is null)) + if (toolTip is not null) yield return new HexStructureInfoProviderAndData(provider, toolTip); } } @@ -67,7 +67,7 @@ public IEnumerable> GetToolTips(HexPosit public IEnumerable> GetReferences(HexPosition position) { foreach (var provider in Providers) { var reference = provider.GetReference(position); - if (!(reference is null)) + if (reference is not null) yield return new HexStructureInfoProviderAndData(provider, reference); } } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/HeapData.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/HeapData.cs index f6a7bcefe6..e0dc9fb597 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/HeapData.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/HeapData.cs @@ -101,7 +101,7 @@ public StringsHeapRecordData(HexBuffer buffer, HexSpan stringSpan, bool hasTermi String = new StructField("String", new StringData(new HexBufferSpan(buffer, stringSpan), Encoding.UTF8)); if (hasTerminatingZero) Terminator = new StructField("Terminator", new ByteData(buffer, stringSpan.End)); - if (!(Terminator is null)) { + if (Terminator is not null) { Fields = new BufferField[] { String, Terminator, @@ -167,7 +167,7 @@ public USHeapRecordData(HexBuffer buffer, HexSpan lengthSpan, HexSpan stringSpan String = new StructField("String", new StringData(new HexBufferSpan(buffer, stringSpan), Encoding.Unicode)); if (!terminalByteSpan.IsEmpty) TerminalByte = new StructField("TerminalByte", new ByteData(new HexBufferSpan(buffer, terminalByteSpan))); - if (!(TerminalByte is null)) { + if (TerminalByte is not null) { Fields = new BufferField[] { Length, String, diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/TablesHeaderData.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/TablesHeaderData.cs index 4a953a47bb..6e5c2b8987 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/TablesHeaderData.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/TablesHeaderData.cs @@ -49,7 +49,7 @@ protected TablesHeaderData(HexBufferSpan span) /// Extra data or null if there was no extra data public abstract StructField? ExtraData { get; } /// true if field exists in header and isn't null - public bool HasExtraData => !(ExtraData is null); + public bool HasExtraData => ExtraData is not null; /// Rows public abstract StructField> Rows { get; } } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/TokenData.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/TokenData.cs index 2a2034a18c..53c425edf7 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/TokenData.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/DotNet/TokenData.cs @@ -107,7 +107,7 @@ protected CodedTokenData(HexBufferSpan span, CodedToken codedToken) /// Formatter public override void WriteValue(HexFieldFormatter formatter) { var token = ReadToken(); - if (!(token is null)) + if (token is not null) formatter.WriteToken(token.Value.Raw); else WriteValueError(formatter); diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/HexBufferFile.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/HexBufferFile.cs index 676a4fc7cc..74abecee67 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/HexBufferFile.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/Files/HexBufferFile.cs @@ -85,7 +85,7 @@ protected HexBufferFile(HexBuffer buffer, HexSpan span, string name, string file /// /// true if it's a nested file ( is not null) /// - public bool IsNestedFile => !(ParentFile is null); + public bool IsNestedFile => ParentFile is not null; /// /// Gets all nested files diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBufferLine.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBufferLine.cs index a2c4d677e6..4bec68ed5b 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBufferLine.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBufferLine.cs @@ -316,7 +316,7 @@ IEnumerable GetTextAndHexSpans(bool isColumnPresent, HexCellColl firstCell = lastCell = cell; } } - if (!(firstCell is null)) + if (firstCell is not null) yield return Create(collection, firstCell, lastCell!, overlapSpan.Value); yield break; } @@ -453,7 +453,7 @@ public HexLinePositionInfo GetLinePositionInfo(int linePosition) { break; case HexLinePositionInfoType.ValueCellSeparator: - Debug2.Assert(!(position.Cell is null)); + Debug2.Assert(position.Cell is not null); Debug.Assert(position.Cell.CellSpan.End == position.Position); position = HexLinePositionInfo.CreateValue(position.Cell.CellSpan.End - 1, position.Cell); break; @@ -478,7 +478,7 @@ public HexLinePositionInfo GetLinePositionInfo(int linePosition) { case HexLinePositionInfoType.AsciiCell: if (!IsAsciiColumnPresent) return null; - Debug2.Assert(!(cell is null)); + Debug2.Assert(cell is not null); if (onlyVisibleCells && !cell.HasData) { var visible = GetVisible(AsciiCells, cell); if (visible is null) @@ -489,7 +489,7 @@ public HexLinePositionInfo GetLinePositionInfo(int linePosition) { return new HexCellPosition(HexColumnType.Ascii, cell.BufferStart, cellPosition); case HexLinePositionInfoType.ValueCell: - Debug2.Assert(!(cell is null)); + Debug2.Assert(cell is not null); if (!IsValuesColumnPresent) return null; if (onlyVisibleCells && !cell.HasData) { diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBufferLineFormatterOptions.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBufferLineFormatterOptions.cs index b6c6c07b4b..055a822288 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBufferLineFormatterOptions.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBufferLineFormatterOptions.cs @@ -152,7 +152,7 @@ public sealed class HexBufferLineFormatterOptions : IEquatableOther instance /// public bool Equals(HexBufferLineFormatterOptions? other) => - !(other is null) && + other is not null && CharsPerLine == other.CharsPerLine && BytesPerLine == other.BytesPerLine && GroupSizeInBytes == other.GroupSizeInBytes && diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBytes.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBytes.cs index 5f7f355a2d..8503faa94a 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBytes.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexBytes.cs @@ -44,7 +44,7 @@ public readonly struct HexBytes { /// Returns true if all bytes are valid, false if all bytes are invalid, or null /// if it's not known (use ) /// - public bool? AllValid => !(validBytes is null) ? (bool?)null : allValid; + public bool? AllValid => validBytes is not null ? (bool?)null : allValid; readonly byte[] bytes; readonly bool allValid;// Only used if the bit array is null diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexLineSpan.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexLineSpan.cs index 7fdab45881..64d6cdd200 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexLineSpan.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexLineSpan.cs @@ -48,7 +48,7 @@ public readonly struct HexLineSpan { /// /// true if it's a text span /// - public bool IsTextSpan => !(TextSpan is null); + public bool IsTextSpan => TextSpan is not null; /// /// Constructor diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexSpan.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexSpan.cs index 0e619b7032..53376e0cb4 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexSpan.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/HexSpan.cs @@ -143,7 +143,7 @@ public bool IntersectsWith(HexSpan span) => /// /// /// - public bool OverlapsWith(HexSpan span) => !(Overlap(span) is null); + public bool OverlapsWith(HexSpan span) => Overlap(span) is not null; /// /// operator ==() diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Hex/NormalizedHexBufferSpanCollection.cs b/dnSpy/dnSpy.Contracts.DnSpy/Hex/NormalizedHexBufferSpanCollection.cs index 5d62da7eec..33867361e0 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Hex/NormalizedHexBufferSpanCollection.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Hex/NormalizedHexBufferSpanCollection.cs @@ -98,7 +98,7 @@ public NormalizedHexBufferSpanCollection(IEnumerable spans) { foreach (var span in spans) { if (span.IsDefault) throw new ArgumentException(); - if (!(buffer is null) && buffer != span.Buffer) + if (buffer is not null && buffer != span.Buffer) throw new ArgumentException(); buffer = span.Buffer; list.Add(span.Span); @@ -183,7 +183,7 @@ public HexBufferSpan this[int index] { /// public IEnumerator GetEnumerator() { foreach (var span in coll) { - Debug2.Assert(!(buffer is null));// Can't be null if coll is non-empty + Debug2.Assert(buffer is not null);// Can't be null if coll is non-empty yield return new HexBufferSpan(buffer, span); } } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Images/ImageOptions.cs b/dnSpy/dnSpy.Contracts.DnSpy/Images/ImageOptions.cs index 5d906b9327..52ad447c54 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Images/ImageOptions.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Images/ImageOptions.cs @@ -72,8 +72,8 @@ public ImageOptions(ITextView textView) { if (textView is null) throw new ArgumentNullException(nameof(textView)); var wpfTextView = textView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); - if (!(wpfTextView is null)) { + Debug2.Assert(wpfTextView is not null); + if (wpfTextView is not null) { Zoom = new Size(wpfTextView.ZoomLevel / 100, wpfTextView.ZoomLevel / 100); DpiObject = wpfTextView.VisualElement; } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/BestMatchSelector.cs b/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/BestMatchSelector.cs index c153b3f0af..e435e34d66 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/BestMatchSelector.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/BestMatchSelector.cs @@ -117,14 +117,14 @@ int CountUpperCaseLetters(string text) { [MethodImpl(MethodImplOptions.AggressiveInlining)] MatchPriority GetMatchPriority(Completion completion) { var filterText = completion.TryGetFilterText(); - Debug2.Assert(!(filterText is null)); + Debug2.Assert(filterText is not null); if (filterText is null) return MatchPriority.Other; if (filterText.Equals(searchText, StringComparison.CurrentCulture)) return MatchPriority.Full; - bool matchedAcronym = !(acronymMatchIndexes is null) && AcronymSearchHelpers.TryUpdateAcronymIndexes(acronymMatchIndexes, searchText, filterText); + bool matchedAcronym = acronymMatchIndexes is not null && AcronymSearchHelpers.TryUpdateAcronymIndexes(acronymMatchIndexes, searchText, filterText); if (matchedAcronym && CountUpperCaseLetters(filterText) == acronymMatchIndexes!.Length) return MatchPriority.FullAcronym; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/CompletionFilter.cs b/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/CompletionFilter.cs index 733578f399..ad93ae7b8c 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/CompletionFilter.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/CompletionFilter.cs @@ -50,7 +50,7 @@ public bool IsMatch(Completion completion) { if (completionText.IndexOf(searchText, stringComparison) >= 0) return true; - if (!(acronymMatchIndexes is null) && TryUpdateAcronymIndexes(completionText)) + if (acronymMatchIndexes is not null && TryUpdateAcronymIndexes(completionText)) return true; return false; @@ -61,7 +61,7 @@ public Span[] GetMatchSpans(string completionText) { // Acronyms have higher priority, eg. TA should match |T|ask|A|waiter // and not |Ta|skAwaiter. - if (!(acronymMatchIndexes is null) && TryUpdateAcronymIndexes(completionText)) { + if (acronymMatchIndexes is not null && TryUpdateAcronymIndexes(completionText)) { var localIndexes = acronymMatchIndexes; var res = new Span[localIndexes.Length]; for (int i = 0; i < localIndexes.Length; i++) diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/DsCompletionSet.cs b/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/DsCompletionSet.cs index 3684d1c716..fa9a427856 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/DsCompletionSet.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Language/Intellisense/DsCompletionSet.cs @@ -119,7 +119,7 @@ string SearchText { /// Filters the list. should be called after this method /// public override void Filter() { - Debug2.Assert(!(ApplicableTo is null), "You must initialize " + nameof(ApplicableTo) + " before calling this method"); + Debug2.Assert(ApplicableTo is not null, "You must initialize " + nameof(ApplicableTo) + " before calling this method"); var inputText = SearchText; var filteredList = new List(allCompletions.Length); Filter(filteredList, allCompletions); @@ -159,7 +159,7 @@ public MruSelection(Completion completion, int index) { /// /// protected virtual CompletionSelectionStatus GetBestMatch() { - Debug2.Assert(!(ApplicableTo is null), "You must initialize " + nameof(ApplicableTo) + " before calling this method"); + Debug2.Assert(ApplicableTo is not null, "You must initialize " + nameof(ApplicableTo) + " before calling this method"); var inputText = SearchText; var completionFilter = CreateCompletionFilter(inputText); int matches = 0; @@ -167,7 +167,7 @@ protected virtual CompletionSelectionStatus GetBestMatch() { var mruSelectionCase = default(MruSelection); var mruSelection = default(MruSelection); if (inputText.Length > 0) { - Debug2.Assert(!(searchText is null)); + Debug2.Assert(searchText is not null); foreach (var completion in Completions) { if (!completionFilter.IsMatch(completion)) continue; @@ -191,10 +191,10 @@ protected virtual CompletionSelectionStatus GetBestMatch() { // local 'i' exists, and we previously typed 'int', and we've just typed 'i', // then select 'i' and not 'int' var selectedCompletion = mruSelectionCase.Completion ?? mruSelection.Completion ?? selector.Result; - if (!(selector.Result is null) && inputText.Equals(selector.Result!.TryGetFilterText(), StringComparison.OrdinalIgnoreCase)) + if (selector.Result is not null && inputText.Equals(selector.Result!.TryGetFilterText(), StringComparison.OrdinalIgnoreCase)) selectedCompletion = selector.Result; - bool isSelected = !(selectedCompletion is null); + bool isSelected = selectedCompletion is not null; bool isUnique = matches == 1; return new CompletionSelectionStatus(selectedCompletion, isSelected, isUnique); } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/AutomationPeerMemoryLeakWorkaround.cs b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/AutomationPeerMemoryLeakWorkaround.cs index df4b955a9b..8952d63bad 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/AutomationPeerMemoryLeakWorkaround.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/AutomationPeerMemoryLeakWorkaround.cs @@ -61,11 +61,11 @@ public static void ClearAll(ItemsControl? itemsControl) { // Some of the cached items contain references to data that should be GC'd var method = itemsControl.ItemContainerGenerator.GetType().GetMethod("ResetRecyclableContainers", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Array.Empty(), null); - Debug2.Assert(!(method is null)); + Debug2.Assert(method is not null); method?.Invoke(itemsControl.ItemContainerGenerator, Array.Empty()); var automationPeer = UIElementAutomationPeer.FromElement(itemsControl); - if (!(automationPeer is null)) { + if (automationPeer is not null) { PropertyInfo? prop; MethodInfo? getMethod; @@ -73,13 +73,13 @@ public static void ClearAll(ItemsControl? itemsControl) { // Clear _dataChildren prop = automationPeer.GetType().GetProperty("ItemPeers", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); getMethod = prop?.GetGetMethod(nonPublic: true); - Debug2.Assert(!(getMethod is null)); - if (!(getMethod is null)) { + Debug2.Assert(getMethod is not null); + if (getMethod is not null) { var coll = getMethod.Invoke(automationPeer, Array.Empty()); - Debug2.Assert(!(coll is null)); - if (!(coll is null)) { + Debug2.Assert(coll is not null); + if (coll is not null) { var clearMethod = coll.GetType().GetMethod("Clear", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Array.Empty(), null); - Debug2.Assert(!(clearMethod is null)); + Debug2.Assert(clearMethod is not null); clearMethod?.Invoke(coll, Array.Empty()); } } @@ -87,10 +87,10 @@ public static void ClearAll(ItemsControl? itemsControl) { // Clear _recentlyRealizedPeers prop = automationPeer.GetType().GetProperty("RecentlyRealizedPeers", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); getMethod = prop?.GetGetMethod(nonPublic: true); - Debug2.Assert(!(getMethod is null)); - if (!(getMethod is null)) { + Debug2.Assert(getMethod is not null); + if (getMethod is not null) { var coll = getMethod.Invoke(automationPeer, Array.Empty()) as System.Collections.IList; - Debug2.Assert(!(coll is null)); + Debug2.Assert(coll is not null); coll?.Clear(); } } @@ -98,14 +98,14 @@ public static void ClearAll(ItemsControl? itemsControl) { // Set ChildrenValid = false prop = automationPeer.GetType().GetProperty("ChildrenValid", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var setMethod = prop?.GetSetMethod(nonPublic: true); - Debug2.Assert(!(setMethod is null)); + Debug2.Assert(setMethod is not null); setMethod?.Invoke(automationPeer, new object[] { false }); // Clear _children prop = automationPeer.GetType().GetProperty("Children", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); getMethod = prop?.GetGetMethod(nonPublic: true); - Debug2.Assert(!(getMethod is null)); - if (!(getMethod is null)) { + Debug2.Assert(getMethod is not null); + if (getMethod is not null) { var coll = getMethod.Invoke(automationPeer, Array.Empty()) as System.Collections.IList; coll?.Clear(); } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/DataFieldVM.cs b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/DataFieldVM.cs index e9834dff58..8e3318eaf1 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/DataFieldVM.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/DataFieldVM.cs @@ -238,7 +238,7 @@ protected DataFieldVM(Action onUpdated) /// public override string? ConvertToObjectValue(out object value) { var error = ConvertToValue(out var v); - Debug2.Assert(!(v is null)); + Debug2.Assert(v is not null); value = v; return error; } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/Dialogs/ProgressDlg.xaml.cs b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/Dialogs/ProgressDlg.xaml.cs index e0421ea82c..8004d9d5d0 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/Dialogs/ProgressDlg.xaml.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/Dialogs/ProgressDlg.xaml.cs @@ -34,7 +34,7 @@ public ProgressDlg() { InitializeComponent(); DataContextChanged += (s, e) => { var data = DataContext as ProgressVM; - if (!(data is null)) { + if (data is not null) { data.OnCompleted += ProgressVM_OnCompleted; if (data.HasCompleted) OnCompleted(); @@ -64,7 +64,7 @@ protected override void OnClosing(CancelEventArgs e) { void OnCompleted() { var data = DataContext as ProgressVM; - DialogResult = !(data is null) && !data.WasCanceled; + DialogResult = data is not null && !data.WasCanceled; Close(); } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/Dialogs/ProgressVM.cs b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/Dialogs/ProgressVM.cs index cf196cd6a4..199580590a 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/Dialogs/ProgressVM.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/Dialogs/ProgressVM.cs @@ -201,7 +201,7 @@ public string? CurrentItemDescription { /// /// true if there was an error /// - public bool WasError => !(ErrorMessage is null); + public bool WasError => ErrorMessage is not null; /// /// Gets the error message or null if no error diff --git a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/EnumVM.cs b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/EnumVM.cs index 7c368ff762..eb2b7d9d7c 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/EnumVM.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/EnumVM.cs @@ -77,7 +77,7 @@ public EnumVM(object value, string name) { public static EnumVM[] Create(bool sort, Type enumType, params object[] values) { var list = new List(); foreach (var value in enumType.GetEnumValues()) { - Debug2.Assert(!(value is null)); + Debug2.Assert(value is not null); if (values.Any(a => a.Equals(value))) continue; list.Add(new EnumVM(value)); @@ -110,7 +110,7 @@ public sealed class EnumListVM : ListVM { return list[Index].Value; } set { - if (!(value is null) && !object.Equals(SelectedItem, value)) + if (value is not null && !object.Equals(SelectedItem, value)) SelectedIndex = GetIndex(value); } } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/GridViewColumnSorter.cs b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/GridViewColumnSorter.cs index 69360928b3..13daea610f 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/GridViewColumnSorter.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/GridViewColumnSorter.cs @@ -102,7 +102,7 @@ void Initialize(IGridViewColumnDescsProvider descsProvider) { } void GridView_Columns_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { - Debug2.Assert(!(descsProvider is null)); + Debug2.Assert(descsProvider is not null); var gridView = (GridView)listView.View; var columns = gridView.Columns; Debug.Assert(columns.Count == descsProvider.Descs.Columns.Length); @@ -123,7 +123,7 @@ void ListView_Click(object? sender, RoutedEventArgs e) { } void UpdateSortedColumn(GridViewColumnDesc desc) { - Debug2.Assert(!(descsProvider is null)); + Debug2.Assert(descsProvider is not null); if (!desc.CanBeSorted) return; var sortedColumn = descsProvider.Descs.SortedColumn; @@ -148,7 +148,7 @@ static GridViewSortDirection GetGridViewSortDirection(GridViewSortDirection dire } void UpdateColumns() { - Debug2.Assert(!(descsProvider is null)); + Debug2.Assert(descsProvider is not null); var gridView = (GridView)listView.View; var cols = gridView.Columns; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/InitDataTemplateAP.cs b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/InitDataTemplateAP.cs index 2735cd3e87..4b5a71898a 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/InitDataTemplateAP.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/InitDataTemplateAP.cs @@ -62,7 +62,7 @@ sealed class MefState : IAutoLoaded { } static void InitializePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { - Debug2.Assert(!(MefState.Instance is null)); + Debug2.Assert(MefState.Instance is not null); if ((bool)e.NewValue) { foreach (var elem in MefState.Instance.entries) elem.Value.Initialize(d); diff --git a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/IsDraggableAP.cs b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/IsDraggableAP.cs index 0a79a83a41..edb326647b 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/IsDraggableAP.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/IsDraggableAP.cs @@ -42,6 +42,6 @@ public sealed class IsDraggableAP : DependencyObject { /// /// Element /// - public static bool GetIsDraggable(FrameworkElement? element) => !(element is null) && (bool)element.GetValue(IsDraggableProperty); + public static bool GetIsDraggable(FrameworkElement? element) => element is not null && (bool)element.GetValue(IsDraggableProperty); } } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/ListVM.cs b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/ListVM.cs index 5823da30a1..510c53716f 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/MVVM/ListVM.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/MVVM/ListVM.cs @@ -167,7 +167,7 @@ int GetIndex(T value) { string IDataErrorInfo.this[string columnName] { get { if (columnName == nameof(SelectedIndex)) { - if (!(DataErrorInfoDelegate is null)) + if (DataErrorInfoDelegate is not null) return DataErrorInfoDelegate(this); } return string.Empty; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Menus/CommandTargetMenuItemBase.cs b/dnSpy/dnSpy.Contracts.DnSpy/Menus/CommandTargetMenuItemBase.cs index 4c12d5458e..1217796aa5 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Menus/CommandTargetMenuItemBase.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Menus/CommandTargetMenuItemBase.cs @@ -62,7 +62,7 @@ protected CommandTargetMenuItemBase(Guid group, int cmdId) { protected abstract ICommandTarget? GetCommandTarget(IMenuItemContext context); /// - public override bool IsVisible(IMenuItemContext context) => !(GetCommandTarget(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetCommandTarget(context) is not null; /// public override bool IsEnabled(IMenuItemContext context) => GetCommandTarget(context)?.CanExecute(group, cmdId) == CommandTargetStatus.Handled; @@ -112,7 +112,7 @@ protected CommandTargetMenuItemBase(Guid group, int cmdId) { protected abstract ICommandTarget? GetCommandTarget(TContext context); /// - public override bool IsVisible(TContext context) => !(GetCommandTarget(context) is null); + public override bool IsVisible(TContext context) => GetCommandTarget(context) is not null; /// public override bool IsEnabled(TContext context) => GetCommandTarget(context)?.CanExecute(group, cmdId) == CommandTargetStatus.Handled; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Menus/MenuItemBase.cs b/dnSpy/dnSpy.Contracts.DnSpy/Menus/MenuItemBase.cs index d4439c7f73..5c36cb97b0 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Menus/MenuItemBase.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Menus/MenuItemBase.cs @@ -72,38 +72,38 @@ public abstract class MenuItemBase : IMenuItem where TContext : class void IMenuItem.Execute(IMenuItemContext context) { var ctx = GetCachedContext(context); - if (!(ctx is null)) + if (ctx is not null) Execute(ctx); } bool IMenuItem.IsEnabled(IMenuItemContext context) { var ctx = GetCachedContext(context); - return !(ctx is null) && IsEnabled(ctx); + return ctx is not null && IsEnabled(ctx); } bool IMenuItem.IsVisible(IMenuItemContext context) { var ctx = GetCachedContext(context); - return !(ctx is null) && IsVisible(ctx); + return ctx is not null && IsVisible(ctx); } string? IMenuItem.GetHeader(IMenuItemContext context) { var ctx = GetCachedContext(context); - return !(ctx is null) ? GetHeader(ctx) : null; + return ctx is not null ? GetHeader(ctx) : null; } ImageReference? IMenuItem.GetIcon(IMenuItemContext context) { var ctx = GetCachedContext(context); - return !(ctx is null) ? GetIcon(ctx) : null; + return ctx is not null ? GetIcon(ctx) : null; } string? IMenuItem.GetInputGestureText(IMenuItemContext context) { var ctx = GetCachedContext(context); - return !(ctx is null) ? GetInputGestureText(ctx) : null; + return ctx is not null ? GetInputGestureText(ctx) : null; } bool IMenuItem.IsChecked(IMenuItemContext context) { var ctx = GetCachedContext(context); - return !(ctx is null) ? IsChecked(ctx) : false; + return ctx is not null ? IsChecked(ctx) : false; } /// diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Scripting/UIUtils.cs b/dnSpy/dnSpy.Contracts.DnSpy/Scripting/UIUtils.cs index d6125825eb..f819612bc9 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Scripting/UIUtils.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Scripting/UIUtils.cs @@ -50,7 +50,7 @@ public static void UI(this Dispatcher dispatcher, Action a) { return; } }), DispatcherPriority.Send); - if (!(exInfo is null)) + if (exInfo is not null) exInfo.Throw(); } @@ -77,7 +77,7 @@ public static T UI(this Dispatcher dispatcher, Func f) { return default!; } }), DispatcherPriority.Send); - if (!(exInfo is null)) + if (exInfo is not null) exInfo.Throw(); return res; } @@ -117,7 +117,7 @@ public static IEnumerable UIIter(this Dispatcher dispatcher, Func !(type.BaseType is null) && type.BaseType.FullName == "System.MulticastDelegate" && type.BaseType.DefinitionAssembly.IsCorLib(); + static bool IsDelegate(TypeDef type) => type.BaseType is not null && type.BaseType.FullName == "System.MulticastDelegate" && type.BaseType.DefinitionAssembly.IsCorLib(); static bool HasInstanceConstructors(TypeDef type) => type.Methods.Any(m => m.IsInstanceConstructor); static bool HasMethodBodies(TypeDef type) { foreach (var method in type.Methods) { - if (!(method.Body is null)) + if (method.Body is not null) return true; } return false; @@ -301,7 +301,7 @@ static bool HasMethodBodies(TypeDef type) { static bool HasLocals(TypeDef type) { foreach (var method in type.Methods) { - if (!(method.Body is null) && method.Body.HasVariables) + if (method.Body is not null && method.Body.HasVariables) return true; } return false; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Search/SameModuleDocumentTreeNodeFilter.cs b/dnSpy/dnSpy.Contracts.DnSpy/Search/SameModuleDocumentTreeNodeFilter.cs index 95bd09afd9..b452203300 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Search/SameModuleDocumentTreeNodeFilter.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Search/SameModuleDocumentTreeNodeFilter.cs @@ -37,7 +37,7 @@ public SameModuleDocumentTreeNodeFilter(ModuleDef allowedModule, IDocumentTreeNo #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public override DocumentTreeNodeFilterResult GetResult(AssemblyDef asm) { - if (!(allowedModule.Assembly is null) && allowedModule.Assembly != asm) + if (allowedModule.Assembly is not null && allowedModule.Assembly != asm) return new DocumentTreeNodeFilterResult(FilterType.Hide, false); return base.GetResult(asm); } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Search/SearchComparers.cs b/dnSpy/dnSpy.Contracts.DnSpy/Search/SearchComparers.cs index f0c06d03e8..21bbc79cea 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Search/SearchComparers.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Search/SearchComparers.cs @@ -37,7 +37,7 @@ static class SearchComparerFactory { /// public static ISearchComparer Create(string searchText, bool caseSensitive, bool matchWholeWords, bool matchAnyWords) { var regex = TryCreateRegEx(searchText, caseSensitive); - if (!(regex is null)) + if (regex is not null) return new RegExSearchComparer(regex); var searchTerms = searchText.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); @@ -58,10 +58,10 @@ public static ISearchComparer CreateLiteral(string searchText, bool caseSensitiv var s = searchText.Trim(); var val64 = TryParseInt64(s); - if (!(val64 is null)) + if (val64 is not null) return new IntegerLiteralSearchComparer(val64.Value); var uval64 = TryParseUInt64(s); - if (!(uval64 is null)) + if (uval64 is not null) return new IntegerLiteralSearchComparer(unchecked((long)uval64.Value)); if (double.TryParse(s, out double dbl)) return new DoubleLiteralSearchComparer(dbl); @@ -70,7 +70,7 @@ public static ISearchComparer CreateLiteral(string searchText, bool caseSensitiv s = s.Substring(1, s.Length - 2); else { var regex = TryCreateRegEx(s, caseSensitive); - if (!(regex is null)) + if (regex is not null) return new RegExStringLiteralSearchComparer(regex); } return new StringLiteralSearchComparer(s, caseSensitive, matchWholeWords); @@ -144,7 +144,7 @@ sealed class RegExStringLiteralSearchComparer : ISearchComparer { public RegExStringLiteralSearchComparer(Regex regex) => this.regex = regex ?? throw new ArgumentNullException(nameof(regex)); public bool IsMatch(string? text, object? obj) { - if (obj is IHasConstant hc && !(hc.Constant is null)) + if (obj is IHasConstant hc && hc.Constant is not null) obj = hc.Constant.Value; return obj is string s && regex.IsMatch(s); @@ -163,7 +163,7 @@ public StringLiteralSearchComparer(string s, bool caseSensitive = false, bool ma } public bool IsMatch(string? text, object? obj) { - if (obj is IHasConstant hc && !(hc.Constant is null)) + if (obj is IHasConstant hc && hc.Constant is not null) obj = hc.Constant.Value; if (!(obj is string s)) @@ -180,7 +180,7 @@ sealed class IntegerLiteralSearchComparer : ISearchComparer { public IntegerLiteralSearchComparer(long value) => searchValue = value; public bool IsMatch(string? text, object? obj) { - if (obj is IHasConstant hc && !(hc.Constant is null)) + if (obj is IHasConstant hc && hc.Constant is not null) obj = hc.Constant.Value; if (obj is null) return false; @@ -211,7 +211,7 @@ sealed class DoubleLiteralSearchComparer : ISearchComparer { public DoubleLiteralSearchComparer(double value) => searchValue = value; public bool IsMatch(string? text, object? obj) { - if (obj is IHasConstant hc && !(hc.Constant is null)) + if (obj is IHasConstant hc && hc.Constant is not null) obj = hc.Constant.Value; if (obj is null) return false; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Text/Classification/ThemeClassificationFormatDefinition.cs b/dnSpy/dnSpy.Contracts.DnSpy/Text/Classification/ThemeClassificationFormatDefinition.cs index 4f70d3963e..887e453cf8 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Text/Classification/ThemeClassificationFormatDefinition.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Text/Classification/ThemeClassificationFormatDefinition.cs @@ -48,22 +48,22 @@ public ResourceDictionary CreateResourceDictionary(ITheme theme) { var res = CreateResourceDictionary(); var isBold = GetIsBold(theme); - if (!(isBold is null)) + if (isBold is not null) res.Add(IsBoldId, isBold.Value); var isItalic = GetIsItalic(theme); - if (!(isItalic is null)) + if (isItalic is not null) res.Add(IsItalicId, isItalic.Value); var fg = GetForeground(theme); - if (!(fg is null)) { + if (fg is not null) { res[ForegroundBrushId] = fg; if (fg.Opacity != 1) res[ForegroundOpacityId] = fg.Opacity; } var bg = GetBackground(theme); - if (!(bg is null)) { + if (bg is not null) { res[BackgroundBrushId] = bg; if (bg.Opacity != 1) res[BackgroundOpacityId] = bg.Opacity; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Text/Classification/ThemeMarkerFormatDefinition.cs b/dnSpy/dnSpy.Contracts.DnSpy/Text/Classification/ThemeMarkerFormatDefinition.cs index 19263a2543..4ecc019e2c 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Text/Classification/ThemeMarkerFormatDefinition.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Text/Classification/ThemeMarkerFormatDefinition.cs @@ -48,11 +48,11 @@ public ResourceDictionary CreateResourceDictionary(ITheme theme) { var res = CreateResourceDictionary(); var fg = GetForeground(theme); - if (!(fg is null)) + if (fg is not null) res[ForegroundBrushId] = fg; var bg = GetBackground(theme); - if (!(bg is null)) + if (bg is not null) res[BackgroundBrushId] = bg; return res; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/ToolWindows/Search/SearchMatcher.cs b/dnSpy/dnSpy.Contracts.DnSpy/ToolWindows/Search/SearchMatcher.cs index 142a3cb657..f47fbb6329 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/ToolWindows/Search/SearchMatcher.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/ToolWindows/Search/SearchMatcher.cs @@ -105,7 +105,7 @@ public List GetMatchSpans(string columnId, string text) { return spans; foreach (var cmd in searchCommands) { - if (!(cmd.ColumnId is null) && cmd.ColumnId != columnId) + if (cmd.ColumnId is not null && cmd.ColumnId != columnId) continue; if (cmd.Negate) continue; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/TreeView/AsyncNodeProvider.cs b/dnSpy/dnSpy.Contracts.DnSpy/TreeView/AsyncNodeProvider.cs index 01a27cad07..580f2b1231 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/TreeView/AsyncNodeProvider.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/TreeView/AsyncNodeProvider.cs @@ -118,7 +118,7 @@ protected void AddMessageNode(Func create) => UI(() => { }); void RemoveMessageNode_UI() { - if (!(msgNode is null)) + if (msgNode is not null) targetNode.TreeNode.Children.Remove(msgNode); OnCompleted(); } diff --git a/dnSpy/dnSpy.Contracts.DnSpy/TreeView/TreeNodeData.cs b/dnSpy/dnSpy.Contracts.DnSpy/TreeView/TreeNodeData.cs index 6365dab5d3..3c2e313672 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/TreeView/TreeNodeData.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/TreeView/TreeNodeData.cs @@ -70,7 +70,7 @@ public abstract class TreeNodeData { public ITreeNode TreeNode { get => treeNode; set { - if (!(treeNode is null)) + if (treeNode is not null) throw new InvalidOperationException(); treeNode = value ?? throw new ArgumentNullException(nameof(value)); } @@ -199,7 +199,7 @@ public static class TreeNodeDataExtensionMethods { /// This /// public static T? GetAncestorOrSelf(this TreeNodeData? self) where T : TreeNodeData { - while (!(self is null)) { + while (self is not null) { if (self is T found) return found; var parent = self.TreeNode.Parent; diff --git a/dnSpy/dnSpy.Contracts.DnSpy/Utilities/UIUtilities.cs b/dnSpy/dnSpy.Contracts.DnSpy/Utilities/UIUtilities.cs index b9767359f2..30b1c98d87 100644 --- a/dnSpy/dnSpy.Contracts.DnSpy/Utilities/UIUtilities.cs +++ b/dnSpy/dnSpy.Contracts.DnSpy/Utilities/UIUtilities.cs @@ -46,7 +46,7 @@ public static class UIUtilities { static T? GetItem(DependencyObject view, object o) where T : class { var depo = o as DependencyObject; - while (!(depo is null) && !(depo is T) && depo != view) + while (depo is not null && !(depo is T) && depo != view) depo = GetParent(depo); return depo as T; } @@ -61,7 +61,7 @@ public static class UIUtilities { public static bool IsLeftDoubleClick(DependencyObject view, MouseButtonEventArgs e) where T : class { if (MouseButton.Left != e.ChangedButton) return false; - return !(GetItem(view, e.OriginalSource) is null); + return GetItem(view, e.OriginalSource) is not null; } /// @@ -99,9 +99,9 @@ static void selector_IsVisibleChanged(object? sender, DependencyPropertyChangedE static void FocusSelectorInternal(Selector selector) { bool focused = false; var item = selector.SelectedItem as IInputElement; - if (item is null && !(selector.SelectedItem is null)) + if (item is null && selector.SelectedItem is not null) item = selector.ItemContainerGenerator.ContainerFromItem(selector.SelectedItem) as IInputElement; - if (!(item is null)) + if (item is not null) focused = item.Focus(); if (!focused) { selector.Focus(); @@ -125,7 +125,7 @@ static void UIElement_IsVisibleChanged(object? sender, DependencyPropertyChanged public static void Focus(IInputElement? element, Action? calledAfterFocus = null) { var uiElem = element as UIElement; var fwkElem = element as FrameworkElement; - if (uiElem is null || (!(fwkElem is null) && fwkElem.IsLoaded && fwkElem.IsVisible) || (fwkElem is null && uiElem.IsVisible)) { + if (uiElem is null || (fwkElem is not null && fwkElem.IsLoaded && fwkElem.IsVisible) || (fwkElem is null && uiElem.IsVisible)) { element?.Focus(); calledAfterFocus?.Invoke(); return; diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/AddressReference.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/AddressReference.cs index c8e9d185f5..d3fdf6b9c6 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/AddressReference.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/AddressReference.cs @@ -64,7 +64,7 @@ public AddressReference(string? filename, bool isRva, ulong address, ulong lengt /// /// public bool Equals(AddressReference? other) => - !(other is null) && + other is not null && IsRVA == other.IsRVA && Address == other.Address && Length == other.Length && diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/CustomAttributesUtils.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/CustomAttributesUtils.cs index b09d4e8361..ea4032fcd3 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/CustomAttributesUtils.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/CustomAttributesUtils.cs @@ -27,7 +27,7 @@ namespace dnSpy.Contracts.Decompiler { /// public static class CustomAttributesUtils { static bool IsType(TypeDef type, (UTF8String @namespace, UTF8String name)[] typeNames) { - if (!(type.DeclaringType is null)) + if (type.DeclaringType is not null) return false; var name = type.Name; var @namespace = type.Namespace; @@ -151,7 +151,7 @@ static IEnumerable GetSecurityDeclarations(ModuleDef module, IH /// public static IEnumerable GetCustomAttributes(this AssemblyDef assembly) { var module = (ModuleDef?)assembly.ManifestModule; - if (!(module is null)) { + if (module is not null) { if (assembly.HashAlgorithm != AssemblyHashAlgorithm.SHA1) { var declType = new TypeRefUser(module, systemReflectionName, assemblyAlgorithmIdAttributeName, module.CorLibTypes.AssemblyRef); var enumDeclType = new ValueTypeSig(new TypeRefUser(module, systemConfigurationAssembliesName, assemblyHashAlgorithmName, module.CorLibTypes.AssemblyRef)); @@ -182,7 +182,7 @@ public static IEnumerable GetCustomAttributes(this AssemblyDef } foreach (var ca in assembly.CustomAttributes) yield return ca; - if (!(module is null)) { + if (module is not null) { foreach (var ca in GetSecurityDeclarations(module, assembly)) yield return ca; } @@ -419,7 +419,7 @@ public static IEnumerable GetCustomAttributes(this MethodDef me } static bool HasIsReadOnlyAttribute(IHasCustomAttribute hca) => - !(Find(hca, systemRuntimeCompilerServicesName, isReadOnlyAttributeName) is null); + Find(hca, systemRuntimeCompilerServicesName, isReadOnlyAttributeName) is not null; /// /// Gets custom attributes and pseudo custom attributes @@ -509,7 +509,7 @@ static CustomAttribute CreateMarshalTypeCustomAttribute(ModuleDef module, Marsha var type = ca.AttributeType; if (type.Name != name || type.Namespace != @namespace) continue; - if (!(type.DeclaringType is null)) + if (type.DeclaringType is not null) continue; return ca; } @@ -525,7 +525,7 @@ public static IEnumerable GetCustomAttributes(this PropertyDef foreach (var ca in property.CustomAttributes) yield return ca; var defMemCa = Find(property.DeclaringType, systemReflectionName, defaultMemberAttributeName); - if (!(defMemCa is null) && defMemCa.ConstructorArguments.Count > 0 && + if (defMemCa is not null && defMemCa.ConstructorArguments.Count > 0 && defMemCa.ConstructorArguments[0].Value is UTF8String defMember && defMember != itemName && defMember == property.Name) { var module = property.Module; diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/Extensions.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/Extensions.cs index 3584bdd75f..181caa22f8 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/Extensions.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/Extensions.cs @@ -188,11 +188,11 @@ static IEnumerable GetAllMethods(this PropertyDef p) { } static IEnumerable GetAllMethods(this EventDef e) { - if (!(e.AddMethod is null)) + if (e.AddMethod is not null) yield return e.AddMethod; - if (!(e.InvokeMethod is null)) + if (e.InvokeMethod is not null) yield return e.InvokeMethod; - if (!(e.RemoveMethod is null)) + if (e.RemoveMethod is not null) yield return e.RemoveMethod; foreach (var m in e.OtherMethods) yield return m; @@ -228,9 +228,9 @@ public static bool IsIndexer(this PropertyDef? property) { var accessor = property.GetMethod ?? property.SetMethod; var basePropDef = property; - if (!(accessor is null) && accessor.HasOverrides) { + if (accessor is not null && accessor.HasOverrides) { var baseAccessor = accessor.Overrides.First().MethodDeclaration.ResolveMethodDef(); - if (!(baseAccessor is null)) { + if (baseAccessor is not null) { foreach (var baseProp in baseAccessor.DeclaringType.Properties) { if (baseProp.GetMethod == baseAccessor || baseProp.SetMethod == baseAccessor) { basePropDef = baseProp; @@ -252,7 +252,7 @@ public static bool IsIndexer(this PropertyDef? property) { if (type is null) return null; foreach (var ca in type.CustomAttributes.FindAll("System.Reflection.DefaultMemberAttribute")) { - if (!(ca.Constructor is null) && ca.Constructor.FullName == @"System.Void System.Reflection.DefaultMemberAttribute::.ctor(System.String)" && + if (ca.Constructor is not null && ca.Constructor.FullName == @"System.Void System.Reflection.DefaultMemberAttribute::.ctor(System.String)" && ca.ConstructorArguments.Count == 1 && ca.ConstructorArguments[0].Value is UTF8String) { return (UTF8String)ca.ConstructorArguments[0].Value; diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/GenericArgumentResolver.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/GenericArgumentResolver.cs index 4be046a393..60295392e4 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/GenericArgumentResolver.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/GenericArgumentResolver.cs @@ -56,7 +56,7 @@ public struct GenericArgumentResolver { bool ReplaceGenericArg(ref TypeSig typeSig) { if (typeSig is GenericMVar genericMVar) { var newSig = Read(methodGenArgs, genericMVar.Number); - if (!(newSig is null)) { + if (newSig is not null) { typeSig = newSig; return true; } @@ -65,7 +65,7 @@ bool ReplaceGenericArg(ref TypeSig typeSig) { if (typeSig is GenericVar genericVar) { var newSig = Read(typeGenArgs, genericVar.Number); - if (!(newSig is null)) { + if (newSig is not null) { typeSig = newSig; return true; } @@ -98,7 +98,7 @@ MethodSig ResolveGenericArgs(MethodSig sig, MethodBaseSig old) { foreach (var p in old.Params) sig.Params.Add(ResolveGenericArgs(p)); sig.GenParamCount = old.GenParamCount; - if (!(sig.ParamsAfterSentinel is null)) { + if (sig.ParamsAfterSentinel is not null) { foreach (var p in old.ParamsAfterSentinel) sig.ParamsAfterSentinel.Add(ResolveGenericArgs(p)); } @@ -187,15 +187,15 @@ MethodSig ResolveGenericArgs(MethodSig sig, MethodBaseSig old) { LocalSig? lsig; PropertySig? psig; GenericInstMethodSig? gsig; - if (!((msig = sig as MethodSig) is null)) + if ((msig = sig as MethodSig) is not null) result = ResolveGenericArgs(msig); - else if (!((fsig = sig as FieldSig) is null)) + else if ((fsig = sig as FieldSig) is not null) result = ResolveGenericArgs(fsig); - else if (!((lsig = sig as LocalSig) is null)) + else if ((lsig = sig as LocalSig) is not null) result = ResolveGenericArgs(lsig); - else if (!((psig = sig as PropertySig) is null)) + else if ((psig = sig as PropertySig) is not null) result = ResolveGenericArgs(psig); - else if (!((gsig = sig as GenericInstMethodSig) is null)) + else if ((gsig = sig as GenericInstMethodSig) is not null) result = ResolveGenericArgs(gsig); else result = null; @@ -217,7 +217,7 @@ T ResolveGenericArgs2(T outSig, T inSig) where T : MethodBaseSig { outSig.RetType = ResolveGenericArgs(inSig.RetType); outSig.GenParamCount = inSig.GenParamCount; UpdateSigList(outSig.Params, inSig.Params); - if (!(inSig.ParamsAfterSentinel is null)) { + if (inSig.ParamsAfterSentinel is not null) { outSig.ParamsAfterSentinel = new List(inSig.ParamsAfterSentinel.Count); UpdateSigList(outSig.ParamsAfterSentinel, inSig.ParamsAfterSentinel); } diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/InstructionReference.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/InstructionReference.cs index 3ce8520ea3..4e92ca3684 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/InstructionReference.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/InstructionReference.cs @@ -51,7 +51,7 @@ public InstructionReference(MethodDef method, Instruction instruction) { /// /// /// - public bool Equals(InstructionReference? other) => !(other is null) && Method == other.Method && Instruction == other.Instruction; + public bool Equals(InstructionReference? other) => other is not null && Method == other.Method && Instruction == other.Instruction; /// /// Equals() diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/MetadataTextColorProvider.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/MetadataTextColorProvider.cs index 1c5238d822..5058d6a2ad 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/MetadataTextColorProvider.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/MetadataTextColorProvider.cs @@ -47,14 +47,14 @@ public virtual object GetColor(TypeDef? type) { if (type.IsSealed && type.IsAbstract) { var bt = type.BaseType; - if (!(bt is null) && bt.DefinitionAssembly.IsCorLib()) { + if (bt is not null && bt.DefinitionAssembly.IsCorLib()) { if (bt is TypeRef baseTr) { if (baseTr.Namespace == systemString && baseTr.Name == objectString) return BoxedTextColor.StaticType; } else { var baseTd = bt as TypeDef; - if (!(baseTd is null) && baseTd.Namespace == systemString && baseTd.Name == objectString) + if (baseTd is not null && baseTd.Namespace == systemString && baseTd.Name == objectString) return BoxedTextColor.StaticType; } } @@ -77,7 +77,7 @@ public virtual object GetColor(TypeRef? type) { return BoxedTextColor.Text; var td = type.Resolve(); - if (!(td is null)) + if (td is not null) return GetColor(td); return BoxedTextColor.Type; @@ -112,10 +112,10 @@ public virtual object GetColor(IMemberRef? memberRef) { if (mr.MethodSig is null) return BoxedTextColor.InstanceMethod; var md = mr.ResolveMethodDef(); - if (!(md is null) && md.IsConstructor) + if (md is not null && md.IsConstructor) return GetColor(md.DeclaringType); if (!mr.MethodSig.HasThis) { - if (!(md is null) && md.IsDefined(systemRuntimeCompilerServicesString, extensionAttributeString)) + if (md is not null && md.IsDefined(systemRuntimeCompilerServicesString, extensionAttributeString)) return BoxedTextColor.ExtensionMethod; return BoxedTextColor.StaticMethod; } @@ -173,10 +173,10 @@ public virtual object GetColor(GenericParam? genericParam) { if (genericParam is null) return BoxedTextColor.Text; - if (!(genericParam.DeclaringType is null)) + if (genericParam.DeclaringType is not null) return BoxedTextColor.TypeGenericParameter; - if (!(genericParam.DeclaringMethod is null)) + if (genericParam.DeclaringMethod is not null) return BoxedTextColor.MethodGenericParameter; return BoxedTextColor.TypeGenericParameter; @@ -303,7 +303,7 @@ public override object GetColor(TypeDef? type) { } static bool IsModule(TypeDef? type) => - !(type is null) && type.DeclaringType is null && type.IsSealed && type.IsDefined(stringMicrosoftVisualBasicCompilerServices, stringStandardModuleAttribute); + type is not null && type.DeclaringType is null && type.IsSealed && type.IsDefined(stringMicrosoftVisualBasicCompilerServices, stringStandardModuleAttribute); static readonly UTF8String stringMicrosoftVisualBasicCompilerServices = new UTF8String("Microsoft.VisualBasic.CompilerServices"); static readonly UTF8String stringStandardModuleAttribute = new UTF8String("StandardModuleAttribute"); } diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodDebugInfo.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodDebugInfo.cs index 7684ccc972..a7ff45ff89 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodDebugInfo.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodDebugInfo.cs @@ -147,7 +147,7 @@ public MethodDebugInfo(string? compilerName, int decompilerSettingsVersion, Stat } } } - if (!(intersection is null)) + if (intersection is not null) return intersection; var list = new List(); diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodDebugInfoBuilder.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodDebugInfoBuilder.cs index 28624cb5ef..84f30b38c9 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodDebugInfoBuilder.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodDebugInfoBuilder.cs @@ -111,7 +111,7 @@ public MethodDebugInfoBuilder(int decompilerSettingsVersion, StateMachineKind st /// public MethodDebugInfo Create() { TextSpan? methodSpan; - if (!(StartPosition is null) && !(EndPosition is null) && StartPosition.Value <= EndPosition.Value) + if (StartPosition is not null && EndPosition is not null && StartPosition.Value <= EndPosition.Value) methodSpan = TextSpan.FromBounds(StartPosition.Value, EndPosition.Value); else methodSpan = null; diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodStatementReference.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodStatementReference.cs index 40fe816d0b..22855cd7d1 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodStatementReference.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/MethodStatementReference.cs @@ -52,7 +52,7 @@ public MethodStatementReference(MethodDef method, uint? offset) { /// public override bool Equals(object? obj) { var other = obj as MethodStatementReference; - return !(other is null) && + return other is not null && Method == other.Method && Offset == other.Offset; } diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/TokenReference.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/TokenReference.cs index 1ceca30e57..eecdfacc24 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/TokenReference.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/TokenReference.cs @@ -58,7 +58,7 @@ public TokenReference(ModuleDef module, uint token) { /// /// /// - public bool Equals(TokenReference? other) => !(other is null) && Token == other.Token && ModuleDef == other.ModuleDef; + public bool Equals(TokenReference? other) => other is not null && Token == other.Token && ModuleDef == other.ModuleDef; /// /// Equals() diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/TypesHierarchyHelpers.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/TypesHierarchyHelpers.cs index 4c8ff935d5..e01075b9ea 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/TypesHierarchyHelpers.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/TypesHierarchyHelpers.cs @@ -33,7 +33,7 @@ public static bool IsBaseType(TypeDef? baseType, TypeDef? derivedType, bool reso var comparableBaseType = baseType.ResolveTypeDef(); if (comparableBaseType is null) return false; - while (!(derivedType.BaseType is null)) { + while (derivedType.BaseType is not null) { var resolvedBaseType = derivedType.BaseType.Resolve(); if (resolvedBaseType is null) return false; @@ -148,7 +148,7 @@ static bool MatchMethod(MethodDef? mCandidate, MethodBaseSig? mCandidateSig, Met public static bool MatchInterfaceMethod(MethodDef? candidate, MethodDef? method, ITypeDefOrRef interfaceContextType) { var genericInstSig = interfaceContextType.TryGetGenericInstSig(); - if (!(genericInstSig is null)) { + if (genericInstSig is not null) { return MatchMethod(candidate, candidate?.MethodSig, method, GenericArgumentResolver.Resolve(method?.MethodSig, genericInstSig.GenericArguments, null)); } else { @@ -181,7 +181,7 @@ public static IEnumerable FindBaseProperties(PropertyDef? property, continue; yield return baseProperty; var anyPropertyAccessor = baseProperty.GetMethod ?? baseProperty.SetMethod; - if (!(anyPropertyAccessor is null) && anyPropertyAccessor.IsNewSlot == anyPropertyAccessor.IsVirtual) + if (anyPropertyAccessor is not null && anyPropertyAccessor.IsNewSlot == anyPropertyAccessor.IsVirtual) yield break; } } @@ -215,7 +215,7 @@ public static IEnumerable FindBaseEvents(EventDef? eventDef, TypeDef? IsVisibleFromDerived(baseEvent, declType)) { yield return baseEvent; var anyEventAccessor = baseEvent.AddMethod ?? baseEvent.RemoveMethod ?? baseEvent.InvokeMethod; - if (!(anyEventAccessor is null) && anyEventAccessor.IsNewSlot == anyEventAccessor.IsVirtual) + if (anyEventAccessor is not null && anyEventAccessor.IsNewSlot == anyEventAccessor.IsVirtual) yield break; } } @@ -254,7 +254,7 @@ public static bool IsVisibleFromDerived(IMemberDef? baseMember, TypeDef? derived var derivedTypeAsm = derivedType.Module.Assembly; var asm = baseMember.DeclaringType.Module.Assembly; - if (!(derivedTypeAsm is null) && !(asm is null)) { + if (derivedTypeAsm is not null && asm is not null) { foreach (var attribute in asm.CustomAttributes) { if (!Compare(attribute.AttributeType, systemRuntimeCompilerServicesString, internalsVisibleToAttributeString)) continue; @@ -347,7 +347,7 @@ private static IEnumerable BaseTypes(TypeDef? typeDef) { typeDef = typeDef.BaseType.ResolveTypeDef(); if (typeDef is null) break; - } while (!(typeDef.BaseType is null)); + } while (typeDef.BaseType is not null); } public static IEnumerable GetTypeAndBaseTypes(TypeDef? type) { diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocKeyProvider.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocKeyProvider.cs index a2066898b5..f804c69f2f 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocKeyProvider.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocKeyProvider.cs @@ -72,7 +72,7 @@ public sealed class XmlDocKeyProvider { else { parameters = null; } - if (!(parameters is null) && parameters.Any(a => a.IsNormalMethodParameter)) { + if (parameters is not null && parameters.Any(a => a.IsNormalMethodParameter)) { b.Append('('); for (int i = 0; i < parameters.Count; i++) { var param = parameters[i]; @@ -84,7 +84,7 @@ public sealed class XmlDocKeyProvider { } b.Append(')'); } - if (!(explicitReturnType is null)) { + if (explicitReturnType is not null) { b.Append('~'); AppendTypeName(b, explicitReturnType); } @@ -95,12 +95,12 @@ public sealed class XmlDocKeyProvider { static IEnumerable GetParameters(PropertyDef property) { if (property is null) yield break; - if (!(property.GetMethod is null)) { + if (property.GetMethod is not null) { foreach (var param in property.GetMethod.Parameters) yield return param; yield break; } - if (!(property.SetMethod is null)) { + if (property.SetMethod is not null) { int last = property.SetMethod.Parameters.Count - 1; foreach (var param in property.SetMethod.Parameters) { if (param.Index != last) @@ -160,7 +160,7 @@ static void AppendTypeName(StringBuilder b, TypeSig type) { } else { var typeRef = type.ToTypeDefOrRef(); - if (!(typeRef.DeclaringType is null)) { + if (typeRef.DeclaringType is not null) { AppendTypeName(b, typeRef.DeclaringType.ToTypeSig()); b.Append('.'); b.Append(typeRef.Name); @@ -175,7 +175,7 @@ static int AppendTypeNameWithArguments(StringBuilder b, ITypeDefOrRef? type, ILi if (type is null) return 0; int outerTypeParameterCount = 0; - if (!(type.DeclaringType is null)) { + if (type.DeclaringType is not null) { ITypeDefOrRef declType = type.DeclaringType; outerTypeParameterCount = AppendTypeNameWithArguments(b, declType, genericArguments); b.Append('.'); @@ -289,7 +289,7 @@ public static string SplitTypeParameterCountFromReflectionName(string reflection if (type is null && pos > 0) { // Original code only entered if ns.Length > 0 // try if this is a nested type type = FindType(module, name.Substring(0, pos)); - if (!(type is null)) { + if (type is not null) { foreach (var nt in type.NestedTypes) { if (nt.Name == name) return nt; diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocLoader.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocLoader.cs index e5e88992db..b555e0a11b 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocLoader.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocLoader.cs @@ -37,7 +37,7 @@ public static class XmlDocLoader { static XmlDocumentationProvider? LoadMscorlibDocumentation() { string? xmlDocFile = FindXmlDocumentation("mscorlib.dll", MDHeaderRuntimeVersion.MS_CLR_40) ?? FindXmlDocumentation("mscorlib.dll", MDHeaderRuntimeVersion.MS_CLR_20); - if (!(xmlDocFile is null)) + if (xmlDocFile is not null) return XmlDocumentationProvider.Create(xmlDocFile); else return null; @@ -152,7 +152,7 @@ static string[] GetDirectories(string path) { fileName = null; foreach (var path in refAsmPathsV4) { fileName = LookupLocalizedXmlDoc(Path.Combine(path, assemblyFileName)); - if (!(fileName is null)) + if (fileName is not null) break; } fileName = fileName diff --git a/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocumentationProvider.cs b/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocumentationProvider.cs index fe2dab7f6d..c3f22f68a4 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocumentationProvider.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Decompiler/XmlDoc/XmlDocumentationProvider.cs @@ -150,7 +150,7 @@ public XmlDocumentationProvider(string fileName) ReadXmlDoc(xmlReader); } else { var redirectionTarget = GetRedirectionTarget(fileName, redirectAttr); - if (!(redirectionTarget is null)) { + if (redirectionTarget is not null) { //Debug.WriteLine("XmlDoc " + fileName + " is redirecting to " + redirectionTarget); using (FileStream redirectedFs = new FileStream(redirectionTarget, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) { using (XmlTextReader redirectedXmlReader = new XmlTextReader(redirectedFs)) { @@ -303,7 +303,7 @@ static void ReadMembersSection(XmlTextReader reader, LinePositionMapper linePosM if (reader.LocalName == "member") { int pos = linePosMapper.GetPositionForLine(reader.LineNumber) + Math.Max(reader.LinePosition - 2, 0); var memberAttr = (string?)reader.GetAttribute("name"); - if (!(memberAttr is null)) + if (memberAttr is not null) indexList.Add(new IndexEntry(GetHashCode(memberAttr), pos)); reader.Skip(); } @@ -372,7 +372,7 @@ static int GetHashCode(string key) // go through all items that have the correct hash while (++m < index.Length && index[m].HashCode == hashcode) { val = LoadDocumentation(key, index[m].PositionInFile); - if (!(val is null)) + if (val is not null) break; } // cache the result (even if it is null) diff --git a/dnSpy/dnSpy.Contracts.Logic/Resources/ResourceHelper.cs b/dnSpy/dnSpy.Contracts.Logic/Resources/ResourceHelper.cs index e808be12ab..1df05ec96a 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Resources/ResourceHelper.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Resources/ResourceHelper.cs @@ -43,7 +43,7 @@ public static class ResourceHelper { internal static void SetResourceManagerTokenCache(ResourceManagerTokenCache tokenCache) { if (tokenCache is null) throw new ArgumentNullException(nameof(tokenCache)); - if (!(resourceManagerTokenCache is null)) + if (resourceManagerTokenCache is not null) throw new InvalidOperationException(); resourceManagerTokenCache = tokenCache; } @@ -55,7 +55,7 @@ internal static void SetResourceManagerTokenCache(ResourceManagerTokenCache toke /// String /// public static string? GetStringOrNull(object obj, string? value) { - Debug2.Assert(!(resourceManagerTokenCache is null)); + Debug2.Assert(resourceManagerTokenCache is not null); if (obj is null) throw new ArgumentNullException(nameof(obj)); if (value is null) @@ -70,7 +70,7 @@ internal static void SetResourceManagerTokenCache(ResourceManagerTokenCache toke /// String /// public static string GetString(object obj, string value) { - Debug2.Assert(!(resourceManagerTokenCache is null)); + Debug2.Assert(resourceManagerTokenCache is not null); if (obj is null) throw new ArgumentNullException(nameof(obj)); if (value is null) @@ -82,7 +82,7 @@ public static string GetString(object obj, string value) { if (mgr is null) return "???"; var s = mgr.GetString(key); - Debug2.Assert(!(s is null)); + Debug2.Assert(s is not null); return s ?? "???"; } @@ -91,8 +91,8 @@ public static string GetString(object obj, string value) { return mgr; var tokenCache = resourceManagerTokenCache; - Debug2.Assert(!(tokenCache is null)); - if (!(tokenCache is null)) { + Debug2.Assert(tokenCache is not null); + if (tokenCache is not null) { if (tokenCache.TryGetResourceManagerGetMethodMetadataToken(assembly, out int getMethodMetadataToken)) { MethodInfo? method; try { @@ -103,7 +103,7 @@ public static string GetString(object obj, string value) { method = null; } mgr = TrySetResourceManager(assembly, method, save: false); - if (!(mgr is null)) + if (mgr is not null) return mgr; } } @@ -116,7 +116,7 @@ public static string GetString(object obj, string value) { continue; var m = prop.GetGetMethod(); mgr = TrySetResourceManager(assembly, m, save: true); - if (!(mgr is null)) + if (mgr is not null) return mgr; } diff --git a/dnSpy/dnSpy.Contracts.Logic/Text/ITextColorWriterExtensions.cs b/dnSpy/dnSpy.Contracts.Logic/Text/ITextColorWriterExtensions.cs index 6f8824592c..3e3c11e11c 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Text/ITextColorWriterExtensions.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Text/ITextColorWriterExtensions.cs @@ -94,8 +94,8 @@ public static T Write(this T output, IAssembly? asm) where T : ITextColorWrit if (asm is null) return output; var asmDef = asm as AssemblyDef; - bool isExe = !(asmDef is null) && - !(asmDef.ManifestModule is null) && + bool isExe = asmDef is not null && + asmDef.ManifestModule is not null && (asmDef.ManifestModule.Characteristics & dnlib.PE.Characteristics.Dll) == 0; output.Write(isExe ? BoxedTextColor.AssemblyExe : BoxedTextColor.Assembly, asm.Name); @@ -119,7 +119,7 @@ public static T Write(this T output, IAssembly? asm) where T : ITextColorWrit if (PublicKeyBase.IsNullOrEmpty2(publicKey)) output.Write(BoxedTextColor.Keyword, "null"); else { - Debug2.Assert(!(publicKey is null)); + Debug2.Assert(publicKey is not null); output.Write(BoxedTextColor.Number, publicKey.ToString()); } diff --git a/dnSpy/dnSpy.Contracts.Logic/Text/Indenter.cs b/dnSpy/dnSpy.Contracts.Logic/Text/Indenter.cs index 5b0659b0bc..0aab872c65 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Text/Indenter.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Text/Indenter.cs @@ -74,7 +74,7 @@ string GetIndentString(int level) { cachedStrings.Add(null); var s = cachedStrings[level]; - if (!(s is null)) + if (s is not null) return s; s = CreateIndentString(level); cachedStrings[level] = s; diff --git a/dnSpy/dnSpy.Contracts.Logic/Utilities/GacInfo.cs b/dnSpy/dnSpy.Contracts.Logic/Utilities/GacInfo.cs index be4a139599..984a1450c0 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Utilities/GacInfo.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Utilities/GacInfo.cs @@ -137,7 +137,7 @@ static GacInfo() { var newWinmdPaths = new List(); bool hasGAC2; - if (!(Type.GetType("Mono.Runtime") is null)) { + if (Type.GetType("Mono.Runtime") is not null) { hasGAC2 = false; var dirs = new Dictionary(StringComparer.OrdinalIgnoreCase); var extraMonoPathsList = new List(); @@ -164,7 +164,7 @@ static GacInfo() { } var paths = Environment.GetEnvironmentVariable("MONO_PATH"); - if (!(paths is null)) { + if (paths is not null) { foreach (var tmp in paths.Split(Path.PathSeparator)) { var path = tmp.Trim(); if (path != string.Empty && Directory.Exists(path)) diff --git a/dnSpy/dnSpy.Contracts.Logic/Utilities/SimpleTypeConverter.cs b/dnSpy/dnSpy.Contracts.Logic/Utilities/SimpleTypeConverter.cs index f08224736f..07fc808a38 100644 --- a/dnSpy/dnSpy.Contracts.Logic/Utilities/SimpleTypeConverter.cs +++ b/dnSpy/dnSpy.Contracts.Logic/Utilities/SimpleTypeConverter.cs @@ -317,7 +317,7 @@ public static string ToString(string? s, bool canHaveNull) { static ulong ParseUnsigned(string s, ulong min, ulong max, out string? error) { error = TryParseUnsigned(s, min, max, out ulong value); - if (!(error is null)) + if (error is not null) return 0; return value; } @@ -421,7 +421,7 @@ public static bool ParseBoolean(string s, out string? error) { public static char ParseChar(string s, out string? error) { int index = 0; char c = ParseChar(s, ref index, out error); - if (!(error is null)) + if (error is not null) return (char)0; SkipSpaces(s, ref index); if (index != s.Length) @@ -495,7 +495,7 @@ static char ParseChar(string s, ref int index, out string? error) { public static string? ParseString(string s, bool canHaveNull, out string? error) { int index = 0; var res = ParseString(s, canHaveNull, ref index, out error); - if (!(error is null)) + if (error is not null) return null; SkipSpaces(s, ref index); if (index != s.Length) @@ -692,7 +692,7 @@ static int ParseHex(string s, ref int index, int hexChars, out char surrogate) { static long ParseSigned(string s, long min, long max, object minObject, out string? error) { error = TryParseSigned(s, min, max, minObject, out long value); - if (!(error is null)) + if (error is not null) return 0; return value; } @@ -882,7 +882,7 @@ static string ToString(IList list, Func toString) { return null; } var res = parseValue(value); - if (!(res.error is null)) { + if (res.error is not null) { error = res.error; return null; } @@ -907,7 +907,7 @@ static string ToString(IList list, Func toString) { while (true) { int oldIndex = index; list.Add(parseValue(data, s, ref index, out error)); - if (!(error is null)) + if (error is not null) return null; Debug.Assert(oldIndex < index); if (oldIndex >= index) diff --git a/dnSpy/dnSpy.Decompiler/CSharp/CSharpFormatter.cs b/dnSpy/dnSpy.Decompiler/CSharp/CSharpFormatter.cs index 39fb144c0f..6872717b87 100644 --- a/dnSpy/dnSpy.Decompiler/CSharp/CSharpFormatter.cs +++ b/dnSpy/dnSpy.Decompiler/CSharp/CSharpFormatter.cs @@ -202,7 +202,7 @@ void WriteSystemType(string name, bool isValueType) { void WriteToken(IMDTokenProvider tok) { if (!ShowTokens) return; - Debug2.Assert(!(tok is null)); + Debug2.Assert(tok is not null); if (tok is null) return; OutputWrite(CommentBegin + ToFormattedUInt32(tok.MDToken.Raw) + CommentEnd, BoxedTextColor.Comment); @@ -214,22 +214,22 @@ public void WriteToolTip(IMemberRef? member) { return; } - if (member is IMethod method && !(method.MethodSig is null)) { + if (member is IMethod method && method.MethodSig is not null) { WriteToolTip(method); return; } - if (member is IField field && !(field.FieldSig is null)) { + if (member is IField field && field.FieldSig is not null) { WriteToolTip(field); return; } - if (member is PropertyDef prop && !(prop.PropertySig is null)) { + if (member is PropertyDef prop && prop.PropertySig is not null) { WriteToolTip(prop); return; } - if (member is EventDef evt && !(evt.EventType is null)) { + if (member is EventDef evt && evt.EventType is not null) { WriteToolTip(evt); return; } @@ -253,22 +253,22 @@ public void Write(IMemberRef? member) { return; } - if (member is IMethod method && !(method.MethodSig is null)) { + if (member is IMethod method && method.MethodSig is not null) { Write(method); return; } - if (member is IField field && !(field.FieldSig is null)) { + if (member is IField field && field.FieldSig is not null) { Write(field); return; } - if (member is PropertyDef prop && !(prop.PropertySig is null)) { + if (member is PropertyDef prop && prop.PropertySig is not null) { Write(prop); return; } - if (member is EventDef evt && !(evt.EventType is null)) { + if (member is EventDef evt && evt.EventType is not null) { Write(evt); return; } @@ -324,9 +324,9 @@ void WriteToolTip(IMethod? method) { Write(method); var td = method.DeclaringType.ResolveTypeDef(); - if (!(td is null)) { + if (td is not null) { var s = TypeFormatterUtils.GetNumberOfOverloadsString(td, method); - if (!(s is null)) + if (s is not null) OutputWrite(s, BoxedTextColor.Text); } } @@ -337,7 +337,7 @@ void WriteType(ITypeDefOrRef type, bool useNamespaces, bool useTypeKeywords) { td = ((TypeRef)type).Resolve(); if (td is null || td.GenericParameters.Count == 0 || - (!(td.DeclaringType is null) && td.DeclaringType.GenericParameters.Count >= td.GenericParameters.Count)) { + (td.DeclaringType is not null && td.DeclaringType.GenericParameters.Count >= td.GenericParameters.Count)) { var oldFlags = options; options &= ~(FormatterOptions.ShowNamespaces | FormatterOptions.ShowIntrinsicTypeKeywords); if (useNamespaces) @@ -350,7 +350,7 @@ void WriteType(ITypeDefOrRef type, bool useNamespaces, bool useTypeKeywords) { } int numGenParams = td.GenericParameters.Count; - if (!(type.DeclaringType is null)) { + if (type.DeclaringType is not null) { var oldFlags = options; options &= ~(FormatterOptions.ShowNamespaces | FormatterOptions.ShowIntrinsicTypeKeywords); if (useNamespaces) @@ -377,11 +377,11 @@ void WriteType(ITypeDefOrRef type, bool useNamespaces, bool useTypeKeywords) { bool WriteRefIfByRef(TypeSig? typeSig, ParamDef? pd, bool forceReadOnly) { if (typeSig.RemovePinnedAndModifiers() is ByRefSig) { - if (!(pd is null) && (!pd.IsIn && pd.IsOut)) { + if (pd is not null && (!pd.IsIn && pd.IsOut)) { OutputWrite(Keyword_out, BoxedTextColor.Keyword); WriteSpace(); } - else if (!(pd is null) && (pd.IsIn && !pd.IsOut && TypeFormatterUtils.IsReadOnlyParameter(pd))) { + else if (pd is not null && (pd.IsIn && !pd.IsOut && TypeFormatterUtils.IsReadOnlyParameter(pd))) { OutputWrite(Keyword_in, BoxedTextColor.Keyword); WriteSpace(); } @@ -445,15 +445,15 @@ void Write(IMethod? method) { WriteModuleName(info); string[]? operatorInfo; - if (!(info.MethodDef is null) && info.MethodDef.IsConstructor && !(method.DeclaringType is null)) + if (info.MethodDef is not null && info.MethodDef.IsConstructor && method.DeclaringType is not null) operatorInfo = null; - else if (!(info.MethodDef is null) && info.MethodDef.Overrides.Count > 0) { + else if (info.MethodDef is not null && info.MethodDef.Overrides.Count > 0) { var ovrMeth = (IMemberRef)info.MethodDef.Overrides[0].MethodDeclaration; operatorInfo = TryGetOperatorInfo(ovrMeth.Name); } else operatorInfo = TryGetOperatorInfo(method.Name); - bool isExplicitOrImplicit = !(operatorInfo is null) && (operatorInfo[0] == "explicit" || operatorInfo[0] == "implicit"); + bool isExplicitOrImplicit = operatorInfo is not null && (operatorInfo[0] == "explicit" || operatorInfo[0] == "implicit"); if (!isExplicitOrImplicit) WriteReturnType(info, writeSpace: true, isReadOnly: TypeFormatterUtils.IsReadOnlyMethod(info.MethodDef)); @@ -462,9 +462,9 @@ void Write(IMethod? method) { Write(method.DeclaringType); WritePeriod(); } - if (!(info.MethodDef is null) && info.MethodDef.IsConstructor && !(method.DeclaringType is null)) + if (info.MethodDef is not null && info.MethodDef.IsConstructor && method.DeclaringType is not null) WriteIdentifier(TypeFormatterUtils.RemoveGenericTick(method.DeclaringType.Name), CSharpMetadataTextColorProvider.Instance.GetColor(method)); - else if (!(info.MethodDef is null) && info.MethodDef.Overrides.Count > 0) { + else if (info.MethodDef is not null && info.MethodDef.Overrides.Count > 0) { var ovrMeth = (IMemberRef)info.MethodDef.Overrides[0].MethodDeclaration; WriteMethodName(method, ovrMeth.Name, operatorInfo); } @@ -490,7 +490,7 @@ void Write(IMethod? method) { void WriteOperatorInfoString(string s) => OutputWrite(s, 'a' <= s[0] && s[0] <= 'z' ? BoxedTextColor.Keyword : BoxedTextColor.Operator); void WriteMethodName(IMethod method, string name, string[]? operatorInfo) { - if (!(operatorInfo is null)) { + if (operatorInfo is not null) { for (int i = 0; i < operatorInfo.Length; i++) { if (i > 0) WriteSpace(); @@ -517,12 +517,12 @@ void Write(IField? field, bool isToolTip) { var sig = field.FieldSig; var td = field.DeclaringType.ResolveTypeDef(); - bool isEnumOwner = !(td is null) && td.IsEnum; + bool isEnumOwner = td is not null && td.IsEnum; var fd = field.ResolveFieldDef(); object? constant = null; - bool isConstant = !(fd is null) && (fd.IsLiteral || (fd.IsStatic && fd.IsInitOnly)) && TypeFormatterUtils.HasConstant(fd, out var constantAttribute) && TypeFormatterUtils.TryGetConstant(fd, constantAttribute, out constant); - if (!isEnumOwner || (!(fd is null) && !fd.IsLiteral)) { + bool isConstant = fd is not null && (fd.IsLiteral || (fd.IsStatic && fd.IsInitOnly)) && TypeFormatterUtils.HasConstant(fd, out var constantAttribute) && TypeFormatterUtils.TryGetConstant(fd, constantAttribute, out constant); + if (!isEnumOwner || (fd is not null && !fd.IsLiteral)) { if (isToolTip) { OutputWrite(DescriptionParenOpen, BoxedTextColor.Punctuation); OutputWrite(isConstant ? dnSpy_Decompiler_Resources.ToolTip_Constant : dnSpy_Decompiler_Resources.ToolTip_Field, BoxedTextColor.Text); @@ -652,7 +652,7 @@ void Write(PropertyDef? prop, bool writeAccessors) { WriteGenericArguments(info); WriteMethodParameterList(info, IndexerParenOpen, IndexerParenClose); } - else if (!(ovrMeth is null) && TypeFormatterUtils.GetPropertyName(ovrMeth) is string ovrMethPropName) + else if (ovrMeth is not null && TypeFormatterUtils.GetPropertyName(ovrMeth) is string ovrMethPropName) WriteIdentifier(ovrMethPropName, CSharpMetadataTextColorProvider.Instance.GetColor(prop)); else WriteIdentifier(prop.Name, CSharpMetadataTextColorProvider.Instance.GetColor(prop)); @@ -733,7 +733,7 @@ void WriteToolTip(ITypeDefOrRef type) { Write(TypeFormatterUtils.GetMemberSpecialFlags(type)); MethodDef invoke; - if (TypeFormatterUtils.IsDelegate(td) && !((invoke = td.FindMethod("Invoke")) is null) && !(invoke.MethodSig is null)) { + if (TypeFormatterUtils.IsDelegate(td) && (invoke = td.FindMethod("Invoke")) is not null && invoke.MethodSig is not null) { OutputWrite(Keyword_delegate, BoxedTextColor.Keyword); WriteSpace(); @@ -796,13 +796,13 @@ void Write(ITypeDefOrRef? type, bool showModuleNames = false) { return; } - if (!(type.DeclaringType is null)) { + if (type.DeclaringType is not null) { Write(type.DeclaringType); WritePeriod(); } string? keyword = GetTypeKeyword(type); - if (!(keyword is null)) + if (keyword is not null) OutputWrite(keyword, BoxedTextColor.Keyword); else { if (showModuleNames) @@ -831,7 +831,7 @@ void WriteNamespace(string ns) { string? GetTypeKeyword(ITypeDefOrRef? type) { if (!ShowIntrinsicTypeKeywords) return null; - if (type is null || !(type.DeclaringType is null) || type.Namespace != "System" || !type.DefinitionAssembly.IsCorLib()) + if (type is null || type.DeclaringType is not null || type.Namespace != "System" || !type.DefinitionAssembly.IsCorLib()) return null; switch (type.TypeName) { case "Void": return "void"; @@ -877,13 +877,13 @@ void Write(TypeSig? type, IList? typeGenArgs, IList? methGenAr methGenArgs = Array.Empty(); List? list = null; - while (!(type is null) && (type.ElementType == ElementType.SZArray || type.ElementType == ElementType.Array)) { + while (type is not null && (type.ElementType == ElementType.SZArray || type.ElementType == ElementType.Array)) { if (list is null) list = new List(); list.Add((ArraySigBase)type); type = type.Next; } - if (!(list is null)) { + if (list is not null) { Write(list[list.Count - 1].Next, typeGenArgs, Array.Empty()); foreach (var aryType in list) { if (aryType.ElementType == ElementType.Array) { @@ -967,11 +967,11 @@ void Write(TypeSig? type, IList? typeGenArgs, IList? methGenAr case ElementType.Var: case ElementType.MVar: var gsType = Read(type.ElementType == ElementType.Var ? typeGenArgs : methGenArgs, (int)((GenericSig)type).Number); - if (!(gsType is null)) + if (gsType is not null) Write(gsType, typeGenArgs, methGenArgs); else { var gp = ((GenericSig)type).GenericParam; - if (!(gp is null)) + if (gp is not null) Write(gp); else { if (type.ElementType == ElementType.MVar) { @@ -988,7 +988,7 @@ void Write(TypeSig? type, IList? typeGenArgs, IList? methGenAr case ElementType.GenericInst: var gis = (GenericInstSig?)type; - Debug2.Assert(!(gis is null)); + Debug2.Assert(gis is not null); if (TypeFormatterUtils.IsSystemNullable(gis)) { Write(GenericArgumentResolver.Resolve(gis.GenericArguments[0], typeGenArgs, methGenArgs), null, null); OutputWrite("?", BoxedTextColor.Operator); @@ -1035,7 +1035,7 @@ void Write(TypeSig? type, IList? typeGenArgs, IList? methGenAr WriteCommaSpace(); Write(sig.Params[i], typeGenArgs, methGenArgs); } - if (!(sig.ParamsAfterSentinel is null)) { + if (sig.ParamsAfterSentinel is not null) { if (sig.Params.Count > 0) WriteCommaSpace(); OutputWrite("...", BoxedTextColor.Punctuation); @@ -1091,7 +1091,7 @@ public void WriteToolTip(ISourceVariable? variable) { Write(variable.Type, !isLocal ? ((Parameter)variable.Variable!).ParamDef : null, null, null, forceReadOnly: (variable.Flags & SourceVariableFlags.ReadOnlyReference) != 0); WriteSpace(); WriteIdentifier(TypeFormatterUtils.GetName(variable), isLocal ? BoxedTextColor.Local : BoxedTextColor.Parameter); - if (!(pd is null)) + if (pd is not null) WriteToken(pd); } @@ -1158,7 +1158,7 @@ void WriteReturnType(in FormatterMethodInfo info, bool writeSpace, bool isReadOn } void ForceWriteReturnType(in FormatterMethodInfo info, bool writeSpace, bool isReadOnly) { - if (!(!(info.MethodDef is null) && info.MethodDef.IsConstructor)) { + if (!(info.MethodDef is not null && info.MethodDef.IsConstructor)) { TypeSig? retType; ParamDef? retParamDef; if (info.RetTypeIsLastArgType) { @@ -1189,9 +1189,9 @@ void ForceWriteReturnType(in FormatterMethodInfo info, bool writeSpace, bool isR void WriteGenericArguments(in FormatterMethodInfo info) { if (info.MethodSig.GenParamCount > 0) { - if (!(info.MethodGenericParams is null)) + if (info.MethodGenericParams is not null) WriteGenerics(info.MethodGenericParams, BoxedTextColor.MethodGenericParameter, GenericParamContext.Create(info.MethodDef)); - else if (!(info.MethodDef is null)) + else if (info.MethodDef is not null) WriteGenerics(info.MethodDef.GenericParameters, BoxedTextColor.MethodGenericParameter); } } @@ -1209,7 +1209,7 @@ void WriteMethodParameterList(in FormatterMethodInfo info, string lparen, string if (i > 0) WriteCommaSpace(); ParamDef? pd; - if (!(info.MethodDef is null) && baseIndex + i < info.MethodDef.Parameters.Count) + if (info.MethodDef is not null && baseIndex + i < info.MethodDef.Parameters.Count) pd = info.MethodDef.Parameters[baseIndex + i].ParamDef; else pd = null; @@ -1222,7 +1222,7 @@ void WriteMethodParameterList(in FormatterMethodInfo info, string lparen, string if (ShowParameterTypes) { needSpace = true; - if (!(pd is null) && pd.CustomAttributes.IsDefined("System.ParamArrayAttribute")) { + if (pd is not null && pd.CustomAttributes.IsDefined("System.ParamArrayAttribute")) { OutputWrite(Keyword_params, BoxedTextColor.Keyword); WriteSpace(); } @@ -1234,7 +1234,7 @@ void WriteMethodParameterList(in FormatterMethodInfo info, string lparen, string WriteSpace(); needSpace = true; - if (!(pd is null)) { + if (pd is not null) { WriteIdentifier(pd.Name, BoxedTextColor.Parameter); WriteToken(pd); } @@ -1253,7 +1253,7 @@ void WriteMethodParameterList(in FormatterMethodInfo info, string lparen, string var t = info.MethodSig.Params[i].RemovePinnedAndModifiers(); if (t.GetElementType() == ElementType.ByRef) t = t.Next; - if (constant is null && !(t is null) && t.IsValueType) + if (constant is null && t is not null && t.IsValueType) OutputWrite(Keyword_default, BoxedTextColor.Keyword); else WriteConstant(constant); diff --git a/dnSpy/dnSpy.Decompiler/DecompilerBase.cs b/dnSpy/dnSpy.Decompiler/DecompilerBase.cs index 446e1ba423..4af7f2c455 100644 --- a/dnSpy/dnSpy.Decompiler/DecompilerBase.cs +++ b/dnSpy/dnSpy.Decompiler/DecompilerBase.cs @@ -81,7 +81,7 @@ protected void WriteAssembly(AssemblyDef asm, IDecompilerOutput output, Decompil output.WriteLine(); PrintEntryPoint(asm.ManifestModule, output); var peImage = TryGetPEImage(asm.ManifestModule); - if (!(peImage is null)) + if (peImage is not null) WriteTimestampComment(output, peImage); output.WriteLine(); } @@ -119,11 +119,11 @@ protected void WriteModule(ModuleDef mod, IDecompilerOutput output, Decompilatio this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_ThisAssemblyContainsUnmanagedCode); } string? runtimeName = GetRuntimeDisplayName(mod); - if (!(runtimeName is null)) { + if (runtimeName is not null) { this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_Runtime + " " + runtimeName); } var peImage = TryGetPEImage(mod); - if (!(peImage is null)) + if (peImage is not null) WriteTimestampComment(output, peImage); output.WriteLine(); } @@ -151,7 +151,7 @@ protected void PrintEntryPoint(ModuleDef mod, IDecompilerOutput output) { else if (ep is MethodDef epMethod) { WriteCommentBegin(output, true); output.Write(dnSpy_Decompiler_Resources.Decompile_EntryPoint + " ", BoxedTextColor.Comment); - if (!(epMethod.DeclaringType is null)) { + if (epMethod.DeclaringType is not null) { output.Write(IdentifierEscaper.Escape(epMethod.DeclaringType.FullName), epMethod.DeclaringType, DecompilerReferenceFlags.None, BoxedTextColor.Comment); output.Write(".", BoxedTextColor.Comment); } @@ -163,7 +163,7 @@ protected void PrintEntryPoint(ModuleDef mod, IDecompilerOutput output) { object? GetEntryPoint(ModuleDef? module) { int maxIters = 1; - for (int i = 0; !(module is null) && i < maxIters; i++) { + for (int i = 0; module is not null && i < maxIters; i++) { var rva = module.NativeEntryPoint; if (rva != 0) return (uint)rva; diff --git a/dnSpy/dnSpy.Decompiler/FilenameUtils.cs b/dnSpy/dnSpy.Decompiler/FilenameUtils.cs index b22c256426..f0bcd160d7 100644 --- a/dnSpy/dnSpy.Decompiler/FilenameUtils.cs +++ b/dnSpy/dnSpy.Decompiler/FilenameUtils.cs @@ -48,7 +48,7 @@ public static string CleanName(string text) { textChars[i] = '-'; } } - if (!(textChars is null)) + if (textChars is not null) text = new string(textChars); if (ReservedFileNames.Contains(text)) diff --git a/dnSpy/dnSpy.Decompiler/FormatterMethodInfo.cs b/dnSpy/dnSpy.Decompiler/FormatterMethodInfo.cs index ad07c82bbf..545854ab57 100644 --- a/dnSpy/dnSpy.Decompiler/FormatterMethodInfo.cs +++ b/dnSpy/dnSpy.Decompiler/FormatterMethodInfo.cs @@ -41,20 +41,20 @@ public FormatterMethodInfo(IMethod method, bool retTypeIsLastArgType = false, bo MethodDef = method as MethodDef; var ms = method as MethodSpec; var mr = method as MemberRef; - if (!(ms is null)) { + if (ms is not null) { var ts = ms.Method is null ? null : ms.Method.DeclaringType as TypeSpec; - if (!(ts is null)) { + if (ts is not null) { if (ts.TypeSig.RemovePinnedAndModifiers() is GenericInstSig gp) TypeGenericParams = gp.GenericArguments; } var gsSig = ms.GenericInstMethodSig; - if (!(gsSig is null)) + if (gsSig is not null) MethodGenericParams = gsSig.GenericArguments; MethodDef = ms.Method.ResolveMethodDef(); } - else if (!(mr is null)) { + else if (mr is not null) { if (mr.DeclaringType is TypeSpec ts) { if (ts.TypeSig.RemovePinnedAndModifiers() is GenericInstSig gp) TypeGenericParams = gp.GenericArguments; diff --git a/dnSpy/dnSpy.Decompiler/IL/ILLanguageHelper.cs b/dnSpy/dnSpy.Decompiler/IL/ILLanguageHelper.cs index 3afb4992b5..512856810e 100644 --- a/dnSpy/dnSpy.Decompiler/IL/ILLanguageHelper.cs +++ b/dnSpy/dnSpy.Decompiler/IL/ILLanguageHelper.cs @@ -31,13 +31,13 @@ public static class ILLanguageHelper { else if (hi != 0) return null; var s = cachedOpCodeDocs[index]; - if (!(s is null)) + if (s is not null) return s; var docProvider = XmlDocLoader.MscorlibDocumentation; - if (!(docProvider is null)) { + if (docProvider is not null) { string? docXml = docProvider.GetDocumentation("F:System.Reflection.Emit.OpCodes." + code.Code.ToString()); - if (!(docXml is null)) { + if (docXml is not null) { XmlDocRenderer renderer = new XmlDocRenderer(); renderer.AddXmlDocumentation(docXml); return cachedOpCodeDocs[index] = renderer.ToString(); diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/BamlResourceProjectFile.cs b/dnSpy/dnSpy.Decompiler/MSBuild/BamlResourceProjectFile.cs index 188891b075..1ce4bd2294 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/BamlResourceProjectFile.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/BamlResourceProjectFile.cs @@ -110,10 +110,10 @@ public override void Create(DecompileContext ctx) { } var body = GetInitializeComponentBody(); - Debug2.Assert(!(body is null)); - if (!(body is null)) { + Debug2.Assert(body is not null); + if (body is not null) { var startupUri = GetStartupUri(body); - if (!(startupUri is null)) + if (startupUri is not null) writer.WriteAttributeString("StartupUri", startupUri); foreach (var info in GetEvents(body)) diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/DefaultNamespaceFinder.cs b/dnSpy/dnSpy.Decompiler/MSBuild/DefaultNamespaceFinder.cs index afbfb4f43b..a0904db34f 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/DefaultNamespaceFinder.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/DefaultNamespaceFinder.cs @@ -54,7 +54,7 @@ public string Find() { var modNs = GetModuleNamespace(module); var foundNs = info2.CommonPrefix; - if (!string.IsNullOrEmpty(modNs) && !(foundNs is null) && foundNs.StartsWith(modNs + ".")) + if (!string.IsNullOrEmpty(modNs) && foundNs is not null && foundNs.StartsWith(modNs + ".")) foundNs = modNs; return foundNs ?? string.Empty; @@ -68,7 +68,7 @@ Info PickNamespace(List infos) { var modNs = GetModuleNamespace(module); var info = infos.FirstOrDefault(a => modNs.Equals(a.CommonPrefix) || a.CommonPrefix.StartsWith(modNs)); - if (!(info.CommonPrefix is null)) + if (info.CommonPrefix is not null) return info; // Here if it's eg. mscorlib, System.Xml or other system assemblies with several @@ -86,7 +86,7 @@ static string GetCommon(string[] namespaces) { else foundNs = GetCommonNamespace(sb, foundNs, ns); } - Debug2.Assert(!(foundNs is null)); + Debug2.Assert(foundNs is not null); return foundNs ?? string.Empty; } @@ -114,7 +114,7 @@ static string GetCommonNamespace(StringBuilder sb, string a, string b) { static string GetModuleNamespace(ModuleDef module) { var asm = module.Assembly; string s; - if (!(asm is null) && module.IsManifestModule) + if (asm is not null && module.IsManifestModule) s = asm.Name; else { s = module.Name; diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/DotNetUtils.cs b/dnSpy/dnSpy.Decompiler/MSBuild/DotNetUtils.cs index 3b78ee540d..2d229bf1aa 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/DotNetUtils.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/DotNetUtils.cs @@ -24,7 +24,7 @@ You should have received a copy of the GNU General Public License namespace dnSpy.Decompiler.MSBuild { static class DotNetUtils { static bool IsType(TypeDef type, string typeFullName) { - while (!(type is null)) { + while (type is not null) { var bt = type.BaseType; if (bt is null) break; @@ -37,13 +37,13 @@ static bool IsType(TypeDef type, string typeFullName) { public static bool IsWinForm(TypeDef type) => IsType(type, "System.Windows.Forms.Form"); public static bool IsSystemWindowsApplication(TypeDef type) => IsType(type, "System.Windows.Application"); - public static bool IsStartUpClass(TypeDef type) => !(type.Module.EntryPoint is null) && type.Module.EntryPoint.DeclaringType == type; + public static bool IsStartUpClass(TypeDef type) => type.Module.EntryPoint is not null && type.Module.EntryPoint.DeclaringType == type; public static bool IsUnsafe(ModuleDef module) => module.CustomAttributes.IsDefined("System.Security.UnverifiableCodeAttribute"); public static IEnumerable GetFields(MethodDef method) => GetDefs(method).OfType(); public static IEnumerable GetDefs(MethodDef method) { var body = method.Body; - if (!(body is null)) { + if (body is not null) { foreach (var instr in body.Instructions) { if (instr.Operand is IMemberDef def && def.DeclaringType == method.DeclaringType) yield return def; diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/FilenameCreator.cs b/dnSpy/dnSpy.Decompiler/MSBuild/FilenameCreator.cs index fdfd0bc414..27489b5db6 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/FilenameCreator.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/FilenameCreator.cs @@ -51,7 +51,7 @@ public FilenameCreator(string baseDir, string defaultNamespace) { } public string Create(string fileExt, string fullName) { - Debug2.Assert(!(fileExt is null) && fileExt.Length > 1 && fileExt[0] == '.'); + Debug2.Assert(fileExt is not null && fileExt.Length > 1 && fileExt[0] == '.'); string name = StripDefaultNamespace(fullName); if (string.IsNullOrEmpty(name)) name = fullName; @@ -59,7 +59,7 @@ public string Create(string fileExt, string fullName) { } public string CreateFromNamespaceName(string fileExt, string ns, string name) { - Debug2.Assert(!(fileExt is null) && fileExt.Length > 1 && fileExt[0] == '.'); + Debug2.Assert(fileExt is not null && fileExt.Length > 1 && fileExt[0] == '.'); var list = GetNamespaceParts(ns); list.Add(name); return Create(list.ToArray(), fileExt); @@ -110,7 +110,7 @@ string Create(string[] parts, string fileExt) { public string Create(ModuleDef module) { string name; var asm = module.Assembly; - if (!(asm is null) && module.IsManifestModule) + if (asm is not null && module.IsManifestModule) name = module.Assembly.Name; else name = FileUtils.GetFilename(module.Name); diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/MSBuildProjectCreator.cs b/dnSpy/dnSpy.Decompiler/MSBuild/MSBuildProjectCreator.cs index fd627d367c..2712663ab4 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/MSBuildProjectCreator.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/MSBuildProjectCreator.cs @@ -39,7 +39,7 @@ sealed class MSBuildProjectCreator { public string SolutionFilename { get { - Debug2.Assert(!(options.SolutionFilename is null)); + Debug2.Assert(options.SolutionFilename is not null); return Path.Combine(options.Directory, options.SolutionFilename); } } @@ -142,7 +142,7 @@ public void Create() { progressListener.SetProgress(maxProgress); } finally { - if (!(satelliteAssemblyFinder is null)) + if (satelliteAssemblyFinder is not null) satelliteAssemblyFinder.Dispose(); } } diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/Project.cs b/dnSpy/dnSpy.Decompiler/MSBuild/Project.cs index 131db30162..36e16bf035 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/Project.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/Project.cs @@ -96,11 +96,11 @@ public void CreateProjectFiles(DecompileContext ctx) { } var ep = Options.Module.EntryPoint; - if (!(ep is null) && !(ep.DeclaringType is null)) + if (ep is not null && ep.DeclaringType is not null) StartupObject = ep.DeclaringType.ReflectionFullName; applicationManifest = ApplicationManifest.TryCreate(Options.Module.Win32Resources, filenameCreator); - if (!(ApplicationManifest is null)) + if (ApplicationManifest is not null) Files.Add(new ApplicationManifestProjectFile(ApplicationManifest.Filename)); foreach (var rsrc in Options.Module.Resources) { @@ -192,7 +192,7 @@ void InitializeSplashScreen() { ProjectFile CreateTypeProjectFile(TypeDef type, FilenameCreator filenameCreator) { var bamlFile = TryGetBamlFile(type); - if (!(bamlFile is null)) { + if (bamlFile is not null) { var filename = filenameCreator.Create(GetTypeExtension(type), type.FullName); TypeProjectFile newFile; var isAppType = DotNetUtils.IsSystemWindowsApplication(type); @@ -213,19 +213,19 @@ ProjectFile CreateTypeProjectFile(TypeDef type, FilenameCreator filenameCreator) const string DESIGNER = ".Designer"; var resxFile = TryGetResXFile(type); if (DotNetUtils.IsWinForm(type)) { - var fname = !(resxFile is null) ? Path.GetFileNameWithoutExtension(resxFile.Filename) : type.Name.String; + var fname = resxFile is not null ? Path.GetFileNameWithoutExtension(resxFile.Filename) : type.Name.String; var filename = filenameCreator.CreateFromNamespaceName(GetTypeExtension(type), type.ReflectionNamespace, fname); var dname = filenameCreator.CreateFromNamespaceName(GetTypeExtension(type), type.ReflectionNamespace, fname + DESIGNER); var newFile = new WinFormsProjectFile(type, filename, Options.DecompilationContext, Options.Decompiler, createDecompilerOutput); - if (!(resxFile is null)) + if (resxFile is not null) resxFile.DependentUpon = newFile; var winFormsDesignerFile = new WinFormsDesignerProjectFile(newFile, dname, createDecompilerOutput); winFormsDesignerFile.DependentUpon = newFile; Files.Add(winFormsDesignerFile); return newFile; } - else if (!(resxFile is null)) { + else if (resxFile is not null) { var filename = filenameCreator.CreateFromNamespaceName(GetTypeExtension(type), type.ReflectionNamespace, Path.GetFileNameWithoutExtension(resxFile.Filename) + DESIGNER); var newFile = new TypeProjectFile(type, filename, Options.DecompilationContext, Options.Decompiler, createDecompilerOutput); newFile.DependentUpon = resxFile; @@ -237,7 +237,7 @@ ProjectFile CreateTypeProjectFile(TypeDef type, FilenameCreator filenameCreator) } var bt = type.BaseType; - if (!(bt is null) && bt.FullName == "System.Configuration.ApplicationSettingsBase") { + if (bt is not null && bt.FullName == "System.Configuration.ApplicationSettingsBase") { var designerFilename = filenameCreator.Create(DESIGNER + GetTypeExtension(type), type.FullName); var settingsFilename = filenameCreator.Create(".settings", type.FullName); ProjectFile designerTypeFile; @@ -264,17 +264,17 @@ ProjectFile CreateTypeProjectFile(TypeDef type, FilenameCreator filenameCreator) } void CreateEmptyAppXamlFile() { - if (!hasXamlClasses || !(appTypeProjFile is null)) + if (!hasXamlClasses || appTypeProjFile is not null) return; if ((Options.Module.Characteristics & Characteristics.Dll) != 0) return; var file = Files.OfType().Where(a => DotNetUtils.IsSystemWindowsApplication(a.Type)).FirstOrDefault(); - Debug2.Assert(!(file is null)); + Debug2.Assert(file is not null); if (file is null) return; Debug2.Assert(file.DependentUpon is null); - if (!(file.DependentUpon is null)) + if (file.DependentUpon is not null) return; Files.Remove(file); @@ -330,7 +330,7 @@ bool ReferencesWPFClasses() { } BamlResourceProjectFile? TryGetBamlFile(TypeDef type) { - Debug2.Assert(!(typeFullNameToBamlFile is null)); + Debug2.Assert(typeFullNameToBamlFile is not null); typeFullNameToBamlFile.TryGetValue(type.FullName, out var bamlFile); return bamlFile; } @@ -345,13 +345,13 @@ void InitializeResX() { Dictionary? typeFullNameToResXFile; ResXProjectFile? TryGetResXFile(TypeDef type) { - Debug2.Assert(!(typeFullNameToResXFile is null)); + Debug2.Assert(typeFullNameToResXFile is not null); typeFullNameToResXFile.TryGetValue(type.FullName, out var resxFile); return resxFile; } string GetTypeExtension(TypeDef type) { - Debug2.Assert(!(typeFullNameToBamlFile is null)); + Debug2.Assert(typeFullNameToBamlFile is not null); if (typeFullNameToBamlFile.TryGetValue(type.FullName, out var bamlFile)) return ".xaml" + Options.Decompiler.FileExtension; return Options.Decompiler.FileExtension; @@ -365,7 +365,7 @@ IEnumerable CreateEmbeddedResourceFiles(ModuleDef module, ResourceN if (ResourceReader.CouldBeResourcesFile(er.CreateReader())) { var files = TryCreateResourceFiles(module, resourceNameCreator, er); - if (!(files is null)) { + if (files is not null) { foreach (var file in files) yield return file; yield break; @@ -413,7 +413,7 @@ bool IsXamlResource(ModuleDef module, string name, ResourceElementSet set) { } IEnumerable CreateXamlResourceFiles(ModuleDef module, ResourceNameCreator resourceNameCreator, ResourceElementSet set) { - bool decompileBaml = Options.DecompileXaml && !(Options.DecompileBaml is null); + bool decompileBaml = Options.DecompileXaml && Options.DecompileBaml is not null; foreach (var e in set.ResourceElements) { Debug.Assert(e.ResourceData.Code == ResourceTypeCode.ByteArray || e.ResourceData.Code == ResourceTypeCode.Stream); var data = (byte[])((BuiltInResourceData)e.ResourceData).Data; @@ -464,7 +464,7 @@ bool DecompileType(TypeDef type) { IEnumerable CreateSatelliteFiles(string rsrcName, FilenameCreator filenameCreator, ProjectFile nonSatFile) { foreach (var satMod in satelliteAssemblyFinder.GetSatelliteAssemblies(Options.Module)) { var satFile = TryCreateSatelliteFile(satMod, rsrcName, filenameCreator, nonSatFile); - if (!(satFile is null)) + if (satFile is not null) yield return satFile; } } @@ -473,7 +473,7 @@ IEnumerable CreateSatelliteFiles(string rsrcName, FilenameCreator f if (!Options.CreateResX) return null; var asm = module.Assembly; - Debug2.Assert(!(asm is null) && !UTF8String.IsNullOrEmpty(asm.Culture)); + Debug2.Assert(asm is not null && !UTF8String.IsNullOrEmpty(asm.Culture)); if (asm is null || UTF8String.IsNullOrEmpty(asm.Culture)) return null; var name = FileUtils.RemoveExtension(rsrcName); @@ -483,7 +483,7 @@ IEnumerable CreateSatelliteFiles(string rsrcName, FilenameCreator f var set = TryCreateResourceElementSet(module, er); if (set is null) return null; - Debug2.Assert(!(er is null)); + Debug2.Assert(er is not null); var dirName = Path.GetDirectoryName(nonSatFile.Filename)!; var dir = Directory.Length + 1 > dirName.Length ? string.Empty : dirName.Substring(Directory.Length + 1); @@ -507,19 +507,19 @@ IEnumerable CreateSatelliteFiles(string rsrcName, FilenameCreator f } public IEnumerable GetJobs() { - if (!(ApplicationIcon is null)) + if (ApplicationIcon is not null) yield return ApplicationIcon; - if (!(ApplicationManifest is null)) + if (ApplicationManifest is not null) yield return ApplicationManifest; foreach (var f in Files) yield return f; } public void OnWrite() { - string asmName = !(Options.Module.Assembly is null) && Options.Module.IsManifestModule ? Options.Module.Assembly.Name : null; + string asmName = Options.Module.Assembly is not null && Options.Module.IsManifestModule ? Options.Module.Assembly.Name : null; foreach (var bamlFile in Files.OfType()) { foreach (var asmRef in bamlFile.AssemblyReferences) { - if (!(asmName is null) && !StringComparer.Ordinal.Equals(asmName, asmRef.Name)) + if (asmName is not null && !StringComparer.Ordinal.Equals(asmName, asmRef.Name)) ExtraAssemblyReferences.Add(asmRef.Name); } } diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/ProjectWriter.cs b/dnSpy/dnSpy.Decompiler/MSBuild/ProjectWriter.cs index 54e0da7992..1491854e73 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/ProjectWriter.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/ProjectWriter.cs @@ -57,7 +57,7 @@ public void Write() { writer.WriteStartDocument(); writer.WriteStartElement("Project", "http://schemas.microsoft.com/developer/msbuild/2003"); var toolsVersion = GetToolsVersion(); - if (!(toolsVersion is null)) + if (toolsVersion is not null) writer.WriteAttributeString("ToolsVersion", toolsVersion); if (projectVersion <= ProjectVersion.VS2015) writer.WriteAttributeString("DefaultTargets", "Build"); @@ -84,7 +84,7 @@ public void Write() { writer.WriteElementString("ProjectGuid", project.Guid.ToString("B").ToUpperInvariant()); writer.WriteElementString("OutputType", GetOutputType()); var appDesignFolder = GetAppDesignerFolder(); - if (!(appDesignFolder is null)) + if (appDesignFolder is not null) writer.WriteElementString("AppDesignerFolder", appDesignFolder); writer.WriteElementString("RootNamespace", GetRootNamespace()); var asmName = GetAssemblyName(); @@ -103,11 +103,11 @@ public void Write() { writer.WriteElementString("ProjectTypeGuids", text); } //TODO: VB includes a "MyType" - if (!(project.ApplicationManifest is null)) + if (project.ApplicationManifest is not null) writer.WriteElementString("ApplicationManifest", GetRelativePath(project.ApplicationManifest.Filename)); - if (!(project.ApplicationIcon is null)) + if (project.ApplicationIcon is not null) writer.WriteElementString("ApplicationIcon", GetRelativePath(project.ApplicationIcon.Filename)); - if (!(project.StartupObject is null)) + if (project.StartupObject is not null) writer.WriteElementString("StartupObject", project.StartupObject); writer.WriteEndElement(); @@ -127,7 +127,7 @@ public void Write() { writer.WriteElementString("NoStdLib", "true"); if (project.AllowUnsafeBlocks) writer.WriteElementString("AllowUnsafeBlocks", "true"); - if (!(noWarnList is null)) + if (noWarnList is not null) writer.WriteElementString("NoWarn", noWarnList); writer.WriteEndElement(); @@ -145,7 +145,7 @@ public void Write() { writer.WriteElementString("NoStdLib", "true"); if (project.AllowUnsafeBlocks) writer.WriteElementString("AllowUnsafeBlocks", "true"); - if (!(noWarnList is null)) + if (noWarnList is not null) writer.WriteElementString("NoWarn", noWarnList); writer.WriteEndElement(); @@ -156,13 +156,13 @@ public void Write() { var hash = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var r in gacRefs) { var asm = project.Module.Context.AssemblyResolver.Resolve(r, project.Module); - if (!(asm is null) && ExistsInProject(asm.ManifestModule.Location)) + if (asm is not null && ExistsInProject(asm.ManifestModule.Location)) continue; hash.Add(r.Name); writer.WriteStartElement("Reference"); writer.WriteAttributeString("Include", IdentifierEscaper.Escape(r.Name)); var hintPath = GetHintPath(asm); - if (!(hintPath is null)) + if (hintPath is not null) writer.WriteElementString("HintPath", hintPath); writer.WriteEndElement(); } @@ -246,13 +246,13 @@ void Write(XmlWriter writer, BuildAction buildAction) { continue; writer.WriteStartElement(ToString(buildAction)); writer.WriteAttributeString("Include", GetRelativePath(file.Filename)); - if (!(file.DependentUpon is null)) + if (file.DependentUpon is not null) writer.WriteElementString("DependentUpon", GetRelativePath(Path.GetDirectoryName(file.Filename)!, file.DependentUpon.Filename)); - if (!(file.SubType is null)) + if (file.SubType is not null) writer.WriteElementString("SubType", file.SubType); - if (!(file.Generator is null)) + if (file.Generator is not null) writer.WriteElementString("Generator", file.Generator); - if (!(file.LastGenOutput is null)) + if (file.LastGenOutput is not null) writer.WriteElementString("LastGenOutput", GetRelativePath(Path.GetDirectoryName(file.Filename)!, file.LastGenOutput.Filename)); if (file.AutoGen) writer.WriteElementString("AutoGen", "True"); @@ -397,7 +397,7 @@ bool IsUserGacPath(string file) { return false; } - bool ExistsInProject(string filename) => !(FindOtherProject(filename) is null); + bool ExistsInProject(string filename) => FindOtherProject(filename) is not null; bool AssemblyExistsInProject(string asmSimpleName) => allProjects.Any(a => StringComparer.OrdinalIgnoreCase.Equals(a.AssemblyName, asmSimpleName)); Project? FindOtherProject(string filename) => diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/ResXProjectFile.cs b/dnSpy/dnSpy.Decompiler/MSBuild/ResXProjectFile.cs index c76769978a..0176c3716e 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/ResXProjectFile.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/ResXProjectFile.cs @@ -36,7 +36,7 @@ static ResXProjectFile() { paramTypes = new Type[] { typeof(string), typeof(Func) }; ctorInfo = typeof(ResXResourceWriter).GetConstructor(paramTypes); - if (!(ctorInfo is null)) { + if (ctorInfo is not null) { var dynMethod = new DynamicMethod("ResXResourceWriter-ctor", typeof(ResXResourceWriter), paramTypes); var ilg = dynMethod.GetILGenerator(); ilg.Emit(OpCodes.Ldarg_0); @@ -48,7 +48,7 @@ static ResXProjectFile() { paramTypes = new Type[] { typeof(string), typeof(object), typeof(Func) }; ctorInfo = typeof(ResXDataNode).GetConstructor(paramTypes); - if (!(ctorInfo is null)) { + if (ctorInfo is not null) { var dynMethod = new DynamicMethod("ResXDataNode-ctor", typeof(ResXDataNode), paramTypes); var ilg = dynMethod.GetILGenerator(); ilg.Emit(OpCodes.Ldarg_0); diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/ResourceNameCreator.cs b/dnSpy/dnSpy.Decompiler/MSBuild/ResourceNameCreator.cs index 1804ff33eb..0f27ce849b 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/ResourceNameCreator.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/ResourceNameCreator.cs @@ -43,13 +43,13 @@ public string GetResxFilename(string resourceName, out string typeFullName) { n = n.Substring(0, n.Length - RESOURCES_EXT.Length); var type = module.Find(n, true); - if (!(type is null) && DotNetUtils.IsWinForm(type)) { + if (type is not null && DotNetUtils.IsWinForm(type)) { typeFullName = type.ReflectionFullName; return filenameCreator.CreateFromNamespaceName(RESX_EXT, type.Namespace, type.Name); } var resXType = GetResXType(type, n); - if (!(resXType is null)) { + if (resXType is not null) { typeFullName = resXType.ReflectionFullName; return filenameCreator.CreateFromNamespaceName(RESX_EXT, resXType.ReflectionNamespace, GetResxDesignerFilename(resXType.ReflectionNamespace, n)); } @@ -66,7 +66,7 @@ string GetResxDesignerFilename(string ns, string name) { } TypeDef? GetResXType(TypeDef? type, string name) { - if (!(type is null) && IsResXType(type, name)) + if (type is not null && IsResXType(type, name)) return type; return FindResXType(name); } @@ -77,7 +77,7 @@ string GetResxDesignerFilename(string ns, string name) { foreach (var t in module.Types) { var s = GetResXString(t); - if (!(s is null)) + if (s is not null) dict[s] = t; } @@ -90,9 +90,9 @@ string GetResxDesignerFilename(string ns, string name) { Dictionary? resXNameToType; static string? GetResXString(TypeDef type) { - if (!type.Fields.Any(a => a.IsStatic && !(a.FieldType is null) && a.FieldType.ToString() == "System.Globalization.CultureInfo")) + if (!type.Fields.Any(a => a.IsStatic && a.FieldType is not null && a.FieldType.ToString() == "System.Globalization.CultureInfo")) return null; - if (!type.Fields.Any(a => a.IsStatic && !(a.FieldType is null) && a.FieldType.ToString() == "System.Resources.ResourceManager")) + if (!type.Fields.Any(a => a.IsStatic && a.FieldType is not null && a.FieldType.ToString() == "System.Resources.ResourceManager")) return null; foreach (var m in type.Methods) { var body = m.Body; @@ -135,11 +135,11 @@ bool IsResXType(TypeDef type, string name) { string GetBamlResourceName(string resourceName) { if (namespaces is null) Initialize(); - Debug2.Assert(!(partialNamespaceMap is null)); - Debug2.Assert(!(partialTypeToFullNameMap is null)); - Debug2.Assert(!(typeToFullNameMap is null)); - Debug2.Assert(!(lowerCaseNsToReal is null)); - Debug2.Assert(!(namespaces is null)); + Debug2.Assert(partialNamespaceMap is not null); + Debug2.Assert(partialTypeToFullNameMap is not null); + Debug2.Assert(typeToFullNameMap is not null); + Debug2.Assert(lowerCaseNsToReal is not null); + Debug2.Assert(namespaces is not null); var ext = FileUtils.GetExtension(resourceName); var nameNoExt = resourceName.Substring(0, resourceName.Length - ext.Length); @@ -162,11 +162,11 @@ static string GetNamespace(string name) { public string GetBamlResourceName(string resourceName, out string typeFullName) { if (namespaces is null) Initialize(); - Debug2.Assert(!(partialNamespaceMap is null)); - Debug2.Assert(!(partialTypeToFullNameMap is null)); - Debug2.Assert(!(typeToFullNameMap is null)); - Debug2.Assert(!(lowerCaseNsToReal is null)); - Debug2.Assert(!(namespaces is null)); + Debug2.Assert(partialNamespaceMap is not null); + Debug2.Assert(partialTypeToFullNameMap is not null); + Debug2.Assert(typeToFullNameMap is not null); + Debug2.Assert(lowerCaseNsToReal is not null); + Debug2.Assert(namespaces is not null); Debug.Assert(resourceName.EndsWith(".baml", StringComparison.OrdinalIgnoreCase)); var name = resourceName.Substring(0, resourceName.Length - ".baml".Length); @@ -180,8 +180,8 @@ public string GetBamlResourceName(string resourceName, out string typeFullName) } string? GetFullName(string partialName) { - Debug2.Assert(!(partialTypeToFullNameMap is null)); - Debug2.Assert(!(typeToFullNameMap is null)); + Debug2.Assert(partialTypeToFullNameMap is not null); + Debug2.Assert(typeToFullNameMap is not null); var name = partialName; if (!string.IsNullOrEmpty(filenameCreator.DefaultNamespace)) name = filenameCreator.DefaultNamespace + "." + name; @@ -194,11 +194,11 @@ public string GetBamlResourceName(string resourceName, out string typeFullName) public string GetResourceFilename(string resourceName) { if (namespaces is null) Initialize(); - Debug2.Assert(!(partialNamespaceMap is null)); - Debug2.Assert(!(partialTypeToFullNameMap is null)); - Debug2.Assert(!(typeToFullNameMap is null)); - Debug2.Assert(!(lowerCaseNsToReal is null)); - Debug2.Assert(!(namespaces is null)); + Debug2.Assert(partialNamespaceMap is not null); + Debug2.Assert(partialTypeToFullNameMap is not null); + Debug2.Assert(typeToFullNameMap is not null); + Debug2.Assert(lowerCaseNsToReal is not null); + Debug2.Assert(namespaces is not null); string[] parts = resourceName.Split(new char[] { '.' }); var possibleNamespaces = new List(parts.Length); @@ -223,7 +223,7 @@ public string GetResourceFilename(string resourceName) { } void Initialize() { - if (!(namespaces is null)) + if (namespaces is not null) return; // Only include actual used namespaces, eg. if "ns1.ns2.Type1" is used, but there's no diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/SettingsProjectFile.cs b/dnSpy/dnSpy.Decompiler/MSBuild/SettingsProjectFile.cs index a3b8cebd06..1e24921ec6 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/SettingsProjectFile.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/SettingsProjectFile.cs @@ -89,7 +89,7 @@ public override void Create(DecompileContext ctx) { writer.WriteAttributeString("GenerateDefaultValueInCode", "false"); writer.WriteAttributeString("Type", setting.Type); writer.WriteAttributeString("Scope", setting.Scope); - if (!(setting.DesignTimeValue is null)) { + if (setting.DesignTimeValue is not null) { writer.WriteStartElement("DesignTimeValue"); writer.WriteAttributeString("Profile", setting.DesignTimeValue.Profile); writer.WriteString(setting.DesignTimeValue.Text); @@ -133,12 +133,12 @@ IEnumerable FindSettings() { bool roaming = false; ca = prop.CustomAttributes.Find("System.Configuration.SettingsManageabilityAttribute"); - if (!(ca is null) && ca.ConstructorArguments.Count == 1) { + if (ca is not null && ca.ConstructorArguments.Count == 1) { arg = ca.ConstructorArguments[0]; var argType = arg.Type.RemovePinnedAndModifiers(); - if (!(argType is null) && argType.ReflectionFullName == "System.Configuration.SettingsManageability") { + if (argType is not null && argType.ReflectionFullName == "System.Configuration.SettingsManageability") { var v = arg.Value as int?; - if (!(v is null)) { + if (v is not null) { switch ((SettingsManageability)v.Value) { case SettingsManageability.Roaming: roaming = true; @@ -151,17 +151,17 @@ IEnumerable FindSettings() { var setting = new Setting(); ca = prop.CustomAttributes.Find("System.Configuration.SpecialSettingAttribute"); - if (!(ca is null) && ca.ConstructorArguments.Count == 1) { + if (ca is not null && ca.ConstructorArguments.Count == 1) { arg = ca.ConstructorArguments[0]; var argType = arg.Type.RemovePinnedAndModifiers(); - if (!(argType is null) && argType.ReflectionFullName == "System.Configuration.SpecialSetting") { + if (argType is not null && argType.ReflectionFullName == "System.Configuration.SpecialSetting") { var v = arg.Value as int?; - if (!(v is null)) { + if (v is not null) { switch ((SpecialSetting)v.Value) { case SpecialSetting.ConnectionString: settingsType = "(Connection string)"; var designTimeValue = GetConnectionStringDesignTimeValue(prop); - if (!(designTimeValue is null)) { + if (designTimeValue is not null) { setting.DesignTimeValue = new Value { Profile = DEFAULT_PROFILE, Text = designTimeValue, @@ -178,20 +178,20 @@ IEnumerable FindSettings() { string? provider = null; ca = prop.CustomAttributes.Find("System.Configuration.SettingsProviderAttribute"); - if (!(ca is null) && ca.ConstructorArguments.Count == 1) { + if (ca is not null && ca.ConstructorArguments.Count == 1) { arg = ca.ConstructorArguments[0]; var argType = arg.Type.RemovePinnedAndModifiers(); if (argType.GetElementType() == ElementType.String) provider = arg.Value as UTF8String; - else if (!(argType is null) && argType.FullName == "System.Type") { - if (arg.Value is TypeDefOrRefSig t && !(t.TypeDefOrRef is null)) + else if (argType is not null && argType.FullName == "System.Type") { + if (arg.Value is TypeDefOrRefSig t && t.TypeDefOrRef is not null) provider = t.TypeDefOrRef.ReflectionFullName; } } string? description = null; ca = prop.CustomAttributes.Find("System.Configuration.SettingsDescriptionAttribute"); - if (!(ca is null) && ca.ConstructorArguments.Count == 1) { + if (ca is not null && ca.ConstructorArguments.Count == 1) { arg = ca.ConstructorArguments[0]; var argType = arg.Type.RemovePinnedAndModifiers(); if (argType.GetElementType() == ElementType.String) @@ -217,7 +217,7 @@ IEnumerable FindSettings() { string? GetConnectionStringDesignTimeValue(PropertyDef prop) { if (toConnectionStringInfo is null) InitializeConnectionStringDesignTimeValues(); - Debug2.Assert(!(toConnectionStringInfo is null)); + Debug2.Assert(toConnectionStringInfo is not null); if (!toConnectionStringInfo.TryGetValue(prop.Name, out var info)) return null; @@ -239,7 +239,7 @@ sealed class ConnectionStringInfo { void InitializeConnectionStringDesignTimeValues() { Debug2.Assert(toConnectionStringInfo is null); - if (!(toConnectionStringInfo is null)) + if (toConnectionStringInfo is not null) return; toConnectionStringInfo = new Dictionary(StringComparer.Ordinal); diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/SettingsTypeProjectFile.cs b/dnSpy/dnSpy.Decompiler/MSBuild/SettingsTypeProjectFile.cs index e17846d0dc..b78a2380c5 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/SettingsTypeProjectFile.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/SettingsTypeProjectFile.cs @@ -71,7 +71,7 @@ void InitializeIsEmpty() { } public IMemberDef[] GetDefsToRemove() { - if (!(defsToRemove is null)) + if (defsToRemove is not null) return defsToRemove; lock (defsToRemoveLock) { if (defsToRemove is null) @@ -84,7 +84,7 @@ public IMemberDef[] GetDefsToRemove() { IEnumerable CalculateDefsToRemove() { var defaultProp = FindDefaultProperty(); - if (!(defaultProp is null)) { + if (defaultProp is not null) { foreach (var d in DotNetUtils.GetMethodsAndSelf(defaultProp)) yield return d; foreach (var d in DotNetUtils.GetDefs(defaultProp)) @@ -103,7 +103,7 @@ IEnumerable CalculateDefsToRemove() { if (p.Name != "Default") continue; var g = p.GetMethod; - if (g is null || !g.IsStatic || !(p.SetMethod is null) || p.OtherMethods.Count != 0) + if (g is null || !g.IsStatic || p.SetMethod is not null || p.OtherMethods.Count != 0) continue; if (g.MethodSig.GetParamCount() != 0) continue; diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/WinFormsProjectFile.cs b/dnSpy/dnSpy.Decompiler/MSBuild/WinFormsProjectFile.cs index 075f9b4b53..ae21fb37db 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/WinFormsProjectFile.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/WinFormsProjectFile.cs @@ -47,7 +47,7 @@ protected override void Decompile(DecompileContext ctx, IDecompilerOutput output } public IMemberDef[] GetDefsToRemove() { - if (!(defsToRemove is null)) + if (defsToRemove is not null) return defsToRemove; lock (defsToRemoveLock) { if (defsToRemove is null) @@ -60,14 +60,14 @@ public IMemberDef[] GetDefsToRemove() { IEnumerable CalculateDefsToRemove() { var m = GetInitializeComponent(); - if (!(m is null)) { + if (m is not null) { yield return m; foreach (var f in DotNetUtils.GetFields(m)) yield return f; } m = GetDispose(); - if (!(m is null)) { + if (m is not null) { yield return m; foreach (var f in DotNetUtils.GetFields(m)) yield return f; diff --git a/dnSpy/dnSpy.Decompiler/MSBuild/XamlTypeProjectFile.cs b/dnSpy/dnSpy.Decompiler/MSBuild/XamlTypeProjectFile.cs index df7ea6c60e..f217c6a576 100644 --- a/dnSpy/dnSpy.Decompiler/MSBuild/XamlTypeProjectFile.cs +++ b/dnSpy/dnSpy.Decompiler/MSBuild/XamlTypeProjectFile.cs @@ -40,11 +40,11 @@ protected override void Decompile(DecompileContext ctx, IDecompilerOutput output IEnumerable GetDefsToRemove() { var ep = Type.Module.EntryPoint; - if (!(ep is null) && ep.DeclaringType == Type) + if (ep is not null && ep.DeclaringType == Type) yield return ep; var d = FindInitializeComponent(); - if (!(d is null)) { + if (d is not null) { yield return d; foreach (var f in DotNetUtils.GetFields(d)) { if (f.FieldType.RemovePinnedAndModifiers().GetElementType() == ElementType.Boolean) @@ -53,14 +53,14 @@ IEnumerable GetDefsToRemove() { } var connMeth = FindConnectMethod(); - if (!(connMeth is null)) { + if (connMeth is not null) { yield return connMeth; foreach (var f in DotNetUtils.GetFields(connMeth)) yield return f; } var delMeth = FindCreateDelegateMethod(); - if (!(delMeth is null)) + if (delMeth is not null) yield return delMeth; } diff --git a/dnSpy/dnSpy.Decompiler/TargetFrameworkInfo.cs b/dnSpy/dnSpy.Decompiler/TargetFrameworkInfo.cs index cbd5ec131b..0fa86c0223 100644 --- a/dnSpy/dnSpy.Decompiler/TargetFrameworkInfo.cs +++ b/dnSpy/dnSpy.Decompiler/TargetFrameworkInfo.cs @@ -61,9 +61,9 @@ readonly struct TargetFrameworkInfo { public static TargetFrameworkInfo Create(ModuleDef module) { var asm = module.Assembly; - if (!(asm is null) && module.IsManifestModule) { + if (asm is not null && module.IsManifestModule) { var info = TryGetTargetFrameworkInfoInternal(asm); - if (!(info is null)) + if (info is not null) return info.Value; } @@ -235,7 +235,7 @@ static IEnumerable GetModules(ModuleDef module) { yield return module; foreach (var asmRef in module.GetAssemblyRefs()) { var asm = module.Context.AssemblyResolver.Resolve(asmRef, module); - if (!(asm is null)) + if (asm is not null) yield return asm.ManifestModule; } } @@ -266,7 +266,7 @@ static Dnr2035Version GetDotNetVersion2035Internal(ModuleDef module) { ver = Dnr2035Version.V30; } var asm = module.Assembly; - if (!(asm is null) && module.IsManifestModule) { + if (asm is not null && module.IsManifestModule) { if (dotNet35Asms.Contains(asm.FullName)) return Dnr2035Version.V35; if (dotNet30Asms.Contains(asm.FullName)) diff --git a/dnSpy/dnSpy.Decompiler/TypeFormatterUtils.cs b/dnSpy/dnSpy.Decompiler/TypeFormatterUtils.cs index 94c325a8eb..f893826b33 100644 --- a/dnSpy/dnSpy.Decompiler/TypeFormatterUtils.cs +++ b/dnSpy/dnSpy.Decompiler/TypeFormatterUtils.cs @@ -113,7 +113,7 @@ public static string GetFileName(string s) { static int GetNumberOfOverloads(TypeDef? type, string name, bool checkBaseTypes) { var hash = new HashSet(MethodEqualityComparer.DontCompareDeclaringTypes); - while (!(type is null)) { + while (type is not null) { foreach (var m in type.Methods) { if (m.Name == name) hash.Add(m); @@ -139,7 +139,7 @@ public static string GetName(ISourceVariable variable) { var n = variable.Name; if (!string.IsNullOrWhiteSpace(n)) return n; - if (!(variable.Variable is null)) { + if (variable.Variable is not null) { if (variable.IsLocal) return "V_" + variable.Variable.Index.ToString(); return "A_" + variable.Variable.Index.ToString(); @@ -150,8 +150,8 @@ public static string GetName(ISourceVariable variable) { public static bool IsSystemNullable(GenericInstSig gis) { var gt = gis.GenericType as ValueTypeSig; - return !(gt is null) && - !(gt.TypeDefOrRef is null) && + return gt is not null && + gt.TypeDefOrRef is not null && gt.TypeDefOrRef.DefinitionAssembly.IsCorLib() && gt.TypeDefOrRef.FullName == "System.Nullable`1"; } @@ -200,7 +200,7 @@ static int GetValueTupleSimpleRank(GenericInstSig gis) { return rank; } - public static bool IsDelegate(TypeDef? td) => !(td is null) && + public static bool IsDelegate(TypeDef? td) => td is not null && new SigComparer().Equals(td.BaseType, td.Module.CorLibTypes.GetTypeRef("System", "MulticastDelegate")) && td.BaseType.DefinitionAssembly.IsCorLib(); @@ -343,7 +343,7 @@ public static MemberSpecialFlags GetMemberSpecialFlags(IMethod method) { var flags = MemberSpecialFlags.None; var md = method.ResolveMethodDef(); - if (!(md is null) && IsExtension(md.CustomAttributes)) + if (md is not null && IsExtension(md.CustomAttributes)) flags |= MemberSpecialFlags.Extension; if (IsAwaitableType(method.MethodSig.GetRetType())) @@ -365,11 +365,11 @@ public static bool HasConstant(IHasConstant? hc, out CustomAttribute? constantAt constantAttribute = null; if (hc is null) return false; - if (!(hc.Constant is null)) + if (hc.Constant is not null) return true; foreach (var ca in hc.CustomAttributes) { var type = ca.AttributeType; - while (!(type is null)) { + while (type is not null) { var fullName = type.FullName; if (fullName == "System.Runtime.CompilerServices.CustomConstantAttribute" || fullName == "System.Runtime.CompilerServices.DecimalConstantAttribute") { @@ -383,12 +383,12 @@ public static bool HasConstant(IHasConstant? hc, out CustomAttribute? constantAt } public static bool TryGetConstant(IHasConstant? hc, CustomAttribute? constantAttribute, out object? constant) { - if (!(hc?.Constant is null)) { + if (hc?.Constant is not null) { constant = hc.Constant.Value; return true; } - if (!(constantAttribute is null)) { + if (constantAttribute is not null) { if (constantAttribute.TypeFullName == "System.Runtime.CompilerServices.DecimalConstantAttribute") { if (TryGetDecimalConstantAttributeValue(constantAttribute, out var decimalValue)) { constant = decimalValue; diff --git a/dnSpy/dnSpy.Decompiler/Utils/StateMachineHelpers.cs b/dnSpy/dnSpy.Decompiler/Utils/StateMachineHelpers.cs index 0b85f226f6..1aef2a902c 100644 --- a/dnSpy/dnSpy.Decompiler/Utils/StateMachineHelpers.cs +++ b/dnSpy/dnSpy.Decompiler/Utils/StateMachineHelpers.cs @@ -159,7 +159,7 @@ static bool ImplementsInterface(TypeDef type, UTF8String @namespace, UTF8String var ifaces = type.Interfaces; for (int i = 0; i < ifaces.Count; i++) { var iface = ifaces[i].Interface; - if (!(iface is null) && EqualsName(iface, @namespace, name)) + if (iface is not null && EqualsName(iface, @namespace, name)) return true; } return false; @@ -189,7 +189,7 @@ static bool ImplementsInterface(TypeDef type, UTF8String @namespace, UTF8String static bool IsDisposeSig(MethodSig sig) { if (sig.GenParamCount != 0) return false; - if (!(sig.ParamsAfterSentinel is null)) + if (sig.ParamsAfterSentinel is not null) return false; if (sig.Params.Count != 0) return false; diff --git a/dnSpy/dnSpy.Decompiler/VisualBasic/VisualBasicFormatter.cs b/dnSpy/dnSpy.Decompiler/VisualBasic/VisualBasicFormatter.cs index 73c8676028..3abf51a031 100644 --- a/dnSpy/dnSpy.Decompiler/VisualBasic/VisualBasicFormatter.cs +++ b/dnSpy/dnSpy.Decompiler/VisualBasic/VisualBasicFormatter.cs @@ -218,7 +218,7 @@ void WriteSystemType(string name, bool isValueType) { void WriteToken(IMDTokenProvider tok) { if (!ShowTokens) return; - Debug2.Assert(!(tok is null)); + Debug2.Assert(tok is not null); if (tok is null) return; OutputWrite(CommentBegin + ToFormattedUInt32(tok.MDToken.Raw) + CommentEnd, BoxedTextColor.Comment); @@ -230,22 +230,22 @@ public void WriteToolTip(IMemberRef? member) { return; } - if (member is IMethod method && !(method.MethodSig is null)) { + if (member is IMethod method && method.MethodSig is not null) { WriteToolTip(method); return; } - if (member is IField field && !(field.FieldSig is null)) { + if (member is IField field && field.FieldSig is not null) { WriteToolTip(field); return; } - if (member is PropertyDef prop && !(prop.PropertySig is null)) { + if (member is PropertyDef prop && prop.PropertySig is not null) { WriteToolTip(prop); return; } - if (member is EventDef evt && !(evt.EventType is null)) { + if (member is EventDef evt && evt.EventType is not null) { WriteToolTip(evt); return; } @@ -269,22 +269,22 @@ public void Write(IMemberRef? member) { return; } - if (member is IMethod method && !(method.MethodSig is null)) { + if (member is IMethod method && method.MethodSig is not null) { Write(method); return; } - if (member is IField field && !(field.FieldSig is null)) { + if (member is IField field && field.FieldSig is not null) { Write(field); return; } - if (member is PropertyDef prop && !(prop.PropertySig is null)) { + if (member is PropertyDef prop && prop.PropertySig is not null) { Write(prop); return; } - if (member is EventDef evt && !(evt.EventType is null)) { + if (member is EventDef evt && evt.EventType is not null) { Write(evt); return; } @@ -340,9 +340,9 @@ void WriteToolTip(IMethod? method) { Write(method); var td = method.DeclaringType.ResolveTypeDef(); - if (!(td is null)) { + if (td is not null) { var s = TypeFormatterUtils.GetNumberOfOverloadsString(td, method); - if (!(s is null)) + if (s is not null) OutputWrite(s, BoxedTextColor.Text); } } @@ -353,7 +353,7 @@ void WriteType(ITypeDefOrRef type, bool useNamespaces, bool useTypeKeywords) { td = ((TypeRef)type).Resolve(); if (td is null || td.GenericParameters.Count == 0 || - (!(td.DeclaringType is null) && td.DeclaringType.GenericParameters.Count >= td.GenericParameters.Count)) { + (td.DeclaringType is not null && td.DeclaringType.GenericParameters.Count >= td.GenericParameters.Count)) { var oldFlags = options; options &= ~(FormatterOptions.ShowNamespaces | FormatterOptions.ShowIntrinsicTypeKeywords); if (useNamespaces) @@ -366,7 +366,7 @@ void WriteType(ITypeDefOrRef type, bool useNamespaces, bool useTypeKeywords) { } int numGenParams = td.GenericParameters.Count; - if (!(type.DeclaringType is null)) { + if (type.DeclaringType is not null) { var oldFlags = options; options &= ~(FormatterOptions.ShowNamespaces | FormatterOptions.ShowIntrinsicTypeKeywords); if (useNamespaces) @@ -436,16 +436,16 @@ void Write(IMethod? method) { WriteModuleName(info); string[]? operatorInfo; - if (!(info.MethodDef is null) && info.MethodDef.IsConstructor && !(method.DeclaringType is null)) + if (info.MethodDef is not null && info.MethodDef.IsConstructor && method.DeclaringType is not null) operatorInfo = null; - else if (!(info.MethodDef is null) && info.MethodDef.Overrides.Count > 0) { + else if (info.MethodDef is not null && info.MethodDef.Overrides.Count > 0) { var ovrMeth = (IMemberRef)info.MethodDef.Overrides[0].MethodDeclaration; operatorInfo = TryGetOperatorInfo(ovrMeth.Name); } else operatorInfo = TryGetOperatorInfo(method.Name); - if (!(operatorInfo is null)) { + if (operatorInfo is not null) { for (int i = 0; i < operatorInfo.Length - 1; i++) { WriteOperatorInfoString(operatorInfo[i]); WriteSpace(); @@ -461,9 +461,9 @@ void Write(IMethod? method) { Write(method.DeclaringType); WritePeriod(); } - if (!(info.MethodDef is null) && info.MethodDef.IsConstructor && !(method.DeclaringType is null)) + if (info.MethodDef is not null && info.MethodDef.IsConstructor && method.DeclaringType is not null) OutputWrite(Keyword_New, BoxedTextColor.Keyword); - else if (!(info.MethodDef is null) && info.MethodDef.Overrides.Count > 0) { + else if (info.MethodDef is not null && info.MethodDef.Overrides.Count > 0) { var ovrMeth = (IMemberRef)info.MethodDef.Overrides[0].MethodDeclaration; WriteMethodName(method, ovrMeth.Name, operatorInfo); } @@ -484,7 +484,7 @@ void Write(IMethod? method) { void WriteOperatorInfoString(string s) => OutputWrite(s, 'A' <= s[0] && s[0] <= 'Z' ? BoxedTextColor.Keyword : BoxedTextColor.Operator); void WriteMethodName(IMethod method, string name, string[]? operatorInfo) { - if (!(operatorInfo is null)) + if (operatorInfo is not null) WriteOperatorInfoString(operatorInfo[operatorInfo.Length - 1]); else WriteIdentifier(name, VisualBasicMetadataTextColorProvider.Instance.GetColor(method)); @@ -505,12 +505,12 @@ void Write(IField? field, bool isToolTip) { var sig = field.FieldSig; var td = field.DeclaringType.ResolveTypeDef(); - bool isEnumOwner = !(td is null) && td.IsEnum; + bool isEnumOwner = td is not null && td.IsEnum; var fd = field.ResolveFieldDef(); object? constant = null; - bool isConstant = !(fd is null) && (fd.IsLiteral || (fd.IsStatic && fd.IsInitOnly)) && TypeFormatterUtils.HasConstant(fd, out var constantAttribute) && TypeFormatterUtils.TryGetConstant(fd, constantAttribute, out constant); - if (!isEnumOwner || (!(fd is null) && !fd.IsLiteral)) { + bool isConstant = fd is not null && (fd.IsLiteral || (fd.IsStatic && fd.IsInitOnly)) && TypeFormatterUtils.HasConstant(fd, out var constantAttribute) && TypeFormatterUtils.TryGetConstant(fd, constantAttribute, out constant); + if (!isEnumOwner || (fd is not null && !fd.IsLiteral)) { if (isToolTip) { OutputWrite(DescriptionParenOpen, BoxedTextColor.Punctuation); OutputWrite(isConstant ? dnSpy_Decompiler_Resources.ToolTip_Constant : dnSpy_Decompiler_Resources.ToolTip_Field, BoxedTextColor.Text); @@ -656,7 +656,7 @@ void Write(PropertyDef? prop, AccessorKind accessorKind) { WritePeriod(); } var ovrMeth = md is null || md.Overrides.Count == 0 ? null : md.Overrides[0].MethodDeclaration; - if (!(ovrMeth is null) && TypeFormatterUtils.GetPropertyName(ovrMeth) is string ovrMethPropName) + if (ovrMeth is not null && TypeFormatterUtils.GetPropertyName(ovrMeth) is string ovrMethPropName) WriteIdentifier(ovrMethPropName, VisualBasicMetadataTextColorProvider.Instance.GetColor(prop)); else WriteIdentifier(prop.Name, VisualBasicMetadataTextColorProvider.Instance.GetColor(prop)); @@ -733,7 +733,7 @@ void WriteToolTip(ITypeDefOrRef type) { Write(TypeFormatterUtils.GetMemberSpecialFlags(type)); MethodDef invoke; - if (TypeFormatterUtils.IsDelegate(td) && !((invoke = td.FindMethod("Invoke")) is null) && !(invoke.MethodSig is null)) { + if (TypeFormatterUtils.IsDelegate(td) && (invoke = td.FindMethod("Invoke")) is not null && invoke.MethodSig is not null) { OutputWrite(Keyword_delegate, BoxedTextColor.Keyword); WriteSpace(); @@ -779,7 +779,7 @@ void WriteToolTip(ITypeDefOrRef type) { } static bool IsModule(TypeDef type) => - !(type is null) && type.DeclaringType is null && type.IsSealed && type.IsDefined(stringMicrosoftVisualBasicCompilerServices, stringStandardModuleAttribute); + type is not null && type.DeclaringType is null && type.IsSealed && type.IsDefined(stringMicrosoftVisualBasicCompilerServices, stringStandardModuleAttribute); static readonly UTF8String stringMicrosoftVisualBasicCompilerServices = new UTF8String("Microsoft.VisualBasic.CompilerServices"); static readonly UTF8String stringStandardModuleAttribute = new UTF8String("StandardModuleAttribute"); @@ -798,13 +798,13 @@ void Write(ITypeDefOrRef? type, bool showModuleNames = false) { return; } - if (!(type.DeclaringType is null)) { + if (type.DeclaringType is not null) { Write(type.DeclaringType); WritePeriod(); } string? keyword = GetTypeKeyword(type); - if (!(keyword is null)) + if (keyword is not null) OutputWrite(keyword, BoxedTextColor.Keyword); else { if (showModuleNames) @@ -833,7 +833,7 @@ void WriteNamespace(string ns) { string? GetTypeKeyword(ITypeDefOrRef type) { if (!ShowIntrinsicTypeKeywords) return null; - if (type is null || !(type.DeclaringType is null) || type.Namespace != "System" || !type.DefinitionAssembly.IsCorLib()) + if (type is null || type.DeclaringType is not null || type.Namespace != "System" || !type.DefinitionAssembly.IsCorLib()) return null; switch (type.TypeName) { case "Boolean": return "Boolean"; @@ -874,13 +874,13 @@ void Write(TypeSig? type, IList? typeGenArgs, IList? methGenAr methGenArgs = Array.Empty(); List? list = null; - while (!(type is null) && (type.ElementType == ElementType.SZArray || type.ElementType == ElementType.Array)) { + while (type is not null && (type.ElementType == ElementType.SZArray || type.ElementType == ElementType.Array)) { if (list is null) list = new List(); list.Add((ArraySigBase)type); type = type.Next; } - if (!(list is null)) { + if (list is not null) { Write(list[list.Count - 1].Next, typeGenArgs, Array.Empty()); foreach (var aryType in list) { if (aryType.ElementType == ElementType.Array) { @@ -965,11 +965,11 @@ void Write(TypeSig? type, IList? typeGenArgs, IList? methGenAr case ElementType.Var: case ElementType.MVar: var gsType = Read(type.ElementType == ElementType.Var ? typeGenArgs : methGenArgs, (int)((GenericSig)type).Number); - if (!(gsType is null)) + if (gsType is not null) Write(gsType, typeGenArgs, methGenArgs); else { var gp = ((GenericSig)type).GenericParam; - if (!(gp is null)) + if (gp is not null) Write(gp); else { if (type.ElementType == ElementType.MVar) { @@ -986,7 +986,7 @@ void Write(TypeSig? type, IList? typeGenArgs, IList? methGenAr case ElementType.GenericInst: var gis = (GenericInstSig?)type; - Debug2.Assert(!(gis is null)); + Debug2.Assert(gis is not null); if (TypeFormatterUtils.IsSystemNullable(gis)) { Write(GenericArgumentResolver.Resolve(gis.GenericArguments[0], typeGenArgs, methGenArgs), null, null); OutputWrite("?", BoxedTextColor.Operator); @@ -1035,7 +1035,7 @@ void Write(TypeSig? type, IList? typeGenArgs, IList? methGenAr WriteCommaSpace(); Write(sig.Params[i], typeGenArgs, methGenArgs); } - if (!(sig.ParamsAfterSentinel is null)) { + if (sig.ParamsAfterSentinel is not null) { if (sig.Params.Count > 0) WriteCommaSpace(); OutputWrite("...", BoxedTextColor.Punctuation); @@ -1095,7 +1095,7 @@ public void WriteToolTip(ISourceVariable? variable) { WriteSpace(); } WriteIdentifier(TypeFormatterUtils.GetName(variable), isLocal ? BoxedTextColor.Local : BoxedTextColor.Parameter); - if (!(pd is null)) + if (pd is not null) WriteToken(pd); WriteSpace(); OutputWrite(Keyword_As, BoxedTextColor.Keyword); @@ -1162,7 +1162,7 @@ void WriteReturnType(in FormatterMethodInfo info) { return; if (IsSub(info)) return; - if (!(!(info.MethodDef is null) && info.MethodDef.IsConstructor)) { + if (!(info.MethodDef is not null && info.MethodDef.IsConstructor)) { var retInfo = GetReturnTypeInfo(info); WriteSpace(); OutputWrite(Keyword_As, BoxedTextColor.Keyword); @@ -1194,9 +1194,9 @@ void WriteReturnType(in FormatterMethodInfo info) { void WriteGenericArguments(in FormatterMethodInfo info) { if (info.MethodSig.GenParamCount > 0) { - if (!(info.MethodGenericParams is null)) + if (info.MethodGenericParams is not null) WriteGenerics(info.MethodGenericParams, BoxedTextColor.MethodGenericParameter, GenericParamContext.Create(info.MethodDef)); - else if (!(info.MethodDef is null)) + else if (info.MethodDef is not null) WriteGenerics(info.MethodDef.GenericParameters, BoxedTextColor.MethodGenericParameter); } } @@ -1214,7 +1214,7 @@ void WriteMethodParameterList(in FormatterMethodInfo info, string lparen, string if (i > 0) WriteCommaSpace(); ParamDef? pd; - if (!(info.MethodDef is null) && baseIndex + i < info.MethodDef.Parameters.Count) + if (info.MethodDef is not null && baseIndex + i < info.MethodDef.Parameters.Count) pd = info.MethodDef.Parameters[baseIndex + i].ParamDef; else pd = null; @@ -1232,7 +1232,7 @@ void WriteMethodParameterList(in FormatterMethodInfo info, string lparen, string WriteSpace(); } - if (!(pd is null) && pd.CustomAttributes.IsDefined("System.ParamArrayAttribute")) { + if (pd is not null && pd.CustomAttributes.IsDefined("System.ParamArrayAttribute")) { OutputWrite(Keyword_params, BoxedTextColor.Keyword); needSpace = true; } @@ -1243,7 +1243,7 @@ void WriteMethodParameterList(in FormatterMethodInfo info, string lparen, string WriteSpace(); needSpace = true; - if (!(pd is null)) { + if (pd is not null) { WriteIdentifier(pd.Name, BoxedTextColor.Parameter); WriteToken(pd); } diff --git a/dnSpy/dnSpy/BackgroundImage/BackgroundImageService.cs b/dnSpy/dnSpy/BackgroundImage/BackgroundImageService.cs index b77bce4c59..9dfd6f037c 100644 --- a/dnSpy/dnSpy/BackgroundImage/BackgroundImageService.cs +++ b/dnSpy/dnSpy/BackgroundImage/BackgroundImageService.cs @@ -125,7 +125,7 @@ public void OnImageChanged() { } protected void UpdateImagePosition() { - Debug2.Assert(!(currentImage is null)); + Debug2.Assert(currentImage is not null); if (currentImage is null) return; UpdateImagePosition(currentImage); @@ -234,7 +234,7 @@ public void OnSettingsChanged() { } void AddImageToAdornmentLayer() { - Debug2.Assert(!(currentImage is null)); + Debug2.Assert(currentImage is not null); AddImageToAdornmentLayerCore(currentImage); } diff --git a/dnSpy/dnSpy/BackgroundImage/BackgroundImageSettingsService.cs b/dnSpy/dnSpy/BackgroundImage/BackgroundImageSettingsService.cs index 22d8fe8ed6..132aeb12c0 100644 --- a/dnSpy/dnSpy/BackgroundImage/BackgroundImageSettingsService.cs +++ b/dnSpy/dnSpy/BackgroundImage/BackgroundImageSettingsService.cs @@ -83,7 +83,7 @@ public SettingsInfo(Lazy !(currentImageInfo is null); + public bool HasImageSource => currentImageInfo is not null; public bool HasThemeImages => filenameIterators.Any(a => a.SourceOptions.HasThemeImages); sealed class SourceOptions { @@ -311,7 +311,7 @@ static List Shuffle(Random random, List list) { } List GetAllFilenames() { - Debug2.Assert(!(theme is null)); + Debug2.Assert(theme is not null); if (cachedAllFilenamesListWeakRef?.Target is List list && (DateTimeOffset.UtcNow - cachedTime).TotalMilliseconds <= cachedFilenamesMaxMilliseconds) return list; @@ -333,7 +333,7 @@ List GetAllFilenames() { ImageInfo? TryCreateNextImageSource(List filenames) { foreach (var filename in filenames) { var imgInfo = TryCreateImageSource(filename); - if (!(imgInfo is null)) + if (imgInfo is not null) return imgInfo; } @@ -346,7 +346,7 @@ List GetAllFilenames() { if (currentEnumeratorInfo is null) currentEnumeratorInfo = new EnumeratorInfo(filenameIterators[currentFilenameIteratorIndex]); var imgInfo = TryCreateNextImageSource(currentEnumeratorInfo); - if (!(imgInfo is null)) + if (imgInfo is not null) return imgInfo; int baseIndex = currentFilenameIteratorIndex; @@ -359,7 +359,7 @@ List GetAllFilenames() { currentEnumeratorInfo = new EnumeratorInfo(filenameIterators[currentFilenameIteratorIndex]); imgInfo = TryCreateNextImageSource(currentEnumeratorInfo); - if (!(imgInfo is null)) + if (imgInfo is not null) return imgInfo; } @@ -367,14 +367,14 @@ List GetAllFilenames() { } ImageInfo? TryCreateNextImageSource(EnumeratorInfo info) { - Debug2.Assert(!(theme is null)); + Debug2.Assert(theme is not null); if (info is null) return null; if (!info.Iterator.SourceOptions.IsSupportedTheme(theme)) return null; while (info.Enumerator.MoveNext()) { var imgInfo = TryCreateImageSource(info.Enumerator.Current); - if (!(imgInfo is null)) + if (imgInfo is not null) return imgInfo; } return null; @@ -395,7 +395,7 @@ static bool HasAllowedUriScheme(string filename) { ImageInfo? TryCreateImageSource(string filename) { if (!HasAllowedUriScheme(filename) && !File.Exists(filename)) return null; - if (!(currentImageInfo is null) && StringComparer.InvariantCultureIgnoreCase.Equals(filename, currentImageInfo.Filename)) + if (currentImageInfo is not null && StringComparer.InvariantCultureIgnoreCase.Equals(filename, currentImageInfo.Filename)) return currentImageInfo; try { // Make sure \\?\C:\some\path\image.png won't throw an exception @@ -452,7 +452,7 @@ public void Unregister(IImageSourceServiceListener listener) { DisposeTimer(); backgroundImageSettings.SettingsChanged -= BackgroundImageSettings_SettingsChanged; themeService.ThemeChangedLowPriority -= ThemeService_ThemeChangedLowPriority; - Debug2.Assert(!(imageIterator is null)); + Debug2.Assert(imageIterator is not null); imageIterator.Dispose(); imageIterator = null; } @@ -508,7 +508,7 @@ void UpdateTimer() { const double minimumMilliseconds = 50; if (!enabled || backgroundImageSettings.Interval < TimeSpan.FromMilliseconds(minimumMilliseconds)) DisposeTimer(); - else if (!(dispatcherTimer is null)) { + else if (dispatcherTimer is not null) { // Settings got changed, always write the value even if it's identical. If we // don't, the next image could be shown in eg. 1 second. dispatcherTimer.Interval = backgroundImageSettings.Interval; diff --git a/dnSpy/dnSpy/BackgroundImage/RawSettings.cs b/dnSpy/dnSpy/BackgroundImage/RawSettings.cs index edbd24694b..1e2ebe8352 100644 --- a/dnSpy/dnSpy/BackgroundImage/RawSettings.cs +++ b/dnSpy/dnSpy/BackgroundImage/RawSettings.cs @@ -27,7 +27,7 @@ You should have received a copy of the GNU General Public License namespace dnSpy.BackgroundImage { sealed class RawSettings : IEquatable { - public bool IsValid => !(Id is null); + public bool IsValid => Id is not null; public string? Id { get; private set; } public Stretch Stretch { get; set; } public StretchDirection StretchDirection { get; set; } diff --git a/dnSpy/dnSpy/BackgroundImage/TextViewBackgroundImageService.cs b/dnSpy/dnSpy/BackgroundImage/TextViewBackgroundImageService.cs index d31191bb82..766078945a 100644 --- a/dnSpy/dnSpy/BackgroundImage/TextViewBackgroundImageService.cs +++ b/dnSpy/dnSpy/BackgroundImage/TextViewBackgroundImageService.cs @@ -69,7 +69,7 @@ protected override void OnEnabledCore() { protected override void OnDisabledCore() { wpfTextView.LayoutChanged -= WpfTextView_LayoutChanged; - if (!(adornmentLayer is null)) + if (adornmentLayer is not null) adornmentLayer.RemoveAllAdornments(); } diff --git a/dnSpy/dnSpy/Bookmarks/DotNet/BookmarkLocationFormatterProviderImpl.cs b/dnSpy/dnSpy/Bookmarks/DotNet/BookmarkLocationFormatterProviderImpl.cs index a77039e665..451e4d8f3f 100644 --- a/dnSpy/dnSpy/Bookmarks/DotNet/BookmarkLocationFormatterProviderImpl.cs +++ b/dnSpy/dnSpy/Bookmarks/DotNet/BookmarkLocationFormatterProviderImpl.cs @@ -34,7 +34,7 @@ sealed class BookmarkLocationFormatterProviderImpl : BookmarkLocationFormatterPr switch (location) { case DotNetMethodBodyBookmarkLocationImpl loc: var formatter = loc.Formatter; - if (!(formatter is null)) + if (formatter is not null) return formatter; formatter = bookmarkFormatterService.Value.Create(loc); loc.Formatter = formatter; @@ -42,7 +42,7 @@ sealed class BookmarkLocationFormatterProviderImpl : BookmarkLocationFormatterPr case DotNetTokenBookmarkLocationImpl loc: formatter = loc.Formatter; - if (!(formatter is null)) + if (formatter is not null) return formatter; formatter = bookmarkFormatterService.Value.Create(loc); loc.Formatter = formatter; diff --git a/dnSpy/dnSpy/Bookmarks/DotNet/BookmarkLocationSerializerImpl.cs b/dnSpy/dnSpy/Bookmarks/DotNet/BookmarkLocationSerializerImpl.cs index 6d52d41bbe..363265e4d4 100644 --- a/dnSpy/dnSpy/Bookmarks/DotNet/BookmarkLocationSerializerImpl.cs +++ b/dnSpy/dnSpy/Bookmarks/DotNet/BookmarkLocationSerializerImpl.cs @@ -53,7 +53,7 @@ public override void Serialize(ISettingsSection section, BookmarkLocation locati if (!iloc.Module.IsInMemory && !iloc.Module.IsDynamic) { var s = GetTokenAsString(iloc.Module, iloc.Token); - if (!(s is null)) + if (s is not null) section.Attribute("TokenString", s); } } diff --git a/dnSpy/dnSpy/Bookmarks/DotNet/TextEditor/BookmarkDocumentProviderImpl.cs b/dnSpy/dnSpy/Bookmarks/DotNet/TextEditor/BookmarkDocumentProviderImpl.cs index 98f644b111..3cefb00caf 100644 --- a/dnSpy/dnSpy/Bookmarks/DotNet/TextEditor/BookmarkDocumentProviderImpl.cs +++ b/dnSpy/dnSpy/Bookmarks/DotNet/TextEditor/BookmarkDocumentProviderImpl.cs @@ -64,7 +64,7 @@ sealed class BookmarkDocumentImpl : BookmarkDocument { var documentViewer = tab?.TryGetDocumentViewer(); if (documentViewer is null) return null; - Debug2.Assert(!(tab is null)); + Debug2.Assert(tab is not null); var methodDebugService = documentViewer.GetMethodDebugService(); var info = methodDebugService.TryGetMethodDebugInfo(new ModuleTokenId(bodyLoc.Module, bodyLoc.Token)); if (info is null) @@ -79,7 +79,7 @@ sealed class BookmarkDocumentImpl : BookmarkDocument { var documentViewer = tab?.TryGetDocumentViewer(); if (documentViewer is null) return null; - Debug2.Assert(!(tab is null)); + Debug2.Assert(tab is not null); foreach (var info in documentViewer.ReferenceCollection) { if (!info.Data.IsDefinition) diff --git a/dnSpy/dnSpy/Bookmarks/DotNet/TextEditor/DeleteBookmarksInRemovedModules.cs b/dnSpy/dnSpy/Bookmarks/DotNet/TextEditor/DeleteBookmarksInRemovedModules.cs index 046d181714..35dd4606fa 100644 --- a/dnSpy/dnSpy/Bookmarks/DotNet/TextEditor/DeleteBookmarksInRemovedModules.cs +++ b/dnSpy/dnSpy/Bookmarks/DotNet/TextEditor/DeleteBookmarksInRemovedModules.cs @@ -54,7 +54,7 @@ void Initialize_UI() { } void DocumentTabService_FileCollectionChanged(object? sender, NotifyDocumentCollectionChangedEventArgs e) { - Debug2.Assert(!(bookmarksService is null)); + Debug2.Assert(bookmarksService is not null); if (bookmarksService is null) return; switch (e.Type) { @@ -85,7 +85,7 @@ void DocumentTabService_FileCollectionChanged(object? sender, NotifyDocumentColl bookmarksToRemove.Add(bm); } } - if (!(bookmarksToRemove is null)) + if (bookmarksToRemove is not null) bookmarksService.Remove(bookmarksToRemove.ToArray()); break; diff --git a/dnSpy/dnSpy/Bookmarks/Impl/BookmarkLocationFormatterService.cs b/dnSpy/dnSpy/Bookmarks/Impl/BookmarkLocationFormatterService.cs index 72b63a6d1a..a1cb3a12bb 100644 --- a/dnSpy/dnSpy/Bookmarks/Impl/BookmarkLocationFormatterService.cs +++ b/dnSpy/dnSpy/Bookmarks/Impl/BookmarkLocationFormatterService.cs @@ -44,7 +44,7 @@ public override BookmarkLocationFormatter GetFormatter(BookmarkLocation location foreach (var lz in bookmarkLocationFormatterProviders) { if (Array.IndexOf(lz.Metadata.Types, type) >= 0) { var formatter = lz.Value.Create(location); - if (!(formatter is null)) + if (formatter is not null) return formatter; } } diff --git a/dnSpy/dnSpy/Bookmarks/Impl/BookmarkLocationSerializerService.cs b/dnSpy/dnSpy/Bookmarks/Impl/BookmarkLocationSerializerService.cs index 87735196d9..beee318c0f 100644 --- a/dnSpy/dnSpy/Bookmarks/Impl/BookmarkLocationSerializerService.cs +++ b/dnSpy/dnSpy/Bookmarks/Impl/BookmarkLocationSerializerService.cs @@ -55,7 +55,7 @@ public override void Serialize(ISettingsSection section, BookmarkLocation locati var bmType = location.Type; var serializer = TryGetSerializer(bmType); - Debug2.Assert(!(serializer is null)); + Debug2.Assert(serializer is not null); if (serializer is null) return; @@ -68,11 +68,11 @@ public override void Serialize(ISettingsSection section, BookmarkLocation locati return null; var typeFullName = section.Attribute("__BMT"); - Debug2.Assert(!(typeFullName is null)); + Debug2.Assert(typeFullName is not null); if (typeFullName is null) return null; var serializer = TryGetSerializer(typeFullName); - Debug2.Assert(!(serializer is null)); + Debug2.Assert(serializer is not null); if (serializer is null) return null; diff --git a/dnSpy/dnSpy/Bookmarks/Impl/BookmarksSerializer.cs b/dnSpy/dnSpy/Bookmarks/Impl/BookmarksSerializer.cs index fcea221a5b..19c61860c9 100644 --- a/dnSpy/dnSpy/Bookmarks/Impl/BookmarksSerializer.cs +++ b/dnSpy/dnSpy/Bookmarks/Impl/BookmarksSerializer.cs @@ -69,7 +69,7 @@ public void Save(Bookmark[] bookmarks) { bmSect.Attribute("IsEnabled", bmSettings.IsEnabled); bookmarkLocationSerializerService.Serialize(bmSect.CreateSection("BML"), bm.Location); bmSect.Attribute("Name", bm.Name ?? string.Empty); - if (!(bmSettings.Labels is null) && bmSettings.Labels.Count != 0) + if (bmSettings.Labels is not null && bmSettings.Labels.Count != 0) SaveLabels(bmSect, bmSettings.Labels.ToArray()); } } diff --git a/dnSpy/dnSpy/Bookmarks/Impl/BookmarksServiceImpl.cs b/dnSpy/dnSpy/Bookmarks/Impl/BookmarksServiceImpl.cs index 5382c913ff..48aa271357 100644 --- a/dnSpy/dnSpy/Bookmarks/Impl/BookmarksServiceImpl.cs +++ b/dnSpy/dnSpy/Bookmarks/Impl/BookmarksServiceImpl.cs @@ -63,7 +63,7 @@ void ModifyCore(BookmarkAndSettings[] settings) { lock (lockObj) { foreach (var info in settings) { var bmImpl = info.Bookmark as BookmarkImpl; - Debug2.Assert(!(bmImpl is null)); + Debug2.Assert(bmImpl is not null); if (bmImpl is null) continue; Debug.Assert(bookmarks.Contains(bmImpl)); @@ -133,7 +133,7 @@ void AddCore(List bookmarks, List? objsToClose) { } } } - if (!(objsToClose is null)) { + if (objsToClose is not null) { foreach (var obj in objsToClose) obj.Close(); } @@ -153,7 +153,7 @@ void RemoveCore(Bookmark[] bookmarks) { lock (lockObj) { foreach (var bm in bookmarks) { var bmImpl = bm as BookmarkImpl; - Debug2.Assert(!(bmImpl is null)); + Debug2.Assert(bmImpl is not null); if (bmImpl is null) continue; if (!this.bookmarks.Contains(bmImpl)) diff --git a/dnSpy/dnSpy/Bookmarks/Navigator/BookmarkNavigatorImpl.cs b/dnSpy/dnSpy/Bookmarks/Navigator/BookmarkNavigatorImpl.cs index b6b0bdfce7..deec835e2b 100644 --- a/dnSpy/dnSpy/Bookmarks/Navigator/BookmarkNavigatorImpl.cs +++ b/dnSpy/dnSpy/Bookmarks/Navigator/BookmarkNavigatorImpl.cs @@ -114,7 +114,7 @@ void ViewBookmarkProvider_BookmarksViewOrderChanged_UI() { return null; foreach (var lz in bookmarkDocumentProviders) { var doc = lz.Value.GetDocument(bookmark); - if (!(doc is null)) + if (doc is not null) return doc; } return null; diff --git a/dnSpy/dnSpy/Bookmarks/TextEditor/BookmarkGlyphTextMarkerLocationProviderService.cs b/dnSpy/dnSpy/Bookmarks/TextEditor/BookmarkGlyphTextMarkerLocationProviderService.cs index 0c70de985c..cf8d9b255e 100644 --- a/dnSpy/dnSpy/Bookmarks/TextEditor/BookmarkGlyphTextMarkerLocationProviderService.cs +++ b/dnSpy/dnSpy/Bookmarks/TextEditor/BookmarkGlyphTextMarkerLocationProviderService.cs @@ -43,7 +43,7 @@ sealed class BookmarkGlyphTextMarkerLocationProviderServiceImpl : BookmarkGlyphT throw new ArgumentNullException(nameof(bookmark)); foreach (var lz in bookmarkGlyphTextMarkerLocationProviders) { var loc = lz.Value.GetLocation(bookmark); - if (!(loc is null)) + if (loc is not null) return loc; } return null; diff --git a/dnSpy/dnSpy/Bookmarks/TextEditor/BookmarkMarker.cs b/dnSpy/dnSpy/Bookmarks/TextEditor/BookmarkMarker.cs index 5c28730d61..8cbe2f19ad 100644 --- a/dnSpy/dnSpy/Bookmarks/TextEditor/BookmarkMarker.cs +++ b/dnSpy/dnSpy/Bookmarks/TextEditor/BookmarkMarker.cs @@ -100,7 +100,7 @@ void OnBookmarksAdded_UI(CollectionChangedEventArgs e) { throw new InvalidOperationException(); foreach (var bm in e.Objects) { var location = bookmarkGlyphTextMarkerLocationProviderService.GetLocation(bm); - if (!(location is null)) { + if (location is not null) { bm.GetOrCreateData(() => new BookmarkData(location)); UpdateMarker(bm); continue; @@ -120,7 +120,7 @@ void OnBookmarksModified_UI(IList bookmarks) { uiDispatcher.VerifyAccess(); var bms = new List(bookmarks.Count); var removedMarkers = new List(bookmarks.Count); - Debug2.Assert(!(bookmarkInfos is null)); + Debug2.Assert(bookmarkInfos is not null); for (int i = 0; i < bookmarks.Count; i++) { var bm = bookmarks[i]; if (!bm.TryGetData(out BookmarkData? data)) @@ -142,12 +142,12 @@ void UpdateMarker(Bookmark bm) { if (!bm.TryGetData(out BookmarkData? data)) return; - Debug2.Assert(!(bookmarkInfos is null)); + Debug2.Assert(bookmarkInfos is not null); var info = bookmarkInfos[(int)BookmarkImageUtilities.GetBookmarkKind(bm)]; - if (data.Info == info && !(data.Marker is null)) + if (data.Info == info && data.Marker is not null) return; data.Info = info; - if (!(data.Marker is null)) + if (data.Marker is not null) glyphTextMarkerService.Value.Remove(data.Marker); data.Marker = glyphTextMarkerService.Value.AddMarker(data.Location, info.ImageReference, info.MarkerTypeName, info.SelectedMarkerTypeName, info.ClassificationType, info.ZIndex, bm, bookmarkGlyphTextMarkerHandler, null); diff --git a/dnSpy/dnSpy/Bookmarks/TextEditor/TextViewBookmarkService.cs b/dnSpy/dnSpy/Bookmarks/TextEditor/TextViewBookmarkService.cs index d8439e661d..cf5242cee4 100644 --- a/dnSpy/dnSpy/Bookmarks/TextEditor/TextViewBookmarkService.cs +++ b/dnSpy/dnSpy/Bookmarks/TextEditor/TextViewBookmarkService.cs @@ -118,7 +118,7 @@ LocationsResult GetLocation(IDocumentTab? tab, VirtualSnapshotPoint? position) { var textView = GetTextView(tab); if (textView is null) return new LocationsResult(bookmarksService, null, allLocations); - Debug2.Assert(!(tab is null)); + Debug2.Assert(tab is not null); var pos = position ?? textView.Caret.Position.VirtualBufferPosition; if (pos.Position.Snapshot != textView.TextSnapshot) throw new ArgumentException(); @@ -191,7 +191,7 @@ public ToggleCreateBreakpointInfoResult(Lazy bookmarksService, } public void Dispose() { - if (!(location is null)) + if (location is not null) bookmarksService.Value.Close(location); } @@ -221,7 +221,7 @@ void ToggleCreateBookmark(ToggleCreateBreakpointInfoResult info) { switch (info.kind) { case ToggleCreateBookmarkKind.Add: var bookmark = bookmarksService.Value.Add(new Contracts.Bookmarks.BookmarkInfo(info.TakeOwnershipOfLocation()!, new BookmarkSettings() { IsEnabled = true })); - if (!(bookmark is null)) + if (bookmark is not null) bookmarkNavigator.Value.SetActiveBookmarkNoCheck(bookmark); break; @@ -324,7 +324,7 @@ public override void ClearAllBookmarksInDocument() { return null; foreach (var lz in bookmarkDocumentProviders) { var doc = lz.Value.GetDocument(bookmark); - if (!(doc is null)) + if (doc is not null) return doc; } return null; diff --git a/dnSpy/dnSpy/Bookmarks/ToolWindows/Bookmarks/BookmarksOperations.cs b/dnSpy/dnSpy/Bookmarks/ToolWindows/Bookmarks/BookmarksOperations.cs index c0d6623e5c..55285e9194 100644 --- a/dnSpy/dnSpy/Bookmarks/ToolWindows/Bookmarks/BookmarksOperations.cs +++ b/dnSpy/dnSpy/Bookmarks/ToolWindows/Bookmarks/BookmarksOperations.cs @@ -272,7 +272,7 @@ public override void ImportBookmarks() { var filename = pickFilename.GetFilename(null, "xml", PickFilenameConstants.XmlFilenameFilter); if (!File.Exists(filename)) return; - Debug2.Assert(!(filename is null)); + Debug2.Assert(filename is not null); var settingsService = settingsServiceFactory.Value.Create(); try { settingsService.Open(filename); @@ -316,7 +316,7 @@ public override void EditLabels() { SelectedItems[0].LabelsEditableValue.IsEditingValue = true; else { var newLabels = messageBoxService.Ask(dnSpy_Resources.EditLabelsMsgBoxLabel, SelectedItems[0].GetLabelsString(), dnSpy_Resources.EditLabelsTitle); - if (!(newLabels is null)) { + if (newLabels is not null) { var labelsColl = BookmarkVM.CreateLabelsCollection(newLabels); bookmarksService.Value.Modify(SelectedItems.Select(a => { var bm = a.Bookmark; diff --git a/dnSpy/dnSpy/Bookmarks/ToolWindows/LazyToolWindowVMHelper.cs b/dnSpy/dnSpy/Bookmarks/ToolWindows/LazyToolWindowVMHelper.cs index fb3fa0518e..84655a20ba 100644 --- a/dnSpy/dnSpy/Bookmarks/ToolWindows/LazyToolWindowVMHelper.cs +++ b/dnSpy/dnSpy/Bookmarks/ToolWindows/LazyToolWindowVMHelper.cs @@ -100,7 +100,7 @@ void StartTimer() { } void StopTimer() { - if (!(timer is null)) { + if (timer is not null) { timer.Tick -= Timer_Tick_UI; timer.Stop(); timer = null; diff --git a/dnSpy/dnSpy/Commands/CommandService.cs b/dnSpy/dnSpy/Commands/CommandService.cs index da934eb5ed..5c3041cda3 100644 --- a/dnSpy/dnSpy/Commands/CommandService.cs +++ b/dnSpy/dnSpy/Commands/CommandService.cs @@ -62,7 +62,7 @@ public IRegisteredCommandElement Register(UIElement sourceElement, object target if (c2 is null) continue; var cmd = c2.CreateFromTextInput(target, text); - if (!(cmd is null)) + if (cmd is not null) return cmd; } return null; diff --git a/dnSpy/dnSpy/Commands/RegisteredCommandElement.cs b/dnSpy/dnSpy/Commands/RegisteredCommandElement.cs index b3f10a289a..3b65400544 100644 --- a/dnSpy/dnSpy/Commands/RegisteredCommandElement.cs +++ b/dnSpy/dnSpy/Commands/RegisteredCommandElement.cs @@ -132,7 +132,7 @@ public RegisteredCommandElement(CommandService commandService, UIElement sourceE CommandInfo GetCommand(KeyEventArgs e, object target, out bool waitForSecondKey) { var keyInput = new KeyInput(e); ProviderAndCommand result; - if (!(prevKey is null)) { + if (prevKey is not null) { waitForSecondKey = false; var keyShortcut = new KeyShortcut(prevKey.Value, keyInput); result = keyShortcutCollection.GetTwoKeyShortcuts(keyShortcut).FirstOrDefault(); diff --git a/dnSpy/dnSpy/Controls/FastTreeNodeView.cs b/dnSpy/dnSpy/Controls/FastTreeNodeView.cs index a692b55300..3e5e9986e3 100644 --- a/dnSpy/dnSpy/Controls/FastTreeNodeView.cs +++ b/dnSpy/dnSpy/Controls/FastTreeNodeView.cs @@ -43,7 +43,7 @@ static FastTreeNodeView() => DefaultStyleKeyProperty.OverrideMetadata(typeof(Fas static readonly object toolTipDummy = new object(); void InitializeChildrens() { - if (!(expander is null)) + if (expander is not null) return; ToolTip = toolTipDummy; @@ -64,8 +64,8 @@ void InitializeChildrens() { Focusable = false }; - expander.Checked += (sender, e) => { if (!(Node is null)) Node.IsExpanded = true; }; - expander.Unchecked += (sender, e) => { if (!(Node is null)) Node.IsExpanded = false; }; + expander.Checked += (sender, e) => { if (Node is not null) Node.IsExpanded = true; }; + expander.Unchecked += (sender, e) => { if (Node is not null) Node.IsExpanded = false; }; AddVisualChild(expander); AddVisualChild(icon); diff --git a/dnSpy/dnSpy/Controls/Screen.cs b/dnSpy/dnSpy/Controls/Screen.cs index 80b81a0410..6568cfaa67 100644 --- a/dnSpy/dnSpy/Controls/Screen.cs +++ b/dnSpy/dnSpy/Controls/Screen.cs @@ -90,7 +90,7 @@ public Screen(DependencyObject? o) { var helper = GetHelper(o); IsValid = false; info = default; - if (!(helper is null)) { + if (helper is not null) { var hMonitor = MonitorFromWindow(helper.Handle, MONITOR_DEFAULTTONEAREST); info.cbSize = MONITORINFOEX.SIZE; if (!GetMonitorInfo(hMonitor, ref info)) diff --git a/dnSpy/dnSpy/Controls/StackedContent.cs b/dnSpy/dnSpy/Controls/StackedContent.cs index 03280222b8..2759bfa1cd 100644 --- a/dnSpy/dnSpy/Controls/StackedContent.cs +++ b/dnSpy/dnSpy/Controls/StackedContent.cs @@ -150,7 +150,7 @@ public StackedContent(bool isHorizontal = true, double splitterLength = DEFAULT_ children = new List(); grid = new Grid(); grid.SetResourceReference(FrameworkElement.StyleProperty, "StackedContentGridStyle"); - if (!(margin is null)) + if (margin is not null) grid.Margin = margin.Value; this.isHorizontal = isHorizontal; this.splitterLength = splitterLength; @@ -212,9 +212,9 @@ void UpdateGrid(bool horizontal) { } var rowDef = new RowDefinition() { Height = GetGridLength(info.LengthInfo.Vertical.GridLength!.Value, -d) }; - if (!(info.LengthInfo.Vertical.MaxLength is null)) + if (info.LengthInfo.Vertical.MaxLength is not null) rowDef.MaxHeight = info.LengthInfo.Vertical.MaxLength.Value; - if (!(info.LengthInfo.Vertical.MinLength is null)) + if (info.LengthInfo.Vertical.MinLength is not null) rowDef.MinHeight = info.LengthInfo.Vertical.MinLength.Value; grid.RowDefinitions.Add(rowDef); var uiel = GetUIElement(info.Child); @@ -246,9 +246,9 @@ void UpdateGrid(bool horizontal) { } var colDef = new ColumnDefinition() { Width = GetGridLength(info.LengthInfo.Horizontal.GridLength!.Value, -d) }; - if (!(info.LengthInfo.Horizontal.MaxLength is null)) + if (info.LengthInfo.Horizontal.MaxLength is not null) colDef.MaxWidth = info.LengthInfo.Horizontal.MaxLength.Value; - if (!(info.LengthInfo.Horizontal.MinLength is null)) + if (info.LengthInfo.Horizontal.MinLength is not null) colDef.MinWidth = info.LengthInfo.Horizontal.MinLength.Value; grid.ColumnDefinitions.Add(colDef); var uiel = GetUIElement(info.Child); diff --git a/dnSpy/dnSpy/Controls/WinSysButton.cs b/dnSpy/dnSpy/Controls/WinSysButton.cs index b7cb73ea0b..fa9dd54f8e 100644 --- a/dnSpy/dnSpy/Controls/WinSysButton.cs +++ b/dnSpy/dnSpy/Controls/WinSysButton.cs @@ -63,7 +63,7 @@ public CurrentWinSysType CurrentWinSysType { void WinSysButton_Loaded(object? sender, RoutedEventArgs e) { Loaded -= WinSysButton_Loaded; window = Window.GetWindow(this); - if (!(window is null)) // null if in design mode + if (window is not null) // null if in design mode window.StateChanged += window_StateChanged; } diff --git a/dnSpy/dnSpy/Controls/WpfFocusService.cs b/dnSpy/dnSpy/Controls/WpfFocusService.cs index 533e2b3647..ff941e3ec8 100644 --- a/dnSpy/dnSpy/Controls/WpfFocusService.cs +++ b/dnSpy/dnSpy/Controls/WpfFocusService.cs @@ -36,7 +36,7 @@ sealed class WpfFocusService : IWpfFocusService { WpfFocusService([ImportMany] IEnumerable> checkers) => this.checkers = checkers.ToArray(); public void Focus(IInputElement element) { - Debug2.Assert(!(element is null) && element.Focusable); + Debug2.Assert(element is not null && element.Focusable); if (element is null || !element.Focusable) return; if (CanFocus) diff --git a/dnSpy/dnSpy/Culture/CultureService.cs b/dnSpy/dnSpy/Culture/CultureService.cs index e0e79630d0..00eddf2cf5 100644 --- a/dnSpy/dnSpy/Culture/CultureService.cs +++ b/dnSpy/dnSpy/Culture/CultureService.cs @@ -48,7 +48,7 @@ sealed class CultureService : ICultureService { public bool HasExtraLanguages { get { InitializeSupportedLanguages(); - Debug2.Assert(!(extraLanguages is null)); + Debug2.Assert(extraLanguages is not null); return extraLanguages.Length > 0; } } @@ -56,7 +56,7 @@ public bool HasExtraLanguages { public IEnumerable AllLanguages { get { InitializeSupportedLanguages(); - Debug2.Assert(!(extraLanguages is null)); + Debug2.Assert(extraLanguages is not null); var langs = new HashSet(); langs.Add(LanguageInfo.CreateSystemLanguage()); foreach (var ci in extraLanguages) @@ -71,7 +71,7 @@ public IEnumerable AllLanguages { public LanguageInfo Language { get { var cultureInfo = UICulture; - if (!(cultureInfo is null)) + if (cultureInfo is not null) return LanguageInfo.Create(cultureInfo); return LanguageInfo.CreateSystemLanguage(); } @@ -122,7 +122,7 @@ void InitializeCulture(CultureInfo? info) { } void InitializeSupportedLanguages() { - if (!(extraLanguages is null)) + if (extraLanguages is not null) return; var langs = new HashSet(); foreach (var di in GetDirectories(AppDirectories.BinDirectory)) { @@ -133,7 +133,7 @@ void InitializeSupportedLanguages() { if (files.Length == 0) continue; var ci = TryCreateCultureInfo(Path.GetFileName(di)); - if (!(ci is null)) + if (ci is not null) langs.Add(ci); } diff --git a/dnSpy/dnSpy/Decompiler/MethodDebugService.cs b/dnSpy/dnSpy/Decompiler/MethodDebugService.cs index 0ce83f992a..c2068be9ec 100644 --- a/dnSpy/dnSpy/Decompiler/MethodDebugService.cs +++ b/dnSpy/dnSpy/Decompiler/MethodDebugService.cs @@ -114,7 +114,7 @@ IList FindByTextPositionCore(int textPosition, FindByText var methodStatements = FindByLineAndTextOffset(scopeSpan, lineStartPos, lineEndPos, textPosition); if (methodStatements is null && lineStartPos != textPosition) methodStatements = FindByLineAndTextOffset(scopeSpan, lineStartPos, lineEndPos, lineStartPos); - if (!(methodStatements is null) && methodStatements.Count > 1) { + if (methodStatements is not null && methodStatements.Count > 1) { // If there are two methods (get; set;) on the same line, only return one of them var exact = methodStatements.Where(a => a.Statement.TextSpan != scopeSpan && a.Statement.TextSpan.Contains(textPosition)).ToList(); if (exact.Count != 0) @@ -127,7 +127,7 @@ IList FindByTextPositionCore(int textPosition, FindByText methodStatements = Filter(methodStatements, textPosition); - if (!(methodStatements is null)) { + if (methodStatements is not null) { if ((options & FindByTextPositionOptions.SameMethod) == 0 || IsSameMethod(methodStatements, textPosition)) return methodStatements; } @@ -136,7 +136,7 @@ IList FindByTextPositionCore(int textPosition, FindByText TextSpan GetScopeSpan(int textPosition) { int stmtIndex = GetScopeSpanStartIndex(textPosition); - Debug2.Assert(!(sortedStatements is null)); + Debug2.Assert(sortedStatements is not null); if (stmtIndex >= 0) { var scopeSpan = sortedStatements[stmtIndex].Statement.TextSpan; if (scopeSpan.Contains(textPosition)) @@ -173,7 +173,7 @@ bool IsSameMethod(List methodStatements, int textPosition if (methodStatements.Count == 0) return false; var methodInfo = TryGetMethodDebugInfo(methodStatements[0].Method); - Debug2.Assert(!(methodInfo is null)); + Debug2.Assert(methodInfo is not null); if (methodInfo is null) return false; var methodSpan = methodInfo.Span; @@ -196,7 +196,7 @@ bool IsSameMethod(List methodStatements, int textPosition foreach (var kv in dict) { var info = kv.Value; var sourceStatement = info.GetSourceStatementByTextOffset(lineStart, lineEnd, textPosition); - if (!(sourceStatement is null) && sourceStatement.Value.TextSpan.Start >= scopeSpan.Start && sourceStatement.Value.TextSpan.End <= scopeSpan.End) { + if (sourceStatement is not null && sourceStatement.Value.TextSpan.Start >= scopeSpan.Start && sourceStatement.Value.TextSpan.End <= scopeSpan.End) { if (list is null) list = new List(); list.Add(new MethodSourceStatement(info.Method, sourceStatement.Value)); @@ -222,7 +222,7 @@ bool IsSameMethod(List methodStatements, int textPosition methodSourceStatement = new MethodSourceStatement(info.Method, sourceStatement); } } - if (!(methodSourceStatement is null)) { + if (methodSourceStatement is not null) { if (list.Count == 0) list.Add(methodSourceStatement.Value); else if (methodSourceStatement.Value.Statement.TextSpan.Start == list[0].Statement.TextSpan.Start) @@ -270,7 +270,7 @@ public IEnumerable GetStatementsByTextSpan(Span span) { int position = span.Start; int end = span.End; int index = GetStartIndex(position); - Debug2.Assert(!(sortedStatements is null)); + Debug2.Assert(sortedStatements is not null); if (index < 0) yield break; var array = sortedStatements; @@ -307,7 +307,7 @@ bool TryGetOuterMostSpan(int position, out TextSpan outermostSpan) { int GetScopeSpanStartIndex(int position) { if (sortedStatements is null) InitializeSortedStatements(); - Debug2.Assert(!(sortedStatements is null)); + Debug2.Assert(sortedStatements is not null); int index = GetStartIndexCore(position); var array = sortedStatements; @@ -338,7 +338,7 @@ int GetScopeSpanStartIndex(int position) { } int GetStartIndexCore(int position) { - Debug2.Assert(!(sortedStatements is null)); + Debug2.Assert(sortedStatements is not null); var array = sortedStatements; int lo = 0, hi = array.Length - 1; while (lo <= hi) { @@ -362,7 +362,7 @@ int GetStartIndexCore(int position) { void InitializeSortedStatements() { Debug2.Assert(sortedStatements is null); - if (!(sortedStatements is null)) + if (sortedStatements is not null) return; var list = new List(); foreach (var kv in dict) { diff --git a/dnSpy/dnSpy/Disassembly/Viewer/DisassemblyDocumentTabContent.cs b/dnSpy/dnSpy/Disassembly/Viewer/DisassemblyDocumentTabContent.cs index 63bbcdba38..4c4f22855b 100644 --- a/dnSpy/dnSpy/Disassembly/Viewer/DisassemblyDocumentTabContent.cs +++ b/dnSpy/dnSpy/Disassembly/Viewer/DisassemblyDocumentTabContent.cs @@ -84,7 +84,7 @@ public override void OnShow(IShowContext ctx) { var bracesStack = new Stack<(int pos, char brace)>(); foreach (var info in disasmContent.Text) { var text = info.Text; - if (!(info.Reference is null)) + if (info.Reference is not null) output.Write(text, info.Reference, ToDecompilerReferenceFlags(info.ReferenceFlags), info.Color); else output.Write(text, info.Color); diff --git a/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentGenerator.cs b/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentGenerator.cs index 645937c7e5..b8632767ed 100644 --- a/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentGenerator.cs +++ b/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentGenerator.cs @@ -218,14 +218,14 @@ public static void Write(int bitness, DisassemblyContentOutput output, string? h WriteComment(output, commentPrefix, LINE); output.Write(Environment.NewLine, BoxedTextColor.Text); } - if (!(header is null)) { + if (header is not null) { WriteComment(output, commentPrefix, header); output.Write(Environment.NewLine, BoxedTextColor.Text); } - if (!(moduleName is null)) + if (moduleName is not null) WriteComment(output, commentPrefix, moduleName); - if (!(methodName is null)) + if (methodName is not null) WriteComment(output, commentPrefix, methodName); WriteComment(output, commentPrefix, GetCodeSizeString(blocks)); output.Write(Environment.NewLine, BoxedTextColor.Text); @@ -244,7 +244,7 @@ public static void Write(int bitness, DisassemblyContentOutput output, string? h sb.Append(' '); } var name = varInfo.Name ?? GetName(variableInfo, varInfo); - if (!(name is null)) { + if (name is not null) { printedName = true; if (varInfo.Index >= 0) sb.Append('('); diff --git a/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentProviderFactory.cs b/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentProviderFactory.cs index 3d42c45000..baa4a007a7 100644 --- a/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentProviderFactory.cs +++ b/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentProviderFactory.cs @@ -77,7 +77,7 @@ public DisassemblyContentProviderFactory(DisassemblyContentProviderFactoryDepend public DisassemblyContentProvider Create() { var blocks = BlockFactory.Create(bitness, this.blocks); var cachedSymResolver = new CachedSymbolResolver(); - if (!(symbolResolver is null)) { + if (symbolResolver is not null) { var addresses = GetPossibleSymbolAddresses(blocks); if (addresses.Length != 0) { var symbolResolverResults = new SymbolResolverResult[addresses.Length]; diff --git a/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentProviderImpl.cs b/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentProviderImpl.cs index dc68b73df8..91969f3473 100644 --- a/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentProviderImpl.cs +++ b/dnSpy/dnSpy/Disassembly/Viewer/X86/DisassemblyContentProviderImpl.cs @@ -41,7 +41,7 @@ public override string? Description { sb.AppendLine(dnSpy_Resources.Disassembly_MethodIsNotOptimized); sb.AppendLine(DisassemblyContentGenerator.LINE); } - if (!(moduleName is null)) + if (moduleName is not null) sb.AppendLine(moduleName); sb.AppendLine(methodName); sb.Append(DisassemblyContentGenerator.GetCodeSizeString(blocks)); diff --git a/dnSpy/dnSpy/Disassembly/X86/BlockFactory.cs b/dnSpy/dnSpy/Disassembly/X86/BlockFactory.cs index 78496db73a..ef50272977 100644 --- a/dnSpy/dnSpy/Disassembly/X86/BlockFactory.cs +++ b/dnSpy/dnSpy/Disassembly/X86/BlockFactory.cs @@ -175,7 +175,7 @@ public static Block[] Create(int bitness, NativeCodeBlock[] blocks) { newBlocks.Add(currentBlock); } // The addr of each block is always in the dictionary so currentBlock is initialized - Debug2.Assert(!(currentBlock.Instructions is null)); + Debug2.Assert(currentBlock.Instructions is not null); currentBlock.Instructions.Add(new X86InstructionInfo(info.code, instr)); } diff --git a/dnSpy/dnSpy/Documents/AssemblyResolver.cs b/dnSpy/dnSpy/Documents/AssemblyResolver.cs index e816f493ae..6efea3037e 100644 --- a/dnSpy/dnSpy/Documents/AssemblyResolver.cs +++ b/dnSpy/dnSpy/Documents/AssemblyResolver.cs @@ -124,11 +124,11 @@ public void MarkFailed(IAssembly asm) { if (!result.IsDefault) { if (!string2.IsNullOrEmpty(result.Filename)) { var file = documentService.Find(FilenameKey.CreateFullPath(result.Filename), checkTempCache: true); - if (!(file is null)) + if (file is not null) return file; } - if (!(result.GetFileData is null)) + if (result.GetFileData is not null) return documentService.TryGetOrCreateInternal(DsDocumentInfo.CreateInMemory(result.GetFileData, result.Filename), true, true); if (!string2.IsNullOrEmpty(result.Filename)) return documentService.TryGetOrCreateInternal(DsDocumentInfo.CreateDocument(result.Filename), true, true); @@ -283,7 +283,7 @@ FrameworkKind GetRuntimeFrameworkKind(string filename, out Version? netVersion) } netVersion = dotNetPathProvider.TryGetDotNetVersion(filename); - if (!(netVersion is null)) + if (netVersion is not null) return FrameworkKind.DotNet; netVersion = null; @@ -361,7 +361,7 @@ static bool TryParseNetFrameworkVersion(string prefix, string tfm, [NotNullWhen( FrameworkKind GetFrameworkKind_TargetFrameworkAttribute(ModuleDef module, out string? frameworkName, out Version? version) { var asm = module.Assembly; - if (!(asm is null) && asm.TryGetOriginalTargetFrameworkAttribute(out frameworkName, out version, out _)) { + if (asm is not null && asm.TryGetOriginalTargetFrameworkAttribute(out frameworkName, out version, out _)) { if (frameworkName == TFM_netframework) return version.Major < 4 ? FrameworkKind.DotNetFramework2 : FrameworkKind.DotNetFramework4; if (frameworkName == TFM_netcoreapp) @@ -409,7 +409,7 @@ FrameworkKind GetFrameworkKind_AssemblyRefs(ModuleDef module, string? frameworkN } } - if (!(systemRuntimeRef is null)) { + if (systemRuntimeRef is not null) { // - .NET Core: // 1.0: System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // 1.1: System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a @@ -447,7 +447,7 @@ FrameworkKind GetFrameworkKind_AssemblyRefs(ModuleDef module, string? frameworkN } version = null; - if (!(mscorlibRef is null)) { + if (mscorlibRef is not null) { // It can't be Unity since we checked that before this method was called. // It can't be .NET Core since it uses System.Runtime. @@ -469,7 +469,7 @@ FrameworkKind GetFrameworkKind_AssemblyRefs(ModuleDef module, string? frameworkN static readonly Version version_4_2_1_0 = new Version(4, 2, 1, 0); // Silverlight uses 5.0.5.0 - static bool IsValidMscorlibVersion(Version version) => !(version is null) && (uint)version.Major <= 5; + static bool IsValidMscorlibVersion(Version version) => version is not null && (uint)version.Major <= 5; static bool StartsWith(UTF8String s, UTF8String value) { var d = s?.Data; @@ -527,7 +527,7 @@ static bool StartsWith(UTF8String s, UTF8String value) { } document = TryRuntimeAssemblyResolvers(assembly, sourceModule); - if (!(document is null)) + if (document is not null) return document; options = DsDocumentService.DefaultOptions; @@ -536,15 +536,15 @@ static bool StartsWith(UTF8String s, UTF8String value) { if (redirected) options |= FindAssemblyOptions.Version; existingDocument = documentService.FindAssembly(assembly, options); - if (!(existingDocument is null)) + if (existingDocument is not null) return existingDocument; (document, loaded) = LookupFromSearchPaths(assembly, sourceModule, sourceModuleDirectoryHint, netVersion); - if (!(document is null)) + if (document is not null) return documentService.GetOrAddCanDispose(document, assembly, loaded); var gacFile = GacInfo.FindInGac(assembly, gacVersion); - if (!(gacFile is null)) + if (gacFile is not null) return documentService.TryGetOrCreateInternal(DsDocumentInfo.CreateDocument(gacFile), true, true); foreach (var gacPath in GacInfo.OtherGacPaths) { if (gacVersion == 4) { @@ -558,7 +558,7 @@ static bool StartsWith(UTF8String s, UTF8String value) { else Debug.Assert(gacVersion == -1); document = TryLoadFromDir(assembly, checkVersion: true, checkPublicKeyToken: true, gacPath.Path); - if (!(document is null)) + if (document is not null) return documentService.GetOrAddCanDispose(document, assembly, isAutoLoaded: true); } break; @@ -568,14 +568,14 @@ static bool StartsWith(UTF8String s, UTF8String value) { case FrameworkKind.SelfContainedDotNet: case FrameworkKind.WindowsUniversal: document = TryRuntimeAssemblyResolvers(assembly, sourceModule); - if (!(document is null)) + if (document is not null) return document; // If it's a self-contained .NET app, we don't need the version since we must only search // the current directory. Debug2.Assert(fwkKind == FrameworkKind.DotNet || netVersion is null); (document, loaded) = LookupFromSearchPaths(assembly, sourceModule, sourceModuleDirectoryHint, netVersion); - if (!(document is null)) + if (document is not null) return documentService.GetOrAddCanDispose(document, assembly, loaded); // If it already exists in assembly explorer, use it @@ -583,7 +583,7 @@ static bool StartsWith(UTF8String s, UTF8String value) { if (IgnorePublicKey(fwkKind)) options &= ~FindAssemblyOptions.PublicKeyToken; existingDocument = documentService.FindAssembly(assembly, options); - if (!(existingDocument is null)) + if (existingDocument is not null) return existingDocument; break; @@ -615,7 +615,7 @@ static bool IgnorePublicKey(FrameworkKind fwkKind) { (IDsDocument? document, bool loaded) LookupFromSearchPaths(IAssembly asmName, ModuleDef? sourceModule, string? sourceModuleDir, Version? dotNetCoreAppVersion) { IDsDocument? document; - if (sourceModuleDir is null && !(sourceModule is null) && !string2.IsNullOrEmpty(sourceModule.Location)) { + if (sourceModuleDir is null && sourceModule is not null && !string2.IsNullOrEmpty(sourceModule.Location)) { try { sourceModuleDir = Path.GetDirectoryName(sourceModule.Location); } @@ -625,36 +625,36 @@ static bool IgnorePublicKey(FrameworkKind fwkKind) { } } - if (!(sourceModuleDir is null)) { + if (sourceModuleDir is not null) { document = TryFindFromDir(asmName, dirPath: sourceModuleDir); - if (!(document is null)) + if (document is not null) return (document, false); } string[]? dotNetPaths; - if (!(dotNetCoreAppVersion is null)) { + if (dotNetCoreAppVersion is not null) { int bitness = (sourceModule?.GetPointerSize(IntPtr.Size) ?? IntPtr.Size) * 8; dotNetPaths = dotNetPathProvider.TryGetDotNetPaths(dotNetCoreAppVersion, bitness); } else dotNetPaths = null; - if (!(dotNetPaths is null)) { + if (dotNetPaths is not null) { foreach (var path in dotNetPaths) { document = TryFindFromDir(asmName, dirPath: path); - if (!(document is null)) + if (document is not null) return (document, false); } } - if (!(sourceModuleDir is null)) { + if (sourceModuleDir is not null) { document = TryLoadFromDir(asmName, checkVersion: false, checkPublicKeyToken: false, dirPath: sourceModuleDir); - if (!(document is null)) + if (document is not null) return (document, true); } - if (!(dotNetPaths is null)) { + if (dotNetPaths is not null) { foreach (var path in dotNetPaths) { document = TryLoadFromDir(asmName, checkVersion: false, checkPublicKeyToken: false, dirPath: path); - if (!(document is null)) + if (document is not null) return (document, true); } } @@ -726,11 +726,11 @@ static bool IgnorePublicKey(FrameworkKind fwkKind) { IDsDocument? document; document = TryRuntimeAssemblyResolvers(assembly, sourceModule); - if (!(document is null)) + if (document is not null) return document; document = documentService.FindAssembly(assembly, DsDocumentService.DefaultOptions); - if (!(document is null)) + if (document is not null) return document; foreach (var winmdPath in GacInfo.WinmdPaths) { diff --git a/dnSpy/dnSpy/Documents/DefaultDsDocumentLoader.cs b/dnSpy/dnSpy/Documents/DefaultDsDocumentLoader.cs index 4271197745..83b8a0a1a3 100644 --- a/dnSpy/dnSpy/Documents/DefaultDsDocumentLoader.cs +++ b/dnSpy/dnSpy/Documents/DefaultDsDocumentLoader.cs @@ -33,7 +33,7 @@ public IDsDocument[] Load(IEnumerable documents) { if (doc.Info.Type == DocumentConstants.DOCUMENTTYPE_FILE && string.IsNullOrEmpty(doc.Info.Name)) continue; var document = documentService.TryGetOrCreate(doc.Info, doc.IsAutoLoaded); - if (!(document is null) && !hash.Contains(document)) { + if (document is not null && !hash.Contains(document)) { hash.Add(document); loadedDocuments.Add(document); } diff --git a/dnSpy/dnSpy/Documents/DefaultDsDocumentProvider.cs b/dnSpy/dnSpy/Documents/DefaultDsDocumentProvider.cs index c7b2f80726..2cec309fbc 100644 --- a/dnSpy/dnSpy/Documents/DefaultDsDocumentProvider.cs +++ b/dnSpy/dnSpy/Documents/DefaultDsDocumentProvider.cs @@ -32,24 +32,24 @@ sealed class DefaultDsDocumentProvider : IDsDocumentProvider { public IDsDocument? Create(IDsDocumentService documentService, DsDocumentInfo documentInfo) { if (documentInfo.Type == DocumentConstants.DOCUMENTTYPE_INMEMORY) { var getFileData = documentInfo.Data as Func<(byte[]? filedata, bool isFileLayout)>; - Debug2.Assert(!(getFileData is null)); - if (!(getFileData is null)) { + Debug2.Assert(getFileData is not null); + if (getFileData is not null) { var info = getFileData(); - if (!(info.filedata is null)) + if (info.filedata is not null) return documentService.CreateDocument(documentInfo, info.filedata, documentInfo.Name, info.isFileLayout); } return null; } var filename = GetFilename(documentInfo); - if (!(filename is null)) + if (filename is not null) return documentService.CreateDocument(documentInfo, filename); return null; } public IDsDocumentNameKey? CreateKey(IDsDocumentService documentService, DsDocumentInfo documentInfo) { var filename = GetFilename(documentInfo); - if (!(filename is null)) + if (filename is not null) return new FilenameKey(filename); return null; } @@ -77,7 +77,7 @@ sealed class DefaultDsDocumentProvider : IDsDocumentProvider { return null; var f = GetGacFilename(s.Substring(0, index)); - if (!(f is null)) + if (f is not null) return f; return s.Substring(index + DocumentConstants.REFERENCE_ASSEMBLY_SEPARATOR.Length).Trim(); } diff --git a/dnSpy/dnSpy/Documents/DotNetPathProvider.cs b/dnSpy/dnSpy/Documents/DotNetPathProvider.cs index 54e1ed1fb1..8f5288c0fe 100644 --- a/dnSpy/dnSpy/Documents/DotNetPathProvider.cs +++ b/dnSpy/dnSpy/Documents/DotNetPathProvider.cs @@ -82,17 +82,17 @@ public DotNetPathProvider() { info = TryGetDotNetPathsCore(version.Major, version.Minor, bitness) ?? TryGetDotNetPathsCore(version.Major, version.Minor, bitness2); - if (!(info is null)) + if (info is not null) return info.Paths; info = TryGetDotNetPathsCore(version.Major, bitness) ?? TryGetDotNetPathsCore(version.Major, bitness2); - if (!(info is null)) + if (info is not null) return info.Paths; info = TryGetDotNetPathsCore(bitness) ?? TryGetDotNetPathsCore(bitness2); - if (!(info is null)) + if (info is not null) return info.Paths; return null; @@ -247,7 +247,7 @@ static IEnumerable GetDotNetBaseDirCandidates() { static bool TryGetInstallLocationFromRegistry(string regPath, [NotNullWhen(true)] out string? installLocation) { using (var key = Registry.LocalMachine.OpenSubKey(regPath)) { installLocation = key?.GetValue("InstallLocation") as string; - return !(installLocation is null); + return installLocation is not null; } } diff --git a/dnSpy/dnSpy/Documents/DsDocumentLoader.cs b/dnSpy/dnSpy/Documents/DsDocumentLoader.cs index 2e84757c8a..adcaaf1a0a 100644 --- a/dnSpy/dnSpy/Documents/DsDocumentLoader.cs +++ b/dnSpy/dnSpy/Documents/DsDocumentLoader.cs @@ -65,7 +65,7 @@ void Load(DocumentToLoad f) { if (f.Info.Type == DocumentConstants.DOCUMENTTYPE_FILE && string.IsNullOrEmpty(f.Info.Name)) return; var document = documentService.TryGetOrCreate(f.Info, f.IsAutoLoaded); - if (!(document is null) && !hash.Contains(document)) { + if (document is not null && !hash.Contains(document)) { loadedDocuments.Add(document); hash.Add(document); if (!f.IsAutoLoaded) { @@ -76,7 +76,7 @@ void Load(DocumentToLoad f) { } public void Execute(IProgress progress) { - Debug2.Assert(!(documentsToLoad is null)); + Debug2.Assert(documentsToLoad is not null); for (int i = 0; i < documentsToLoad.Length; i++) { progress.ThrowIfCancellationRequested(); var f = documentsToLoad[i]; diff --git a/dnSpy/dnSpy/Documents/DsDocumentService.cs b/dnSpy/dnSpy/Documents/DsDocumentService.cs index d64120da07..52d83277f7 100644 --- a/dnSpy/dnSpy/Documents/DsDocumentService.cs +++ b/dnSpy/dnSpy/Documents/DsDocumentService.cs @@ -102,7 +102,7 @@ public DsDocumentService(IDsDocumentServiceSettings documentServiceSettings, [Im } void CallCollectionChanged(NotifyDocumentCollectionChangedEventArgs eventArgs, bool delayLoad = true) { - if (delayLoad && !(dispatcher is null)) + if (delayLoad && dispatcher is not null) dispatcher(() => CallCollectionChanged2(eventArgs)); else CallCollectionChanged2(eventArgs); @@ -183,10 +183,10 @@ static AssemblyNameComparerFlags ToAssemblyNameComparerFlags(FindAssemblyOptions public IDsDocument? Resolve(IAssembly asm, ModuleDef? sourceModule) { var document = FindAssembly(asm); - if (!(document is null)) + if (document is not null) return document; var asmDef = AssemblyResolver.Resolve(asm, sourceModule); - if (!(asmDef is null)) + if (asmDef is not null) return FindAssembly(asm); return null; } @@ -202,7 +202,7 @@ static AssemblyNameComparerFlags ToAssemblyNameComparerFlags(FindAssemblyOptions finally { rwLock.ExitReadLock(); } - if (!(doc is null)) + if (doc is not null) return doc; if (checkTempCache) { @@ -218,7 +218,7 @@ static AssemblyNameComparerFlags ToAssemblyNameComparerFlags(FindAssemblyOptions } DocumentInfo Find_NoLock(IDsDocumentNameKey key) { - Debug2.Assert(!(key is null)); + Debug2.Assert(key is not null); if (key is null) return default; foreach (var info in documents) { @@ -236,7 +236,7 @@ public IDsDocument GetOrAdd(IDsDocument document) { rwLock.EnterUpgradeableReadLock(); try { var existing = Find_NoLock(document.Key).Document; - if (!(existing is null)) + if (existing is not null) result = existing; else { rwLock.EnterWriteLock(); @@ -296,7 +296,7 @@ internal IDsDocument GetOrAddCanDispose(IDsDocument document, IAssembly origAsse return AddTempCachedDocument(document); result = GetOrAdd(document); } - if (!(info.Document is null) && !(origAssemblyRef is null) && document.AssemblyDef is AssemblyDef asm) { + if (info.Document is not null && origAssemblyRef is not null && document.AssemblyDef is AssemblyDef asm) { if (!AssemblyNameComparer.CompareAll.Equals(origAssemblyRef, asm)) { rwLock.EnterWriteLock(); try { @@ -354,7 +354,7 @@ static IDsDocument DisableMMapdIO(IDsDocument document) { if (key is null) return null; var existing = Find(key); - if (!(existing is null)) + if (existing is not null) return existing; var newDocument = TryCreateDocument(info); @@ -377,7 +377,7 @@ static IDsDocument DisableMMapdIO(IDsDocument document) { foreach (var provider in documentProviders) { try { var key = provider.CreateKey(this, info); - if (!(key is null)) + if (key is not null) return key; } catch (Exception ex) { @@ -392,7 +392,7 @@ static IDsDocument DisableMMapdIO(IDsDocument document) { foreach (var provider in documentProviders) { try { var document = provider.Create(this, info); - if (!(document is null)) + if (document is not null) return document; } catch (Exception ex) { @@ -415,7 +415,7 @@ IDsDocument CreateDocumentCore(DsDocumentInfo documentInfo, byte[]? fileData, st try { IPEImage peImage; - if (!(fileData is null)) + if (fileData is not null) peImage = new PEImage(fileData, filename, isFileLayout ? ImageLayout.File : ImageLayout.Memory, verify: true); else { Debug.Assert(isFileLayout); @@ -454,7 +454,7 @@ IDsDocument CreateDocumentCore(DsDocumentInfo documentInfo, byte[]? fileData, st } public void Remove(IDsDocumentNameKey key) { - Debug2.Assert(!(key is null)); + Debug2.Assert(key is not null); if (key is null) return; @@ -466,9 +466,9 @@ public void Remove(IDsDocumentNameKey key) { finally { rwLock.ExitWriteLock(); } - Debug2.Assert(!(removedDocument is null)); + Debug2.Assert(removedDocument is not null); - if (!(removedDocument is null)) + if (removedDocument is not null) CallCollectionChanged(NotifyDocumentCollectionChangedEventArgs.CreateRemove(removedDocument, null)); } @@ -518,7 +518,7 @@ public void Remove(IEnumerable documents) { } public void SetDispatcher(Action action) { - if (!(dispatcher is null)) + if (dispatcher is not null) throw new InvalidOperationException("SetDispatcher() can only be called once"); dispatcher = action ?? throw new ArgumentNullException(nameof(action)); } diff --git a/dnSpy/dnSpy/Documents/MethodAnnotations.cs b/dnSpy/dnSpy/Documents/MethodAnnotations.cs index 8e79f3180e..fedbdbd3d2 100644 --- a/dnSpy/dnSpy/Documents/MethodAnnotations.cs +++ b/dnSpy/dnSpy/Documents/MethodAnnotations.cs @@ -65,7 +65,7 @@ static void AddTimerWait(MethodAnnotations ma) { Timer? timer = null; WeakReference weakSelf = new WeakReference(ma); timer = new Timer(a => { - Debug2.Assert(!(timer is null)); + Debug2.Assert(timer is not null); timer.Dispose(); if (weakSelf.Target is MethodAnnotations self) { self.ClearGarbageCollectedItems(); diff --git a/dnSpy/dnSpy/Documents/Tabs/AppCommandLineArgsHandler.cs b/dnSpy/dnSpy/Documents/Tabs/AppCommandLineArgsHandler.cs index 4af6732c6b..32dd1bc5ae 100644 --- a/dnSpy/dnSpy/Documents/Tabs/AppCommandLineArgsHandler.cs +++ b/dnSpy/dnSpy/Documents/Tabs/AppCommandLineArgsHandler.cs @@ -40,13 +40,13 @@ sealed class AppCommandLineArgsHandler : IAppCommandLineArgsHandler { public void OnNewArgs(IAppCommandLineArgs args) { if (!SelectMember(args)) { var mod = GetLoadedFiles(args).FirstOrDefault(); - if (!(mod is null)) + if (mod is not null) documentTabService.FollowReference((object)mod.Assembly ?? mod); else { foreach (var filename in args.Filenames) { var key = new FilenameKey(filename); var document = documentTabService.DocumentTreeView.DocumentService.GetDocuments().FirstOrDefault(a => a.Key.Equals(key)); - if (!(document is null)) { + if (document is not null) { documentTabService.FollowReference(document); break; } @@ -76,14 +76,14 @@ bool SelectMember(IAppCommandLineArgs args) { var ns = args.SelectMember.Substring(XMLDOC_NS_PREFIX.Length); var modNode = documentTabService.DocumentTreeView.FindNode(mod); var nsNode = modNode is null ? null : documentTabService.DocumentTreeView.FindNamespaceNode(modNode.Document, ns); - if (!(nsNode is null)) { + if (nsNode is not null) { documentTabService.FollowReference(nsNode); return true; } } else { var member = XmlDocKeyProvider.FindMemberByKey(mod, args.SelectMember); - if (!(member is null)) { + if (member is not null) { documentTabService.FollowReference(member); return true; } @@ -99,7 +99,7 @@ IEnumerable GetLoadedFiles(IAppCommandLineArgs args) { var document = documentTabService.DocumentTreeView.DocumentService.GetDocuments().FirstOrDefault(a => key.Equals(a.Key)); if (document?.ModuleDef is null) continue; - if (!(document.AssemblyDef is null)) { + if (document.AssemblyDef is not null) { foreach (var mod in document.AssemblyDef.Modules) yield return mod; } diff --git a/dnSpy/dnSpy/Documents/Tabs/Commands.cs b/dnSpy/dnSpy/Documents/Tabs/Commands.cs index d717a81f93..0a44fdc578 100644 --- a/dnSpy/dnSpy/Documents/Tabs/Commands.cs +++ b/dnSpy/dnSpy/Documents/Tabs/Commands.cs @@ -152,7 +152,7 @@ public override void Execute(IMenuItemContext context) { var flvm = win.SelectedItems.FirstOrDefault(); var oldSelected = documentListService.SelectedDocumentList; - if (!(flvm is null)) { + if (flvm is not null) { documentListLoader.SaveCurrentDocumentsToList(); documentListService.Add(flvm.DocumentList); documentListService.SelectedDocumentList = flvm.DocumentList; @@ -234,7 +234,7 @@ void OpenFile(string filename) { mruList.Add(document.Filename); Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { var node = documentTreeView.FindNode(document); - if (!(node is null)) + if (node is not null) documentTreeView.TreeView.SelectItems(new[] { node }); })); } @@ -294,7 +294,7 @@ sealed class ShowCodeEditorCommandLoader : IAutoLoaded { var cmds = wpfCommandService.GetCommands(ControlConstants.GUID_MAINWINDOW); cmds.Add(ShowCodeEditorRoutedCommand, (s, e) => documentTabService.ActiveTab?.TrySetFocus(), - (s, e) => e.CanExecute = !(documentTabService.ActiveTab is null), + (s, e) => e.CanExecute = documentTabService.ActiveTab is not null, ModifierKeys.Control | ModifierKeys.Alt, Key.D0, ModifierKeys.Control | ModifierKeys.Alt, Key.NumPad0, ModifierKeys.None, Key.F7); @@ -311,7 +311,7 @@ sealed class ShowCodeEditorCommand : MenuItemCommand { [ExportMenuItem(Header = "res:OpenContainingFolderCommand", Group = MenuConstants.GROUP_CTX_DOCUMENTS_OTHER, Order = 30)] sealed class OpenContainingFolderCtxMenuCommand : MenuItemBase { - public override bool IsVisible(IMenuItemContext context) => !(GetFilename(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetFilename(context) is not null; static string? GetFilename(IMenuItemContext context) { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTS_TREEVIEW_GUID)) diff --git a/dnSpy/dnSpy/Documents/Tabs/CopyTokenCommand.cs b/dnSpy/dnSpy/Documents/Tabs/CopyTokenCommand.cs index 6c1a0e1e94..6d48400f96 100644 --- a/dnSpy/dnSpy/Documents/Tabs/CopyTokenCommand.cs +++ b/dnSpy/dnSpy/Documents/Tabs/CopyTokenCommand.cs @@ -29,7 +29,7 @@ You should have received a copy of the GNU General Public License namespace dnSpy.Documents.Tabs { static class CopyTokenCommand { static void ExecuteInternal(uint? token) { - if (!(token is null)) { + if (token is not null) { try { Clipboard.SetText($"0x{token.Value:X8}"); } @@ -39,7 +39,7 @@ static void ExecuteInternal(uint? token) { [ExportMenuItem(Header = "res:CopyMDTokenCommand", Group = MenuConstants.GROUP_CTX_DOCVIEWER_TOKENS, Order = 50)] sealed class CodeCommand : MenuItemBase { - public override bool IsVisible(IMenuItemContext context) => !(GetReference(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetReference(context) is not null; public override void Execute(IMenuItemContext context) => ExecuteInternal(GetReference(context)); static uint? GetReference(IMenuItemContext context) => GetReference(context, MenuConstants.GUIDOBJ_DOCUMENTVIEWERCONTROL_GUID); @@ -62,14 +62,14 @@ sealed class CodeCommand : MenuItemBase { [ExportMenuItem(Header = "res:CopyMDTokenCommand", Group = MenuConstants.GROUP_CTX_SEARCH_TOKENS, Order = 0)] sealed class SearchCommand : MenuItemBase { - public override bool IsVisible(IMenuItemContext context) => !(GetReference(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetReference(context) is not null; public override void Execute(IMenuItemContext context) => ExecuteInternal(GetReference(context)); static uint? GetReference(IMenuItemContext context) => CodeCommand.GetReference(context, MenuConstants.GUIDOBJ_SEARCH_GUID); } [ExportMenuItem(Header = "res:CopyMDTokenCommand", Group = MenuConstants.GROUP_CTX_DOCUMENTS_TOKENS, Order = 40)] sealed class DocumentsCommand : MenuItemBase { - public override bool IsVisible(IMenuItemContext context) => !(GetReference(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetReference(context) is not null; public override void Execute(IMenuItemContext context) => ExecuteInternal(GetReference(context)); static uint? GetReference(IMenuItemContext context) => GetReference(context, MenuConstants.GUIDOBJ_DOCUMENTS_TREEVIEW_GUID); @@ -86,7 +86,7 @@ sealed class DocumentsCommand : MenuItemBase { [ExportMenuItem(Header = "res:CopyMDTokenCommand", Group = MenuConstants.GROUP_CTX_ANALYZER_TOKENS, Order = 0)] sealed class AnalyzerCommand : MenuItemBase { - public override bool IsVisible(IMenuItemContext context) => !(GetReference(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetReference(context) is not null; public override void Execute(IMenuItemContext context) => ExecuteInternal(GetReference(context)); static uint? GetReference(IMenuItemContext context) => DocumentsCommand.GetReference(context, MenuConstants.GUIDOBJ_ANALYZER_TREEVIEW_GUID); } diff --git a/dnSpy/dnSpy/Documents/Tabs/DecompilationCache.cs b/dnSpy/dnSpy/Documents/Tabs/DecompilationCache.cs index 1c28552fc1..2da3bedd74 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DecompilationCache.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DecompilationCache.cs @@ -75,7 +75,7 @@ public Item(DocumentViewerContent content, IContentType contentType) { public void Hit() { LastHitUTC = DateTime.UtcNow; - if (!(WeakContent is null)) { + if (WeakContent is not null) { Content = (DocumentViewerContent?)WeakContent.Target; WeakContent = null; } @@ -83,7 +83,7 @@ public void Hit() { public void MakeWeakReference() { var content = Interlocked.CompareExchange(ref Content, null, Content); - if (!(content is null)) + if (content is not null) WeakContent = new WeakReference(content); } } @@ -210,7 +210,7 @@ public void Clear(HashSet modules) { static bool IsInModifiedModule(IDsDocumentService documentService, HashSet modules, Item item) { var result = item.Content; - if (result is null && !(item.WeakContent is null)) + if (result is null && item.WeakContent is not null) result = (DocumentViewerContent?)item.WeakContent.Target; var refs = result?.ReferenceCollection; if (refs is null) @@ -238,13 +238,13 @@ public static bool IsInModifiedModule(IDsDocumentService documentService, HashSe asmRef = t.DefinitionAssembly; if (asmRef is null && r is IMemberRef) { var type = ((IMemberRef)r).DeclaringType; - if (!(type is null)) + if (type is not null) asmRef = type.DefinitionAssembly; } - if (!(asmRef is null) && !checkedAsmRefs.Contains(asmRef)) { + if (asmRef is not null && !checkedAsmRefs.Contains(asmRef)) { checkedAsmRefs.Add(asmRef); var asm = documentService.FindAssembly(asmRef); - if (!(asm is null) && modules.Contains(asm)) + if (asm is not null && modules.Contains(asm)) return true; } } diff --git a/dnSpy/dnSpy/Documents/Tabs/DefaultDocumentList.cs b/dnSpy/dnSpy/Documents/Tabs/DefaultDocumentList.cs index 1ec1411fad..61b78905e3 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DefaultDocumentList.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DefaultDocumentList.cs @@ -58,7 +58,7 @@ public ReferenceFileFinder(CancellationToken cancellationToken) { } public IEnumerable AllFiles => - allFiles.Where(a => a.Files.Count > 0 && !(a.Name is null)). + allFiles.Where(a => a.Files.Count > 0 && a.Name is not null). Select(a => new DefaultDocumentList(a.Name!, a.Files.Select(b => b.ToDsDocumentInfo()))). Where(a => a.Documents.Length > 0); @@ -93,23 +93,23 @@ void Find(string path) { cancellationToken.ThrowIfCancellationRequested(); var dirs = GetDirs(d1); var redistDir = dirs.FirstOrDefault(a => StringComparer.OrdinalIgnoreCase.Equals(a, Path.Combine(d1, "RedistList"))); - if (!(redistDir is null)) + if (redistDir is not null) AddRedistList(redistDir); foreach (var d2 in GetDirs(d1)) { // d2 = eg. v4.5.1, etc cancellationToken.ThrowIfCancellationRequested(); dirs = GetDirs(d2); redistDir = dirs.FirstOrDefault(a => StringComparer.OrdinalIgnoreCase.Equals(a, Path.Combine(d2, "RedistList"))); - if (!(redistDir is null)) + if (redistDir is not null) AddRedistList(redistDir); var profileDir = dirs.FirstOrDefault(a => StringComparer.OrdinalIgnoreCase.Equals(a, Path.Combine(d2, "Profile"))); - if (!(profileDir is null)) { + if (profileDir is not null) { foreach (var d3 in GetDirs(profileDir)) { // d3 = eg. Client cancellationToken.ThrowIfCancellationRequested(); dirs = GetDirs(d3); redistDir = dirs.FirstOrDefault(a => StringComparer.OrdinalIgnoreCase.Equals(a, Path.Combine(d3, "RedistList"))); - if (!(redistDir is null)) + if (redistDir is not null) AddRedistList(redistDir); } } @@ -121,19 +121,19 @@ void Find(string path) { var net35 = allFiles.FirstOrDefault(a => a.Filename.EndsWith(@"\Reference Assemblies\Microsoft\Framework\v3.5\RedistList\FrameworkList.xml", StringComparison.OrdinalIgnoreCase)); var net35C = allFiles.FirstOrDefault(a => a.Filename.EndsWith(@"\Reference Assemblies\Microsoft\Framework\.NETFramework\v3.5\Profile\Client\RedistList\FrameworkList.xml", StringComparison.OrdinalIgnoreCase)); var wpa81 = allFiles.FirstOrDefault(a => a.Filename.EndsWith(@"\Reference Assemblies\Microsoft\Framework\WindowsPhoneApp\v8.1\RedistList\FrameworkList.xml", StringComparison.OrdinalIgnoreCase)); - if (!(wpa81 is null)) + if (wpa81 is not null) wpa81.Name = "Windows Phone App 8.1"; // Another one has the identical name so add "App" to it - if (!(net30 is null) && !(net20 is null)) + if (net30 is not null && net20 is not null) net30.AddFilesFrom(net20); - if (!(net35 is null) && !(net30 is null)) + if (net35 is not null && net30 is not null) net35.AddFilesFrom(net30); - if (!(net35C is null) && !(net30 is null)) + if (net35C is not null && net30 is not null) net35C.AddFilesFrom(net30); - if (!(net20 is null)) + if (net20 is not null) net20.Name = ".NET Framework 2.0"; - if (!(net30 is null)) + if (net30 is not null) net30.Name = ".NET Framework 3.0"; - if (!(net35 is null)) + if (net35 is not null) net35.Name = ".NET Framework 3.5"; } @@ -366,7 +366,7 @@ public DefaultDocumentList[] Find() { foreach (var f in files) { cancellationToken.ThrowIfCancellationRequested(); var d = ReadDefaultFileList(f); - if (!(d is null)) + if (d is not null) xmlFiles.Add(d.Value); } } @@ -409,7 +409,7 @@ public DefaultDocumentList[] Find() { var type = (string?)sect.Attribute("type") ?? "gac"; var guidStr = (string?)sect.Attribute("guid"); Guid guid = Guid.Empty; - bool hasGuid = !(guidStr is null) && Guid.TryParse(guidStr, out guid); + bool hasGuid = guidStr is not null && Guid.TryParse(guidStr, out guid); if (type.Equals("file")) l.Add(DsDocumentInfo.CreateDocument(name2)); else if (type.Equals("refasm")) diff --git a/dnSpy/dnSpy/Documents/Tabs/Dialogs/ExportToProjectVM.cs b/dnSpy/dnSpy/Documents/Tabs/Dialogs/ExportToProjectVM.cs index 4a2f63aa4d..164da5bdc9 100644 --- a/dnSpy/dnSpy/Documents/Tabs/Dialogs/ExportToProjectVM.cs +++ b/dnSpy/dnSpy/Documents/Tabs/Dialogs/ExportToProjectVM.cs @@ -251,7 +251,7 @@ public ExportToProjectVM(IPickDirectory pickDirectory, IDecompilerService decomp decompileXaml = canDecompileBaml; createSolution = true; ProjectVersionVM.SelectedItem = ProjectVersion.VS2010; - allDecompilers = new ObservableCollection(decompilerService.AllDecompilers.Where(a => !(a.ProjectFileExtension is null)).Select(a => new DecompilerVM(a))); + allDecompilers = new ObservableCollection(decompilerService.AllDecompilers.Where(a => a.ProjectFileExtension is not null).Select(a => new DecompilerVM(a))); decompiler = allDecompilers.First(); isIndeterminate = false; ProjectGuid = new NullableGuidVM(Guid.NewGuid(), a => HasErrorUpdated()); @@ -261,7 +261,7 @@ public ExportToProjectVM(IPickDirectory pickDirectory, IDecompilerService decomp void PickDestDir() { var newDir = pickDirectory.GetDirectory(Directory); - if (!(newDir is null)) + if (newDir is not null) Directory = newDir; } diff --git a/dnSpy/dnSpy/Documents/Tabs/Dialogs/GACFileVM.cs b/dnSpy/dnSpy/Documents/Tabs/Dialogs/GACFileVM.cs index 348a9af56e..d4dd4c03c3 100644 --- a/dnSpy/dnSpy/Documents/Tabs/Dialogs/GACFileVM.cs +++ b/dnSpy/dnSpy/Documents/Tabs/Dialogs/GACFileVM.cs @@ -42,7 +42,7 @@ public string CreatedBy { get { if (createdBy is null) CalculateInfo(); - Debug2.Assert(!(createdBy is null)); + Debug2.Assert(createdBy is not null); return createdBy; } } @@ -52,7 +52,7 @@ public string FileVersion { get { if (fileVersion is null) CalculateInfo(); - Debug2.Assert(!(fileVersion is null)); + Debug2.Assert(fileVersion is not null); return fileVersion; } } diff --git a/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenDocumentListVM.cs b/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenDocumentListVM.cs index 5b06222560..d2343a39be 100644 --- a/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenDocumentListVM.cs +++ b/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenDocumentListVM.cs @@ -156,7 +156,7 @@ void Refilter() { } bool CalculateIsVisible(DocumentListVM vm, string filterText) { - Debug2.Assert(!(filterText is null) && filterText.Trim().ToUpperInvariant() == filterText); + Debug2.Assert(filterText is not null && filterText.Trim().ToUpperInvariant() == filterText); if (string.IsNullOrEmpty(filterText) && !ShowSavedLists) return true; if (ShowSavedLists && !vm.IsUserList) diff --git a/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenDocumentsHelper.cs b/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenDocumentsHelper.cs index afb55a51ba..37f27deaf3 100644 --- a/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenDocumentsHelper.cs +++ b/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenDocumentsHelper.cs @@ -32,10 +32,10 @@ internal static IDsDocument[] OpenDocuments(IDocumentTreeView documentTreeView, var documentLoader = new DsDocumentLoader(documentTreeView.DocumentService, ownerWindow, mruList); var loadedDocuments = documentLoader.Load(filenames.Select(a => new DocumentToLoad(DsDocumentInfo.CreateDocument(a)))); var document = loadedDocuments.Length == 0 ? null : loadedDocuments[loadedDocuments.Length - 1]; - if (selectDocument && !(document is null)) { + if (selectDocument && document is not null) { Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { var node = documentTreeView.FindNode(document); - if (!(node is null)) + if (node is not null) documentTreeView.TreeView.SelectItems(new[] { node }); })); } diff --git a/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenFromGACVM.cs b/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenFromGACVM.cs index 4ec8c93621..77ba1dea26 100644 --- a/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenFromGACVM.cs +++ b/dnSpy/dnSpy/Documents/Tabs/Dialogs/OpenFromGACVM.cs @@ -154,7 +154,7 @@ void Refilter() { } bool CalculateIsVisible(GACFileVM vm, string filterText) { - Debug2.Assert(!(filterText is null) && filterText.Trim().ToUpperInvariant() == filterText); + Debug2.Assert(filterText is not null && filterText.Trim().ToUpperInvariant() == filterText); if (!ShowDuplicates && vm.IsDuplicate) return false; if (string.IsNullOrEmpty(filterText)) diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/BlockStructureCollection.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/BlockStructureCollection.cs index cb356db471..d6af2f98cd 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/BlockStructureCollection.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/BlockStructureCollection.cs @@ -127,7 +127,7 @@ public void GetData(SnapshotSpan lineExtent, List list) { continue; foreach (var info in spanData.Data) { var data = CreateBlockStructureData(info, lineExtent.Snapshot); - if (!(data is null)) + if (data is not null) list.Add(data.Value); } } diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/BracePairCollection.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/BracePairCollection.cs index a680e0174f..970824e791 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/BracePairCollection.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/BracePairCollection.cs @@ -84,11 +84,11 @@ sealed class RightSorter : IComparer { public BracePairResultCollection? GetBracePairs(int position) { var left = leftSorted.Find(position); var right = rightSorted.Find(position); - if (!(left is null) && !(right is null)) + if (left is not null && right is not null) return new BracePairResultCollection(new BracePairResult(left.Value.Span, left.Value.Data), new BracePairResult(right.Value.Data, right.Value.Span)); - if (!(left is null)) + if (left is not null) return new BracePairResultCollection(new BracePairResult(left.Value.Span, left.Value.Data), null); - if (!(right is null)) + if (right is not null) return new BracePairResultCollection(new BracePairResult(right.Value.Data, right.Value.Span), null); return null; } diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/BracePairService.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/BracePairService.cs index 2b843553a7..857f2ec2cf 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/BracePairService.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/BracePairService.cs @@ -190,7 +190,7 @@ static void MoveToMatchingBrace(IDocumentViewer documentViewer, bool select) { return (pair.Left.Start, pair); if (pair.Right.Start == pos) { var pair2 = coll.GetBracePairs(pos - 1); - if (!(pair2 is null) && pair2.Value.First.Right.End == pos) + if (pair2 is not null && pair2.Value.First.Right.End == pos) return (pair2.Value.First.Left.Start, pair2.Value.First); } if (pair.Left.Start <= pos && pos <= pair.Left.End) @@ -288,7 +288,7 @@ void UpdateBraceMatching() { return res; if (res.Value.First.Right.Start == pos) { res = bracePairCollection.GetBracePairs(pos - 1); - if (!(res is null) && res.Value.First.Right.End == pos) + if (res is not null && res.Value.First.Right.End == pos) return new BracePairResultCollection(res.Value.First, null); } return null; @@ -315,25 +315,25 @@ static bool IsSamePair(BracePairResultCollection? a, BracePairResultCollection? } void RefreshTags(BracePairResultCollection? a, BracePairResultCollection? b) { - if (!(a is null)) { + if (a is not null) { RefreshTags(a.Value.First); RefreshTags(a.Value.Second); } - if (!(b is null)) { + if (b is not null) { RefreshTags(b.Value.First); RefreshTags(b.Value.Second); } } void RefreshTags(BracePairResult? a) { - if (!(a is null)) { + if (a is not null) { RefreshTags(a.Value.Left); RefreshTags(a.Value.Right); } } void RefreshTags(Span span) { - if (!(tagger is null)) { + if (tagger is not null) { var snapshot = textView.TextSnapshot; if (span.End <= snapshot.Length) tagger?.RaiseTagsChanged(new SnapshotSpan(snapshot, span)); @@ -341,7 +341,7 @@ void RefreshTags(Span span) { } void RefreshAllTags() { - if (!(tagger is null)) { + if (tagger is not null) { UpdateBracePairs(false); var snapshot = textView.TextSnapshot; tagger?.RaiseTagsChanged(new SnapshotSpan(snapshot, 0, snapshot.Length)); @@ -354,7 +354,7 @@ public void SetBracePairCollection(BracePairCollection? bracePairCollection) { } public void SetBracePairViewTagger(BracePairViewTagger tagger) { - if (!(this.tagger is null)) + if (this.tagger is not null) throw new InvalidOperationException(); this.tagger = tagger ?? throw new ArgumentNullException(nameof(tagger)); } @@ -367,7 +367,7 @@ public IEnumerable> GetTags(NormalizedSnapshotSpanCollec yield return new TagSpan(new SnapshotSpan(snapshot, currentBracePair.Value.First.Left), BracePairTag.Instance); if (currentBracePair.Value.First.Right.End <= snapshot.Length) yield return new TagSpan(new SnapshotSpan(snapshot, currentBracePair.Value.First.Right), BracePairTag.Instance); - if (!(currentBracePair.Value.Second is null)) { + if (currentBracePair.Value.Second is not null) { if (currentBracePair.Value.Second.Value.Left.End <= snapshot.Length) yield return new TagSpan(new SnapshotSpan(snapshot, currentBracePair.Value.Second.Value.Left), BracePairTag.Instance); if (currentBracePair.Value.Second.Value.Right.End <= snapshot.Length) diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/Commands.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/Commands.cs index 20a48bd0e0..362dbc1b11 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/Commands.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/Commands.cs @@ -91,7 +91,7 @@ public override bool IsVisible(IMenuItemContext context) { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTVIEWERCONTROL_GUID)) return false; var uiContext = context.Find(); - return !(uiContext is null) && !uiContext.Selection.IsEmpty; + return uiContext is not null && !uiContext.Selection.IsEmpty; } } @@ -99,15 +99,15 @@ public override bool IsVisible(IMenuItemContext context) { sealed class FindInCodeCommand : MenuItemBase { public override void Execute(IMenuItemContext context) { var elem = GetInputElement(); - if (!(elem is null)) + if (elem is not null) ApplicationCommands.Find.Execute(null, elem); } - public override bool IsEnabled(IMenuItemContext context) => !(GetInputElement() is null); + public override bool IsEnabled(IMenuItemContext context) => GetInputElement() is not null; IInputElement? GetInputElement() { var elem = Keyboard.FocusedElement; - return !(elem is null) && ApplicationCommands.Find.CanExecute(null, elem) ? elem : null; + return elem is not null && ApplicationCommands.Find.CanExecute(null, elem) ? elem : null; } } diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DecompileDocumentTabContent.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DecompileDocumentTabContent.cs index cee2eea635..02e9bb8a87 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DecompileDocumentTabContent.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DecompileDocumentTabContent.cs @@ -184,7 +184,7 @@ DecompileContext CreateDecompileContext(IShowContext ctx) { decompileContext.DecompileNodeContext = new DecompileNodeContext(decompilationContext, Decompiler, decompileContext.DocumentViewerContentFactory.Output, decompileDocumentTabContentFactory.DocumentWriterService, dispatcher); if (ctx.IsRefresh) { decompileContext.SavedRefPos = ((IDocumentViewer)ctx.UIContext).SaveReferencePosition(); - if (!(decompileContext.SavedRefPos is null)) { + if (decompileContext.SavedRefPos is not null) { ctx.OnShown = e => { if (e.Success && !e.HasMovedCaret) { e.HasMovedCaret = ((IDocumentViewer)ctx.UIContext).RestoreReferencePosition(decompileContext.SavedRefPos); @@ -209,7 +209,7 @@ void UpdateLanguage() { public override void OnShow(IShowContext ctx) { UpdateLanguage(); var decompileContext = CreateDecompileContext(ctx); - Debug2.Assert(!(decompileContext.DecompileNodeContext is null)); + Debug2.Assert(decompileContext.DecompileNodeContext is not null); decompileContext.CachedContent = decompileDocumentTabContentFactory.DecompilationCache.Lookup(decompileContext.DecompileNodeContext.Decompiler, nodes, out var contentType); decompileContext.DecompileNodeContext.ContentType = contentType; ctx.Tag = decompileContext; @@ -218,7 +218,7 @@ public override void OnShow(IShowContext ctx) { public override Task CreateContentAsync(IAsyncShowContext ctx) { var decompileContext = (DecompileContext)ctx.Tag!; decompileContext.AsyncShowContext = ctx; - Debug2.Assert(!(decompileContext.DecompileNodeContext is null)); + Debug2.Assert(decompileContext.DecompileNodeContext is not null); decompileContext.DecompileNodeContext.DecompilationContext.CancellationToken = ctx.CancellationToken; decompileDocumentTabContentFactory.DocumentTreeNodeDecompiler.Decompile(decompileContext.DecompileNodeContext, nodes); return Task.CompletedTask; @@ -228,8 +228,8 @@ public override void OnShowAsync(IShowContext ctx, IAsyncShowResult result) { var decompileContext = (DecompileContext)ctx.Tag!; var documentViewer = (IDocumentViewer)ctx.UIContext; - Debug2.Assert(!(decompileContext.DecompileNodeContext is null)); - Debug2.Assert(!(decompileContext.DocumentViewerContentFactory is null)); + Debug2.Assert(decompileContext.DecompileNodeContext is not null); + Debug2.Assert(decompileContext.DocumentViewerContentFactory is not null); var contentType = decompileContext.DecompileNodeContext.ContentType; if (contentType is null) { var contentTypeString = decompileContext.DecompileNodeContext.ContentTypeString; @@ -246,7 +246,7 @@ public override void OnShowAsync(IShowContext ctx, IAsyncShowResult result) { docViewContentFactory.Output.Write(dnSpy_Resources.DecompilationCanceled, BoxedTextColor.Error); content = docViewContentFactory.CreateContent(documentViewer, contentType); } - else if (!(result.Exception is null)) { + else if (result.Exception is not null) { var docViewContentFactory = decompileDocumentTabContentFactory.DocumentViewerContentFactoryProvider.Create(); docViewContentFactory.Output.Write(dnSpy_Resources.DecompilationException, BoxedTextColor.Error); docViewContentFactory.Output.WriteLine(); @@ -271,7 +271,7 @@ public override void OnShowAsync(IShowContext ctx, IAsyncShowResult result) { public override bool NeedAsyncWork(IShowContext ctx) { var decompileContext = (DecompileContext)ctx.Tag!; - if (!(decompileContext.CachedContent is null)) + if (decompileContext.CachedContent is not null) return false; var uiCtx = (IDocumentViewer)ctx.UIContext; diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewer.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewer.cs index a9046773f6..a37e2e94b1 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewer.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewer.cs @@ -68,11 +68,11 @@ public IEnumerable GetGuidObjects(GuidObjectsProviderArgs args) { var dvCtrl = documentViewer.documentViewerControl; var loc = dvCtrl.TextView.GetTextEditorPosition(args.OpenedFromKeyboard); - if (!(loc is null)) { + if (loc is not null) { yield return new GuidObject(MenuConstants.GUIDOBJ_TEXTEDITORPOSITION_GUID, loc); var @ref = dvCtrl.GetReferenceInfo(loc.Position); - if (!(@ref is null)) + if (@ref is not null) yield return new GuidObject(MenuConstants.GUIDOBJ_CODE_REFERENCE_GUID, @ref.Value.ToTextReference()); } } @@ -139,7 +139,7 @@ public override void OnHide() { public override object? CreateUIState() { if (isDisposed) throw new ObjectDisposedException(nameof(IDocumentViewer)); - if (!(cachedEditorPositionState is null)) + if (cachedEditorPositionState is not null) return cachedEditorPositionState; return new EditorPositionState(documentViewerControl.TextView); } @@ -228,7 +228,7 @@ public override void SerializeUIState(ISettingsSection section, object? obj) { if (section is null) throw new ArgumentNullException(nameof(section)); var state = obj as EditorPositionState; - Debug2.Assert(!(state is null)); + Debug2.Assert(state is not null); if (state is null) return; @@ -278,7 +278,7 @@ void IDocumentViewerHelper.FollowReference(TextReference textRef, bool newTab) { Debug.Assert(!isDisposed); if (isDisposed) return; - Debug2.Assert(!(DocumentTab is null)); + Debug2.Assert(DocumentTab is not null); if (DocumentTab is null) return; DocumentTab.FollowReference(textRef, newTab); diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerContentFactory.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerContentFactory.cs index fadf9ea9f5..55f96f0c32 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerContentFactory.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerContentFactory.cs @@ -103,7 +103,7 @@ public DocumentViewerCustomDataContext(IDocumentViewer documentViewer, string te public void AddCustomData(string id, object data) { if (customDataDict is null) throw new ObjectDisposedException(nameof(IDocumentViewerCustomDataContext)); - Debug2.Assert(!(resultDict is null)); + Debug2.Assert(resultDict is not null); if (id is null) throw new ArgumentNullException(nameof(id)); if (resultDict.ContainsKey(id)) diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerControl.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerControl.cs index a20fb526cf..d0c29ab758 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerControl.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerControl.cs @@ -88,12 +88,12 @@ public DocumentViewerControl(ITextBufferFactoryService textBufferFactoryService, WaitAdorner? CurrentWaitAdorner { get => __currentWaitAdorner; set { - if (!(__currentWaitAdorner is null)) { + if (__currentWaitAdorner is not null) { __currentWaitAdorner.progressBar.IsIndeterminate = false; Children.Remove(__currentWaitAdorner); } __currentWaitAdorner = value; - if (!(__currentWaitAdorner is null)) + if (__currentWaitAdorner is not null) Children.Add(__currentWaitAdorner); } } @@ -290,7 +290,7 @@ bool GoToCore(SpanData spanData, bool newTab, bool followLocalRef } var localTarget = FindDefinition(spanData); - if (!(localTarget is null)) + if (localTarget is not null) spanData = localTarget.Value; if (spanData.Data.IsDefinition) { @@ -313,7 +313,7 @@ bool GoToCore(SpanData spanData, bool newTab, bool followLocalRef } else { var localTarget = FindDefinition(spanData); - if (!(localTarget is null)) + if (localTarget is not null) spanData = localTarget.Value; int pos = -1; @@ -351,7 +351,7 @@ bool GoToCore(SpanData spanData, bool newTab, bool followLocalRef bool IsOwnerOf(SpanData refInfo) { var other = currentContent.Content.ReferenceCollection.Find(refInfo.Span.Start); - return !(other is null) && + return other is not null && other.Value.Span == refInfo.Span && other.Value.Data == refInfo.Data; } @@ -419,7 +419,7 @@ sealed class ReferencePosition { var spanData = currentContent.Content.ReferenceCollection.FindFrom(line.Start.Position).FirstOrDefault(r => r.Data.Reference is IMemberDef && r.Data.IsDefinition && !r.Data.IsLocal); if (statements.Count == 0) { - if (!(spanData.Data.Reference is null)) + if (spanData.Data.Reference is not null) return new ReferencePosition(spanData); } else if (spanData.Data.Reference is null) @@ -440,18 +440,18 @@ bool GoTo(IMethodDebugService methodDebugService, ReferencePosition referencePos if (referencePosition is null) return false; - if (!(referencePosition.MethodSourceStatement is null)) { + if (referencePosition.MethodSourceStatement is not null) { var methodSourceStatement = referencePosition.MethodSourceStatement.Value; var methodStatement = methodDebugService.FindByCodeOffset(methodSourceStatement.Method, methodSourceStatement.Statement.ILSpan.Start); - if (!(methodStatement is null)) { + if (methodStatement is not null) { MoveCaretToPosition(methodStatement.Value.Statement.TextSpan.Start, options); return true; } } - if (!(referencePosition.SpanData is null)) { + if (referencePosition.SpanData is not null) { var spanData = FindReferenceInfo(referencePosition.SpanData.Value); - if (!(spanData is null)) + if (spanData is not null) return GoToTarget(spanData, false, false, options); } @@ -470,7 +470,7 @@ public void MoveReference(bool forward) { // Check these references first because if the caret is at a Get declaration (VB), then there's // no code references to it, but there's a 'Get' and 'End Get' in these refs that should be used. var spanRefData = SpanDataCollectionUtilities.GetCurrentSpanReference(spanReferenceCollection, TextView); - if (!(spanRefData?.Data.Reference is null)) { + if (spanRefData?.Data.Reference is not null) { foreach (var newSpanData in GetReferenceInfosFrom(spanReferenceCollection, spanRefData.Value.Span.Start, forward)) { if (object.Equals(newSpanData.Data.Reference, spanRefData.Value.Data.Reference)) { MoveCaretToSpan(newSpanData.Span, MoveCaretOptions.Focus | MoveCaretOptions.Select); @@ -481,7 +481,7 @@ public void MoveReference(bool forward) { } var spanData = GetCurrentReferenceInfo(); - if (!(spanData is null) && !spanData.Value.Data.IsHidden && !spanData.Value.Data.NoFollow) { + if (spanData is not null && !spanData.Value.Data.IsHidden && !spanData.Value.Data.NoFollow) { foreach (var newSpanData in GetReferenceInfosFrom(spanData.Value.Span.Start, forward)) { if (!newSpanData.Data.IsHidden && !newSpanData.Data.NoFollow && SpanDataReferenceInfoExtensions.CompareReferences(newSpanData.Data, spanData.Value.Data)) { MoveCaretToSpan(newSpanData.Span, MoveCaretOptions.Focus | MoveCaretOptions.Select); @@ -512,7 +512,7 @@ public void MoveCaretToSpan(Span span, MoveCaretOptions options) { bool isReversed = false; // If there's another reference at the caret, move caret to Start instead of End var nextRef = GetReferenceInfo(span.End); - if (!(nextRef is null) && nextRef.Value.Span != span) { + if (nextRef is not null && nextRef.Value.Span != span) { wpfTextViewHost.TextView.Caret.MoveTo(new SnapshotPoint(snapshot, span.Start)); isReversed = true; } diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerHighlightReferencesTagger.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerHighlightReferencesTagger.cs index 7bb6f65b74..3d42add7cf 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerHighlightReferencesTagger.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerHighlightReferencesTagger.cs @@ -59,7 +59,7 @@ sealed class HighlightReferencesDocumentViewerListener : IDocumentViewerListener this.documentViewerReferenceEnablerProviders = new Dictionary>(documentViewerReferenceEnablerProviders.Length, StringComparer.Ordinal); foreach (var lazy in documentViewerReferenceEnablerProviders) { string id = lazy.Metadata.Id; - Debug2.Assert(!(id is null)); + Debug2.Assert(id is not null); if (id is null) continue; bool b = this.documentViewerReferenceEnablerProviders.ContainsKey(id); @@ -137,7 +137,7 @@ public static void OnDocumentViewerCreated(IDocumentViewer documentViewer, Dicti } void SetDocumentViewer(IDocumentViewer documentViewer, Dictionary> documentViewerReferenceEnablerProviders) { - if (!(this.documentViewer is null)) + if (this.documentViewer is not null) throw new InvalidOperationException(); this.documentViewer = documentViewer ?? throw new ArgumentNullException(nameof(documentViewer)); this.documentViewerReferenceEnablerProviders = documentViewerReferenceEnablerProviders ?? throw new ArgumentNullException(nameof(documentViewerReferenceEnablerProviders)); @@ -173,9 +173,9 @@ void DocumentViewer_GotNewContent(object? sender, DocumentViewerGotNewContentEve } bool IsEnabled(string? id) { - Debug2.Assert(!(documentViewerReferenceEnablers is null)); - Debug2.Assert(!(documentViewerReferenceEnablerProviders is null)); - Debug2.Assert(!(documentViewer is null)); + Debug2.Assert(documentViewerReferenceEnablers is not null); + Debug2.Assert(documentViewerReferenceEnablerProviders is not null); + Debug2.Assert(documentViewer is not null); // A null id is always enabled if (id is null) @@ -185,9 +185,9 @@ bool IsEnabled(string? id) { bool b = documentViewerReferenceEnablerProviders.TryGetValue(id, out var lazy); Debug.Assert(b, $"Missing {nameof(IDocumentViewerReferenceEnablerProvider)} for reference id = {id}"); if (b) { - Debug2.Assert(!(lazy is null)); + Debug2.Assert(lazy is not null); refChecker = lazy.Value.Create(documentViewer); - if (!(refChecker is null)) + if (refChecker is not null) refChecker.IsEnabledChanged += DocumentViewerReferenceEnabler_IsEnabledChanged; } else @@ -209,13 +209,13 @@ public IEnumerable> GetTags(NormalizedSnapshotSpanColle yield break; if (documentViewer.TextView.IsClosed) yield break; - Debug2.Assert(!(documentViewerReferenceEnablerProviders is null)); - Debug2.Assert(!(documentViewerReferenceEnablers is null)); + Debug2.Assert(documentViewerReferenceEnablerProviders is not null); + Debug2.Assert(documentViewerReferenceEnablers is not null); // It's not common for both references to be non-null but it does happen if it's VB and the reference // is at eg. a Get keyword. For that reason, check for span refs first or we won't see the definition // highlight because it's hidden behind another span reference. - if (!(currentSpanReference is null)) { + if (currentSpanReference is not null) { if (spans.Count == 0) yield break; var snapshot = spans[0].Snapshot; @@ -235,7 +235,7 @@ public IEnumerable> GetTags(NormalizedSnapshotSpanColle } } - if (!(currentReference is null)) { + if (currentReference is not null) { if (spans.Count == 0) yield break; var snapshot = spans[0].Snapshot; @@ -281,13 +281,13 @@ void Caret_PositionChanged(object? sender, CaretPositionChangedEventArgs e) { bool refresh = false; var newRef = GetCurrentReference(); - if (!(newRef is null)) { + if (newRef is not null) { if (!IsSameReference(newRef, currentReference)) refresh = true; } var newSpanRef = GetCurrentSpanReference(); - if (!(newSpanRef is null)) { + if (newSpanRef is not null) { if (!IsSameReference(newSpanRef, currentSpanReference)) refresh = true; } @@ -308,7 +308,7 @@ void RefreshAllTags() { } void TextView_Closed(object? sender, EventArgs e) { - if (!(documentViewerReferenceEnablers is null)) { + if (documentViewerReferenceEnablers is not null) { foreach (var v in documentViewerReferenceEnablers.Values) { if (v is null) continue; @@ -324,7 +324,7 @@ void TextView_Closed(object? sender, EventArgs e) { textView.Closed -= TextView_Closed; textView.Options.OptionChanged -= Options_OptionChanged; textView.Caret.PositionChanged -= Caret_PositionChanged; - if (!(documentViewer is null)) + if (documentViewer is not null) documentViewer.GotNewContent -= DocumentViewer_GotNewContent; } } diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerMouseProcessor.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerMouseProcessor.cs index 45f20911f6..259a040a2b 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerMouseProcessor.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerMouseProcessor.cs @@ -64,7 +64,7 @@ readonly struct MouseReferenceInfo { readonly int position; readonly int versionNumber; - public bool IsClickable => !(SpanData is null) || (!(RealSpanData is null) && Keyboard.Modifiers == ModifierKeys.Control); + public bool IsClickable => SpanData is not null || (RealSpanData is not null && Keyboard.Modifiers == ModifierKeys.Control); public MouseReferenceInfo(SpanData? spanData, SpanData? realSpanData, VirtualSnapshotPoint point) { SpanData = spanData; @@ -83,7 +83,7 @@ public bool IsSamePoint(MouseReferenceInfo other) => public override void PostprocessMouseLeftButtonDown(MouseButtonEventArgs e) { RestoreState(); clickedRef = GetReferenceCore(e); - if (!(clickedRef is null)) + if (clickedRef is not null) UpdateCursor(clickedRef.Value.IsClickable); } @@ -95,7 +95,7 @@ void UpdateCursor(bool canClick) { } void RestoreState() { - if (!(oldCursor is null)) + if (oldCursor is not null) wpfTextView.VisualElement.Cursor = oldCursor; clickedRef = null; oldCursor = null; @@ -117,7 +117,7 @@ public override void PostprocessMouseLeftButtonUp(MouseButtonEventArgs e) { var newRef = GetReferenceCore(e); if (!CanClick(e, newRef)) return; - Debug2.Assert(!(newRef is null)); + Debug2.Assert(newRef is not null); var documentViewer = TryGetDocumentViewer(); if (documentViewer is null) return; diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerOutput.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerOutput.cs index d0b207aef6..1070716732 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerOutput.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerOutput.cs @@ -120,7 +120,7 @@ internal Dictionary GetCustomDataDictionary() { internal DocumentViewerContent CreateContent(Dictionary dataDict) { VerifyState(State.CustomDataProviders); state = State.ContentCreated; - Debug2.Assert(!(cachedText is null)); + Debug2.Assert(cachedText is not null); Debug.Assert(cachedText == stringBuilder.ToString()); return new DocumentViewerContent(cachedText, cachedTextColorsCollection, referenceBuilder.Create(), dataDict); } diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerUIElementService.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerUIElementService.cs index e656ccb3f7..f55f348734 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerUIElementService.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentViewerUIElementService.cs @@ -182,7 +182,7 @@ public void SetData(DocumentViewerUIElementCollection? collection) { } public void RegisterTagger(IDocumentViewerUIElementTagger tagger) { - if (!(this.tagger is null)) + if (this.tagger is not null) throw new InvalidOperationException(); this.tagger = tagger ?? throw new ArgumentNullException(nameof(tagger)); } @@ -207,7 +207,7 @@ public IEnumerable> GetTags(NormalizedSnapshotSp if (!cachedUIElements.TryGetValue(index, out var uiElem)) { uiElem = info.CreateElement(); cachedUIElements.Add(index, uiElem); - Debug2.Assert(!(uiElem is null)); + Debug2.Assert(uiElem is not null); uiElem?.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); } if (uiElem is null) diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentWriterService.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentWriterService.cs index 648e4da823..2e2b482729 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentWriterService.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/DocumentWriterService.cs @@ -53,7 +53,7 @@ public void Write(IDecompilerOutput output, string text, string contentType) { throw new ArgumentException($"Invalid content type: {contentType}"); var writer = GetDocumentWriter(ct); - if (!(writer is null)) + if (writer is not null) writer.Write(output, text); else output.Write(text, BoxedTextColor.Text); @@ -64,7 +64,7 @@ public void Write(IDecompilerOutput output, string text, string contentType) { if (!contentType.IsOfAnyType(lz.Metadata.ContentTypes)) continue; var writer = lz.Value.Create(contentType); - if (!(writer is null)) + if (writer is not null) return writer; } return null; diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/LazyBlockStructureCollection.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/LazyBlockStructureCollection.cs index b681727e29..20e0fdbc27 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/LazyBlockStructureCollection.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/LazyBlockStructureCollection.cs @@ -28,7 +28,7 @@ sealed class LazyBlockStructureCollection { public BlockStructureCollection Collection { get { if (coll is null) { - Debug2.Assert(!(ranges is null)); + Debug2.Assert(ranges is not null); coll = new BlockStructureCollection(ranges); ranges = null; } diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/SpanDataReferenceInfoExtensions.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/SpanDataReferenceInfoExtensions.cs index 86a6ef2c62..233df8cb06 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/SpanDataReferenceInfoExtensions.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/SpanDataReferenceInfoExtensions.cs @@ -31,14 +31,14 @@ public static bool CompareReferences(ReferenceInfo refInfoA, ReferenceInfo refIn var mra = refInfoA.Reference as IMemberRef; var mrb = refInfoB.Reference as IMemberRef; - if (!(mra is null) && !(mrb is null)) { + if (mra is not null && mrb is not null) { // PERF: Prevent expensive resolves by doing a quick name check if (mra.Name != mrb.Name) return false; var dta = mra.DeclaringType; var dtb = mrb.DeclaringType; - if (!(dta is null)) { + if (dta is not null) { if (dtb is null) return false; if (dta.Name != dtb.Name) @@ -47,7 +47,7 @@ public static bool CompareReferences(ReferenceInfo refInfoA, ReferenceInfo refIn return false; } else { - if (!(dtb is null)) + if (dtb is not null) return false; } diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/CodeToolTipProvider.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/CodeToolTipProvider.cs index 11546351ae..1a8f0e96ee 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/CodeToolTipProvider.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/CodeToolTipProvider.cs @@ -68,7 +68,7 @@ public object Create() { if (!output.IsEmpty) res.Children.Add(output.Create()); } - if (!(Image is null)) { + if (Image is not null) { var img = new DsImage { ImageReference = Image.Value, Margin = new Thickness(0, 0, 4, 0), diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/CodeToolTipWriter.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/CodeToolTipWriter.cs index dec5195d8d..eee9edf11f 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/CodeToolTipWriter.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/CodeToolTipWriter.cs @@ -153,15 +153,15 @@ static void WriteXmlDocParameter(IXmlDocOutput output, XElement xml) { switch (xelem.Name.ToString().ToUpperInvariant()) { case "SEE": var cref = (string?)xelem.Attribute("cref"); - if (!(cref is null)) + if (cref is not null) output.Write(XmlDocRenderer.GetCref(cref), BoxedTextColor.Text); var langword = (string?)xelem.Attribute("langword"); - if (!(langword is null)) + if (langword is not null) output.Write(langword.Trim(), BoxedTextColor.Keyword); break; case "PARAMREF": var nameAttr = (string?)xml.Attribute("name"); - if (!(nameAttr is null)) + if (nameAttr is not null) output.Write(nameAttr.Trim(), BoxedTextColor.Parameter); break; case "BR": diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/DnlibReferenceDocumentViewerToolTipProvider.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/DnlibReferenceDocumentViewerToolTipProvider.cs index 3ca0bc4aec..07c569d711 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/DnlibReferenceDocumentViewerToolTipProvider.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/DnlibReferenceDocumentViewerToolTipProvider.cs @@ -56,7 +56,7 @@ sealed class DnlibReferenceDocumentViewerToolTipProvider : IDocumentViewerToolTi string? GetDocumentation(XmlDocumentationProvider docProvider, IMemberRef mr) { var sb = new StringBuilder(); var doc = docProvider.GetDocumentation(XmlDocKeyProvider.GetKey(mr, sb)); - if (!(doc is null)) + if (doc is not null) return doc; var method = mr as IMethod; if (method is null) @@ -106,12 +106,12 @@ object Create(IDocumentViewerToolTipProviderContext context, GenericParam gp) { provider.CreateNewOutput(); try { var docProvider = XmlDocLoader.LoadDocumentation(gp.Module); - if (!(docProvider is null)) { + if (docProvider is not null) { if (!provider.Output.WriteXmlDocGeneric(GetDocumentation(docProvider, gp.Owner), gp.Name) && gp.Owner is TypeDef) { // If there's no doc available, use the parent class' documentation if this // is a generic type parameter (and not a generic method parameter). var owner = ((TypeDef)gp.Owner).DeclaringType; - while (!(owner is null)) { + while (owner is not null) { if (provider.Output.WriteXmlDocGeneric(GetDocumentation(docProvider, owner), gp.Name)) break; owner = owner.DeclaringType; @@ -142,7 +142,7 @@ object Create(IDocumentViewerToolTipProviderContext context, IMemberRef @ref) { try { if (resolvedRef is IMemberDef) { var docProvider = XmlDocLoader.LoadDocumentation(resolvedRef.Module); - if (!(docProvider is null)) + if (docProvider is not null) provider.Output.WriteXmlDoc(GetDocumentation(docProvider, resolvedRef)); } } @@ -169,10 +169,10 @@ object Create(IDocumentViewerToolTipProviderContext context, SourceParameter par var method = parameter.Parameter.Method; try { var docProvider = XmlDocLoader.LoadDocumentation(method.Module); - if (!(docProvider is null)) { + if (docProvider is not null) { if (!provider.Output.WriteXmlDocParameter(GetDocumentation(docProvider, method), parameter.Name)) { var owner = method.DeclaringType; - while (!(owner is null)) { + while (owner is not null) { if (provider.Output.WriteXmlDocParameter(GetDocumentation(docProvider, owner), parameter.Name)) break; owner = owner.DeclaringType; @@ -196,7 +196,7 @@ object Create(IDocumentViewerToolTipProviderContext context, OpCode opCode) { provider.Output.Write(BoxedTextColor.Punctuation, "("); provider.Output.Write(BoxedTextColor.Number, opCodeHex); provider.Output.Write(BoxedTextColor.Punctuation, ")"); - if (!(s is null)) { + if (s is not null) { provider.Output.Write(BoxedTextColor.Text, " - "); provider.Output.Write(BoxedTextColor.Text, s); } diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/DocumentViewerToolTipService.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/DocumentViewerToolTipService.cs index 428e2d7336..df420f92c0 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/DocumentViewerToolTipService.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/ToolTips/DocumentViewerToolTipService.cs @@ -68,7 +68,7 @@ public DocumentViewerToolTipServiceCommandTargetFilter(DocumentViewerToolTipServ DocumentViewerToolTipService? TryGetInstance() { if (__documentViewerToolTipService is null) { var docViewer = textView.TextBuffer.TryGetDocumentViewer(); - if (!(docViewer is null)) + if (docViewer is not null) __documentViewerToolTipService = documentViewerToolTipServiceProvider.GetService(docViewer); } return __documentViewerToolTipService; @@ -249,7 +249,7 @@ public bool TryTriggerQuickInfo() { var ctx = new ToolTipProviderContext(dotNetImageService, decompiler, codeToolTipSettings, documentViewer, classificationFormatMap, themeClassificationTypeService, classificationTypeRegistryService); foreach (var provider in documentViewerToolTipProviders) { var toolTipContent = provider.Value.Create(ctx, @ref); - if (!(toolTipContent is null)) + if (toolTipContent is not null) return toolTipContent; } diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/XmlParser.XamlAttributeParser.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/XmlParser.XamlAttributeParser.cs index 86ce6e1d83..9931dafbef 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/XmlParser.XamlAttributeParser.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/XmlParser.XamlAttributeParser.cs @@ -251,20 +251,20 @@ void SkipNamesAndPeriods() { void Undo(in Token token) { Debug2.Assert(cachedToken is null); - if (!(cachedToken is null)) + if (cachedToken is not null) throw new InvalidOperationException(); cachedToken = token; } Token PeekToken() { - if (!(cachedToken is null)) + if (cachedToken is not null) return cachedToken.Value; cachedToken = GetNextToken(); return cachedToken.Value; } Token GetNextToken() { - if (!(cachedToken is null)) { + if (cachedToken is not null) { var token = cachedToken.Value; cachedToken = null; return token; @@ -275,7 +275,7 @@ Token GetNextToken() { Token? cachedToken; Token ReadTokenCore() { - Debug2.Assert(!(text is null)); + Debug2.Assert(text is not null); Debug2.Assert(cachedToken is null); SkipWhitespace(); @@ -325,14 +325,14 @@ void SkipWhitespace() { } int NextChar() { - Debug2.Assert(!(text is null)); + Debug2.Assert(text is not null); if (textPosition >= textEnd) return -1; return text[textPosition++]; } int PeekChar() { - Debug2.Assert(!(text is null)); + Debug2.Assert(text is not null); if (textPosition >= textEnd) return -1; return text[textPosition]; diff --git a/dnSpy/dnSpy/Documents/Tabs/DocViewer/XmlParser.cs b/dnSpy/dnSpy/Documents/Tabs/DocViewer/XmlParser.cs index 2716c58d8f..2c09c66597 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocViewer/XmlParser.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocViewer/XmlParser.cs @@ -147,7 +147,7 @@ public XmlNameTextViewerReference(XmlNamespaceReference nsRef, string name, XmlN public override bool Equals(object? obj) { var other = obj as XmlNameTextViewerReference; - return !(other is null) && nsRef.Equals(other.nsRef) && name == other.name && refKind == other.refKind; + return other is not null && nsRef.Equals(other.nsRef) && name == other.name && refKind == other.refKind; } public override int GetHashCode() => nsRef.GetHashCode() ^ name.GetHashCode() ^ (int)refKind; @@ -158,7 +158,7 @@ sealed class XmlNamespaceTextViewerReference { public XmlNamespaceTextViewerReference(XmlNamespaceReference nsRef) => XmlNamespaceReference = nsRef ?? throw new ArgumentNullException(nameof(nsRef)); public override bool Equals(object? obj) { var other = obj as XmlNamespaceTextViewerReference; - return !(other is null) && XmlNamespaceReference.Equals(other.XmlNamespaceReference); + return other is not null && XmlNamespaceReference.Equals(other.XmlNamespaceReference); } public override int GetHashCode() => XmlNamespaceReference.GetHashCode(); } @@ -435,7 +435,7 @@ public void Initialize(XmlNamespaces? previous) => public XmlNamespaceDefinition GetOrCreate(string xmlNsAlias) { XmlNamespaces? curr = this; XmlNamespaceDefinition? def; - while (!(curr is null)) { + while (curr is not null) { if (curr.namespaces.TryGetValue(xmlNsAlias, out def)) return def; curr = curr.previous; @@ -462,7 +462,7 @@ public XmlNamespaceDefinition(string alias, string name) { } public override bool Equals(object? obj) { var other = obj as XmlNamespaceDefinition; - return !(other is null) && Name == other.Name; + return other is not null && Name == other.Name; } public override int GetHashCode() => Name.GetHashCode(); } @@ -478,7 +478,7 @@ sealed class XmlNamespaceReference : IEquatable { XmlNamespaceReference GetAttributeNamespaceReference(Span aliasSpan) { var nsRef = TryGetAttributeNamespaceReference(aliasSpan); - if (!(nsRef is null)) + if (nsRef is not null) return nsRef; var nsName = GetSubstring(aliasSpan); nsRef = new XmlNamespaceReference(nsName); @@ -549,7 +549,7 @@ void ReadAttributes() { } else { SaveReference(name, XmlNameReferenceKind.Attribute, findDefsOnly: false); - if (!(xamlAttributeParser is null)) + if (xamlAttributeParser is not null) ParseXamlString(new Span(value.Span.Start + 1, value.Span.Length - 2)); } SaveString(value); @@ -573,7 +573,7 @@ void ReadAttributes() { } void ParseXamlString(Span span) { - Debug2.Assert(!(xamlAttributeParser is null)); + Debug2.Assert(xamlAttributeParser is not null); // Absolute minimum is "{x}", but most likely it's longer if (span.Length <= 3) @@ -603,20 +603,20 @@ void ParseXamlString(Span span) { void Undo(in Token token) { Debug2.Assert(cachedToken is null); - if (!(cachedToken is null)) + if (cachedToken is not null) throw new InvalidOperationException(); cachedToken = token; } Token PeekToken() { - if (!(cachedToken is null)) + if (cachedToken is not null) return cachedToken.Value; cachedToken = GetNextToken(); return cachedToken.Value; } Token GetNextToken() { - if (!(cachedToken is null)) { + if (cachedToken is not null) { var token = cachedToken.Value; cachedToken = null; return token; diff --git a/dnSpy/dnSpy/Documents/Tabs/DocumentList.cs b/dnSpy/dnSpy/Documents/Tabs/DocumentList.cs index dfb6b98775..b17a9be3bd 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocumentList.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocumentList.cs @@ -47,7 +47,7 @@ public static DocumentList Create(ISettingsSection section) { var documentList = new DocumentList(section.Attribute(DOCUMENTLIST_NAME_ATTR)); foreach (var documentSect in section.SectionsWithName(DOCUMENT_SECTION)) { var info = DsDocumentInfoSerializer.TryLoad(documentSect); - if (!(info is null)) + if (info is not null) documentList.Documents.Add(info.Value); } return documentList; @@ -65,7 +65,7 @@ public void Update(IEnumerable documents) { if (d.IsAutoLoaded) continue; var info = d.SerializedDocument; - if (!(info is null)) + if (info is not null) Documents.Add(info.Value); } } diff --git a/dnSpy/dnSpy/Documents/Tabs/DocumentTabContentFactoryService.cs b/dnSpy/dnSpy/Documents/Tabs/DocumentTabContentFactoryService.cs index 2d40445d41..2cf337b28e 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocumentTabContentFactoryService.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocumentTabContentFactoryService.cs @@ -47,7 +47,7 @@ sealed class DocumentTabContentFactoryService : IDocumentTabContentFactoryServic var context = new DocumentTabContentFactoryContext(nodes); foreach (var factory in tabContentFactories) { var tabContent = factory.Value.Create(context); - if (!(tabContent is null)) + if (tabContent is not null) return tabContent; } return null; @@ -58,7 +58,7 @@ sealed class DocumentTabContentFactoryService : IDocumentTabContentFactoryServic var context = new DocumentTabContentFactoryContext(nodes); foreach (var factory in tabContentFactories) { var guid = factory.Value.Serialize(content, section); - if (!(guid is null)) + if (guid is not null) return guid; } return null; @@ -68,7 +68,7 @@ sealed class DocumentTabContentFactoryService : IDocumentTabContentFactoryServic var context = new DocumentTabContentFactoryContext(nodes); foreach (var factory in tabContentFactories) { var content = factory.Value.Deserialize(guid, section, context); - if (!(content is null)) + if (content is not null) return content; } return null; diff --git a/dnSpy/dnSpy/Documents/Tabs/DocumentTabSerializer.cs b/dnSpy/dnSpy/Documents/Tabs/DocumentTabSerializer.cs index d0643ee60f..2f03d329ba 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocumentTabSerializer.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocumentTabSerializer.cs @@ -37,7 +37,7 @@ sealed class DocumentTabSerializer { public IEnumerable Restore(List tgws) { var mainTgw = tgws.FirstOrDefault(a => a.Name == SerializedTabGroupWindow.MAIN_NAME); - if (!(mainTgw is null)) { + if (mainTgw is not null) { foreach (var o in Load(mainTgw)) yield return o; yield return null; diff --git a/dnSpy/dnSpy/Documents/Tabs/DocumentTabService.cs b/dnSpy/dnSpy/Documents/Tabs/DocumentTabService.cs index fb24a52f1f..52958639a6 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DocumentTabService.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DocumentTabService.cs @@ -56,7 +56,7 @@ IEnumerable AllTabContentImpls { ITabGroup SafeActiveTabGroup { get { var g = TabGroupService.ActiveTabGroup; - if (!(g is null)) + if (g is not null) return g; return TabGroupService.Create(); } @@ -68,7 +68,7 @@ TabContentImpl SafeActiveTabContentImpl { get { var g = SafeActiveTabGroup; var impl = (TabContentImpl?)g.ActiveTabContent; - if (!(impl is null)) + if (impl is not null) return impl; return CreateNewTab(g); } @@ -134,7 +134,7 @@ public IEnumerable VisibleFirstTabs { var hash = new HashSet(); foreach (var g in TabGroupService.TabGroups) { var c = (TabContentImpl?)g.ActiveTabContent; - if (!(c is null)) { + if (c is not null) { hash.Add(c); yield return c; } @@ -220,14 +220,14 @@ void CallDocumentCollectionChanged(NotifyDocumentCollectionChangedEventArgs e) { } void TabGroupService_TabGroupSelectionChanged(object? sender, TabGroupSelectedEventArgs e) { - if (!(e.Unselected is null)) { + if (e.Unselected is not null) { var impl = (TabContentImpl?)e.Unselected.ActiveTabContent; - if (!(impl is null)) + if (impl is not null) impl.OnUnselected(); } - if (!(e.Selected is null)) { + if (e.Selected is not null) { var impl = (TabContentImpl?)e.Selected.ActiveTabContent; - if (!(impl is null)) { + if (impl is not null) { impl.OnSelected(); OnNewTabContentShown(impl); } @@ -235,11 +235,11 @@ void TabGroupService_TabGroupSelectionChanged(object? sender, TabGroupSelectedEv } void TabGroupService_TabSelectionChanged(object? sender, TabSelectedEventArgs e) { - if (!(e.Unselected is null)) { + if (e.Unselected is not null) { var impl = (TabContentImpl)e.Unselected; impl.OnUnselected(); } - if (!(e.Selected is null)) { + if (e.Selected is not null) { Debug.Assert(e.TabGroup.ActiveTabContent == e.Selected); e.TabGroup.SetFocus(e.Selected); var impl = (TabContentImpl)e.Selected; @@ -255,7 +255,7 @@ void DocumentTreeView_NodeActivated(object? sender, DocumentTreeNodeActivatedEve var asm = DocumentTreeView.DocumentService.Resolve(asmRefNode.AssemblyRef, asmRefNode.GetModule()); Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { var asmNode = DocumentTreeView.FindNode(asm); - if (!(asmNode is null)) + if (asmNode is not null) DocumentTreeView.TreeView.SelectItems(new[] { asmNode }); })); return; @@ -263,14 +263,14 @@ void DocumentTreeView_NodeActivated(object? sender, DocumentTreeNodeActivatedEve if (e.Node is DerivedTypeNode derivedTypeNode) { var td = derivedTypeNode.TypeDef; - Debug2.Assert(!(td is null)); + Debug2.Assert(td is not null); SelectType(td); return; } if (e.Node is BaseTypeNode baseTypeNode) { var tdr = baseTypeNode.TypeDefOrRef; - Debug2.Assert(!(tdr is null)); + Debug2.Assert(tdr is not null); var td = tdr?.GetScopeType().ResolveTypeDef(); SelectType(td); return; @@ -306,7 +306,7 @@ void DocumentTreeView_NodeActivated(object? sender, DocumentTreeNodeActivatedEve void SelectType(TypeDef? td) { Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { var typeNode = DocumentTreeView.FindNode(td); - if (!(typeNode is null)) + if (typeNode is not null) DocumentTreeView.TreeView.SelectItems(new[] { typeNode }); })); } @@ -314,7 +314,7 @@ void SelectType(TypeDef? td) { void SelectMethod(MethodDef? md) { Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { var methodNode = DocumentTreeView.FindNode(md); - if (!(methodNode is null)) + if (methodNode is not null) DocumentTreeView.TreeView.SelectItems(new[] { methodNode }); })); } @@ -322,7 +322,7 @@ void SelectMethod(MethodDef? md) { void SelectField(FieldDef? fd) { Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { var fieldNode = DocumentTreeView.FindNode(fd); - if (!(fieldNode is null)) + if (fieldNode is not null) DocumentTreeView.TreeView.SelectItems(new[] { fieldNode }); })); } @@ -383,7 +383,7 @@ void ShowNodes(DocumentTreeNodeData[] nodes) { DocumentTabContent CreateTabContent(DocumentTreeNodeData[] nodes) { var content = TryCreateContent(nodes); - Debug2.Assert(!(content is null)); + Debug2.Assert(content is not null); return content ?? new NullDocumentTabContent(); } @@ -439,11 +439,11 @@ void OnNewTabContentShownDelay(IDocumentTab documentTab) { disableSelectionChangedEventCounter--; } - if (!(focusedElem is null) && Keyboard.FocusedElement != focusedElem) { + if (focusedElem is not null && Keyboard.FocusedElement != focusedElem) { if (tabGroupHasFocus) { var tab = ActiveTabContentImpl; - Debug2.Assert(!(tab is null)); - if (!(tab is null)) + Debug2.Assert(tab is not null); + if (tab is not null) tab.TrySetFocus(); } else @@ -504,7 +504,7 @@ internal void OnTabsLoaded() { Debug.Assert(!tabsLoaded); tabsLoaded = true; var impl = ActiveTabContentImpl; - if (!(impl is null)) { + if (impl is not null) { impl.OnTabsLoaded(); OnNewTabContentShown(impl); } @@ -570,18 +570,18 @@ HashSet GetModifiedDocuments(IDsDocument document) { documentsHash.Add(document); var node = DocumentTreeView.FindNode(document); if (node is ModuleDocumentNode) { - if (!(node.Document.AssemblyDef is null) && node.Document.AssemblyDef.ManifestModule == node.Document.ModuleDef) { + if (node.Document.AssemblyDef is not null && node.Document.AssemblyDef.ManifestModule == node.Document.ModuleDef) { var asmNode = node.GetAssemblyNode(); - Debug2.Assert(!(asmNode is null)); - if (!(asmNode is null)) + Debug2.Assert(asmNode is not null); + if (asmNode is not null) documentsHash.Add(asmNode.Document); } } else if (node is AssemblyDocumentNode) { node.TreeNode.EnsureChildrenLoaded(); var manifestModNode = node.TreeNode.DataChildren.FirstOrDefault() as ModuleDocumentNode; - Debug2.Assert(!(manifestModNode is null)); - if (!(manifestModNode is null)) + Debug2.Assert(manifestModNode is not null); + if (manifestModNode is not null) documentsHash.Add(manifestModNode.Document); } return documentsHash; @@ -608,7 +608,7 @@ bool MustRefresh(IDocumentTab tab, IEnumerable documents) { if (InModifiedModuleHelper.IsInModifiedModule(modules!, tab.Content.Nodes)) return true; var documentViewer = tab.TryGetDocumentViewer(); - if (!(documentViewer is null) && InModifiedModuleHelper.IsInModifiedModule(DocumentTreeView.DocumentService, modules!, documentViewer.Content.ReferenceCollection.Select(a => a.Data.Reference))) + if (documentViewer is not null && InModifiedModuleHelper.IsInModifiedModule(DocumentTreeView.DocumentService, modules!, documentViewer.Content.ReferenceCollection.Select(a => a.Data.Reference))) return true; return false; @@ -624,7 +624,7 @@ public void FollowReference(object @ref, bool newTab, bool setFocus, Action(object key, Func> creator) where T : class { return (T)obj; if (weakCachedInstances.TryGetValue(key, out var weakRef)) { obj = weakRef.Target; - if (!(obj is null)) + if (obj is not null) return (T)obj; } @@ -64,7 +64,7 @@ T GetOrCreate(object key, Func> creator) where T : class { ReferenceResult Create() where T : class { foreach (var c in documentTabUIContextProviders) { var t = c.Value.Create() as T; - if (!(t is null)) + if (t is not null) return new ReferenceResult(t, c.Metadata.UseStrongReference); } throw new InvalidOperationException(); @@ -86,7 +86,7 @@ sealed class Key : IEquatable { public Key(object obj) => this.obj = obj ?? throw new ArgumentNullException(nameof(obj)); - public bool Equals(Key? other) => !(other is null) && obj.Equals(other.obj); + public bool Equals(Key? other) => other is not null && obj.Equals(other.obj); public override bool Equals(object? obj) => Equals(obj as Key); public override int GetHashCode() => obj.GetHashCode(); } diff --git a/dnSpy/dnSpy/Documents/Tabs/DsDocumentInfoSerializer.cs b/dnSpy/dnSpy/Documents/Tabs/DsDocumentInfoSerializer.cs index 55a2ffa9f4..61c92fe35f 100644 --- a/dnSpy/dnSpy/Documents/Tabs/DsDocumentInfoSerializer.cs +++ b/dnSpy/dnSpy/Documents/Tabs/DsDocumentInfoSerializer.cs @@ -36,7 +36,7 @@ static class DsDocumentInfoSerializer { public static void Save(ISettingsSection section, DsDocumentInfo info) { // Assume that instances with a non-null Data property can't be serialized - if (!(info.Data is null)) + if (info.Data is not null) return; section.Attribute(DOCUMENTINFO_NAME_ATTR, info.Name); diff --git a/dnSpy/dnSpy/Documents/Tabs/EntryPointCommands.cs b/dnSpy/dnSpy/Documents/Tabs/EntryPointCommands.cs index 252a9624b4..1bf992c174 100644 --- a/dnSpy/dnSpy/Documents/Tabs/EntryPointCommands.cs +++ b/dnSpy/dnSpy/Documents/Tabs/EntryPointCommands.cs @@ -43,7 +43,7 @@ sealed class CodeCommand : MenuItemBase { [ImportingConstructor] CodeCommand(IDocumentTabService documentTabService) => this.documentTabService = documentTabService; - public override bool IsVisible(IMenuItemContext context) => !(GetEntryPoint(documentTabService, context) is null); + public override bool IsVisible(IMenuItemContext context) => GetEntryPoint(documentTabService, context) is not null; static MethodDef? GetEntryPoint(IDocumentTabService documentTabService, IMenuItemContext context) { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTVIEWERCONTROL_GUID)) @@ -54,7 +54,7 @@ sealed class CodeCommand : MenuItemBase { public override void Execute(IMenuItemContext context) { var ep = GetEntryPoint(documentTabService, context); - if (!(ep is null)) + if (ep is not null) documentTabService.FollowReference(ep); } } @@ -66,7 +66,7 @@ sealed class DocumentsCommand : MenuItemBase { [ImportingConstructor] DocumentsCommand(IDocumentTabService documentTabService) => this.documentTabService = documentTabService; - public override bool IsVisible(IMenuItemContext context) => !(GetEntryPoint(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetEntryPoint(context) is not null; static MethodDef? GetEntryPoint(IMenuItemContext context) { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTS_TREEVIEW_GUID)) @@ -79,7 +79,7 @@ sealed class DocumentsCommand : MenuItemBase { public override void Execute(IMenuItemContext context) { var ep = GetEntryPoint(context); - if (!(ep is null)) + if (ep is not null) documentTabService.FollowReference(ep); } } @@ -93,7 +93,7 @@ sealed class CodeCommand : MenuItemBase { [ImportingConstructor] CodeCommand(IDocumentTabService documentTabService) => this.documentTabService = documentTabService; - public override bool IsVisible(IMenuItemContext context) => !(GetModuleCctor(documentTabService, context) is null); + public override bool IsVisible(IMenuItemContext context) => GetModuleCctor(documentTabService, context) is not null; static MethodDef? GetModuleCctor(IDocumentTabService documentTabService, IMenuItemContext context) { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTVIEWERCONTROL_GUID)) @@ -107,7 +107,7 @@ sealed class CodeCommand : MenuItemBase { public override void Execute(IMenuItemContext context) { var ep = GetModuleCctor(documentTabService, context); - if (!(ep is null)) + if (ep is not null) documentTabService.FollowReference(ep); } } @@ -119,7 +119,7 @@ sealed class DocumentsCommand : MenuItemBase { [ImportingConstructor] DocumentsCommand(IDocumentTabService documentTabService) => this.documentTabService = documentTabService; - public override bool IsVisible(IMenuItemContext context) => !(GetModuleCctor(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetModuleCctor(context) is not null; static MethodDef? GetModuleCctor(IMenuItemContext context) { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTS_TREEVIEW_GUID)) @@ -135,7 +135,7 @@ sealed class DocumentsCommand : MenuItemBase { public override void Execute(IMenuItemContext context) { var ep = GetModuleCctor(context); - if (!(ep is null)) + if (ep is not null) documentTabService.FollowReference(ep); } } diff --git a/dnSpy/dnSpy/Documents/Tabs/GoToTokenCommand.cs b/dnSpy/dnSpy/Documents/Tabs/GoToTokenCommand.cs index 69f0d415ee..ce6012f9bc 100644 --- a/dnSpy/dnSpy/Documents/Tabs/GoToTokenCommand.cs +++ b/dnSpy/dnSpy/Documents/Tabs/GoToTokenCommand.cs @@ -63,7 +63,7 @@ static class GoToTokenCommand { return tab.Content.Nodes.FirstOrDefault().GetModule(); } - internal static bool CanExecuteInternal(IDocumentTabService documentTabService) => !(GetResolver(documentTabService, out var tab) is null); + internal static bool CanExecuteInternal(IDocumentTabService documentTabService) => GetResolver(documentTabService, out var tab) is not null; static object? ResolveDef(object mr) { if (mr is ParamDef) @@ -81,7 +81,7 @@ internal static void ExecuteInternal(IDocumentTabService documentTabService) { var resolver = GetResolver(documentTabService, out var tab); if (resolver is null) return; - Debug2.Assert(!(tab is null)); + Debug2.Assert(tab is not null); var member = AskForDef(dnSpy_Resources.GoToToken_Title, resolver); if (member is null) diff --git a/dnSpy/dnSpy/Documents/Tabs/NavigationCommands.cs b/dnSpy/dnSpy/Documents/Tabs/NavigationCommands.cs index ee02732f17..b8b710ace3 100644 --- a/dnSpy/dnSpy/Documents/Tabs/NavigationCommands.cs +++ b/dnSpy/dnSpy/Documents/Tabs/NavigationCommands.cs @@ -54,7 +54,7 @@ sealed class NavigationCommandInstaller : IAutoLoaded { [ImportingConstructor] NavigationCommandInstaller(IDocumentTabService documentTabService, IAppWindow appWindow) { this.documentTabService = documentTabService; - Debug2.Assert(!(Application.Current is null) && !(Application.Current.MainWindow is null)); + Debug2.Assert(Application.Current is not null && Application.Current.MainWindow is not null); var cmds = appWindow.MainWindowCommands; cmds.Add(NavigationCommands.BrowseBack, new RelayCommand(a => BrowseBack(), a => CanBrowseBack)); cmds.Add(NavigationCommands.BrowseForward, new RelayCommand(a => BrowseForward(), a => CanBrowseForward)); diff --git a/dnSpy/dnSpy/Documents/Tabs/NodeDecompiler.cs b/dnSpy/dnSpy/Documents/Tabs/NodeDecompiler.cs index 53774d6134..b2599e8e04 100644 --- a/dnSpy/dnSpy/Documents/Tabs/NodeDecompiler.cs +++ b/dnSpy/dnSpy/Documents/Tabs/NodeDecompiler.cs @@ -69,7 +69,7 @@ public NodeDecompiler(Func, object> execInThread, IDecompilerOutput this.decompiler = decompiler; this.decompilationContext = decompilationContext; this.decompileNodeContext = decompileNodeContext; - if (!(this.decompileNodeContext is null)) + if (this.decompileNodeContext is not null) this.decompileNodeContext.ContentTypeString = decompiler.ContentTypeString; } @@ -186,7 +186,7 @@ DocumentTreeNodeData[] GetChildren(DocumentTreeNodeData node) { } void DecompileUnknown(DocumentTreeNodeData node) { - if (node is IDecompileSelf decompileSelf && !(decompileNodeContext is null)) { + if (node is IDecompileSelf decompileSelf && decompileNodeContext is not null) { if (decompileSelf.Decompile(decompileNodeContext)) return; } @@ -218,7 +218,7 @@ void Decompile(NamespaceNode node) { void Decompile(PEDocumentNode node) { decompiler.WriteCommentLine(output, node.Document.Filename); var peImage = node.Document.PEImage; - if (!(peImage is null)) { + if (peImage is not null) { var timestampLine = dnSpy_Resources.Decompile_Timestamp + " "; uint ts = peImage.ImageNTHeaders.FileHeader.TimeDateStamp; if ((int)ts > 0) { diff --git a/dnSpy/dnSpy/Documents/Tabs/NodeReferenceDocumentTabContentProvider.cs b/dnSpy/dnSpy/Documents/Tabs/NodeReferenceDocumentTabContentProvider.cs index 8626a3932d..137245c665 100644 --- a/dnSpy/dnSpy/Documents/Tabs/NodeReferenceDocumentTabContentProvider.cs +++ b/dnSpy/dnSpy/Documents/Tabs/NodeReferenceDocumentTabContentProvider.cs @@ -56,7 +56,7 @@ sealed class NodeReferenceDocumentTabContentProvider : IReferenceDocumentTabCont return Create(mod); if (@ref is IAssembly asmRef) { var doc = documentTreeView.DocumentService.Resolve(asmRef, null); - if (!(doc is null)) + if (doc is not null) return Create(doc); } return null; diff --git a/dnSpy/dnSpy/Documents/Tabs/RefreshResourcesCommand.cs b/dnSpy/dnSpy/Documents/Tabs/RefreshResourcesCommand.cs index ddb6b7166d..20bbb6b799 100644 --- a/dnSpy/dnSpy/Documents/Tabs/RefreshResourcesCommand.cs +++ b/dnSpy/dnSpy/Documents/Tabs/RefreshResourcesCommand.cs @@ -74,7 +74,7 @@ void RefreshResources(HashSet modifiedResourceNodes) { var ownerNodes = new HashSet(); foreach (var node in modifiedResourceNodes) { var owner = node.GetAncestorOrSelf(); - if (!(owner is null)) + if (owner is not null) ownerNodes.Add(owner); } if (ownerNodes.Count == 0) @@ -82,9 +82,9 @@ void RefreshResources(HashSet modifiedResourceNodes) { decompilationCache.Clear(new HashSet(ownerNodes.Select(a => { var mod = a.GetModuleNode(); - Debug2.Assert(!(mod is null)); + Debug2.Assert(mod is not null); return mod?.Document; - }).Where(a => !(a is null)))); + }).Where(a => a is not null))); var tabs = new List(); foreach (var tab in documentTabService.VisibleFirstTabs) { diff --git a/dnSpy/dnSpy/Documents/Tabs/ResourceCommands.cs b/dnSpy/dnSpy/Documents/Tabs/ResourceCommands.cs index ff8f9e966a..c659faf8ed 100644 --- a/dnSpy/dnSpy/Documents/Tabs/ResourceCommands.cs +++ b/dnSpy/dnSpy/Documents/Tabs/ResourceCommands.cs @@ -45,7 +45,7 @@ sealed class ResourceRef { public static ResourceRef? TryCreate(object? o) { if (o is PropertyDef pd) { - if (!(pd.SetMethod is null)) + if (pd.SetMethod is not null) return null; o = pd.GetMethod; } @@ -204,28 +204,28 @@ sealed class DocumentTreeViewCommand : MenuItemBase { public override bool IsVisible(IMenuItemContext context) => GoToResourceCommand.IsVisible(TryCreate(context)); } - static bool IsVisible(ResourceRef? resRef) => !(resRef is null); + static bool IsVisible(ResourceRef? resRef) => resRef is not null; static void Execute(IDocumentTabService documentTabService, ResourceRef? resRef) { if (resRef is null) return; var modNode = documentTabService.DocumentTreeView.FindNode(resRef.Module); - Debug2.Assert(!(modNode is null)); + Debug2.Assert(modNode is not null); if (modNode is null) return; modNode.TreeNode.EnsureChildrenLoaded(); var resDirNode = modNode.TreeNode.DataChildren.FirstOrDefault(a => a is ResourcesFolderNode); - Debug2.Assert(!(resDirNode is null)); + Debug2.Assert(resDirNode is not null); if (resDirNode is null) return; resDirNode.TreeNode.EnsureChildrenLoaded(); var resSetNode = resDirNode.TreeNode.DataChildren.FirstOrDefault(a => a is ResourceElementSetNode && ((ResourceElementSetNode)a).Name == resRef.Filename); - Debug2.Assert(!(resSetNode is null)); + Debug2.Assert(resSetNode is not null); if (resSetNode is null) return; resSetNode.TreeNode.EnsureChildrenLoaded(); var resNode = resSetNode.TreeNode.DataChildren.FirstOrDefault(a => ResourceElementNode.GetResourceElement((DocumentTreeNodeData)a) is ResourceElement resourceElement && resourceElement.Name == resRef.ResourceName); - Debug2.Assert(!(resNode is null)); + Debug2.Assert(resNode is not null); if (resNode is null) return; documentTabService.FollowReference(resNode); diff --git a/dnSpy/dnSpy/Documents/Tabs/SaveCommands.cs b/dnSpy/dnSpy/Documents/Tabs/SaveCommands.cs index 0b4991fe08..51ab55e02d 100644 --- a/dnSpy/dnSpy/Documents/Tabs/SaveCommands.cs +++ b/dnSpy/dnSpy/Documents/Tabs/SaveCommands.cs @@ -73,7 +73,7 @@ sealed class ExportProjectCommand : MenuItemBase { } public override bool IsEnabled(IMenuItemContext context) => - GetModules().Length > 0 && decompilerService.AllDecompilers.Any(a => !(a.ProjectFileExtension is null)); + GetModules().Length > 0 && decompilerService.AllDecompilers.Any(a => a.ProjectFileExtension is not null); public override void Execute(IMenuItemContext context) { var modules = GetModules(); @@ -82,14 +82,14 @@ public override void Execute(IMenuItemContext context) { var decompiler = decompilerService.Decompiler; if (decompiler.ProjectFileExtension is null) { - decompiler = decompilerService.AllDecompilers.FirstOrDefault(a => !(a.ProjectFileExtension is null)); - Debug2.Assert(!(decompiler is null)); + decompiler = decompilerService.AllDecompilers.FirstOrDefault(a => a.ProjectFileExtension is not null); + Debug2.Assert(decompiler is not null); if (decompiler is null) return; } var task = new ExportTask(this, modules); - var vm = new ExportToProjectVM(new PickDirectory(), decompilerService, task, !(bamlDecompiler is null)); + var vm = new ExportToProjectVM(new PickDirectory(), decompilerService, task, bamlDecompiler is not null); task.vm = vm; vm.ProjectVersion = exportToProjectSettings.ProjectVersion; vm.CreateResX = documentTreeViewSettings.DeserializeResources; @@ -129,7 +129,7 @@ public ExportTask(ExportProjectCommand owner, ModuleDef[] modules) { cancellationTokenSource = new CancellationTokenSource(); cancellationToken = cancellationTokenSource.Token; dispatcher = Dispatcher.CurrentDispatcher; - if (!(owner.bamlDecompiler is null)) { + if (owner.bamlDecompiler is not null) { bamlDecompiler = owner.bamlDecompiler.Value; xamlOutputOptionsProvider = owner.xamlOutputOptionsProvider?.Value; } @@ -161,7 +161,7 @@ public void Execute(ExportToProjectVM vm) { GetDisableAssemblyLoad = () => owner.documentTreeView.DocumentService.DisableAssemblyLoad(), AsyncMethodBodyDecompilation = false, }; - Debug2.Assert(!(vm.Directory is null)); + Debug2.Assert(vm.Directory is not null); var options = new ProjectCreatorOptions(vm.Directory, cancellationToken); options.ProjectVersion = vm.ProjectVersion; if (vm.CreateSolution) @@ -169,7 +169,7 @@ public void Execute(ExportToProjectVM vm) { options.Logger = this; options.ProgressListener = this; - bool hasProjectGuid = !(vm.ProjectGuid.Value is null); + bool hasProjectGuid = vm.ProjectGuid.Value is not null; string? guidFormat = null; int guidNum = 0; if (hasProjectGuid) { @@ -185,7 +185,7 @@ public void Execute(ExportToProjectVM vm) { DecompileXaml = vm.DecompileXaml, ProjectGuid = hasProjectGuid ? new Guid(string.Format(guidFormat!, guidNum++)) : Guid.NewGuid(), }; - if (!(bamlDecompiler is null)) { + if (bamlDecompiler is not null) { var o = BamlDecompilerOptions.Create(vm.Decompiler.Decompiler); var outputOptions = xamlOutputOptionsProvider?.Default ?? new XamlOutputOptions(); projOpts.DecompileBaml = (a, b, c, d) => bamlDecompiler.Decompile(a, b, c, o, d, outputOptions); @@ -203,7 +203,7 @@ public void Execute(ExportToProjectVM vm) { .ContinueWith(t => { DnSpyEventSource.Log.ExportToProjectStop(); var ex = t.Exception; - if (!(ex is null)) + if (ex is not null) Error(string.Format(dnSpy_Resources.ErrorExceptionOccurred, ex)); EmtpyErrorList(); vm.OnExportComplete(); @@ -268,8 +268,8 @@ void IMSBuildProgressListener.SetProgress(int progress) { newValue = newProgress; newProgress = null; } - Debug2.Assert(!(newValue is null)); - if (!(newValue is null)) + Debug2.Assert(newValue is not null); + if (newValue is not null) vm.TotalProgress = newValue.Value; })); } @@ -286,7 +286,7 @@ static string CreateFilesToExportMessage(ModuleDef[] modules) { static string? GetSolutionFilename(IEnumerable modules) { foreach (var e in modules.OrderBy(a => (a.Characteristics & Characteristics.Dll) == 0 ? 0 : 1)) { - var name = e.IsManifestModule && !(e.Assembly is null) ? GetSolutionName(e.Assembly.Name) : GetSolutionName(e.Name); + var name = e.IsManifestModule && e.Assembly is not null ? GetSolutionName(e.Assembly.Name) : GetSolutionName(e.Name); if (!string.IsNullOrWhiteSpace(name)) return name; } @@ -308,7 +308,7 @@ ModuleDef[] GetModules() { var hashSet = new HashSet(); foreach (var n in documentTreeView.TreeView.TopLevelSelection) { var asmNode = n.GetAssemblyNode(); - if (!(asmNode is null)) { + if (asmNode is not null) { asmNode.TreeNode.EnsureChildrenLoaded(); foreach (var c in asmNode.TreeNode.DataChildren.OfType()) hashSet.Add(c.Document.ModuleDef); @@ -316,7 +316,7 @@ ModuleDef[] GetModules() { } var modNode = n.GetModuleNode(); - if (!(modNode is null)) + if (modNode is not null) hashSet.Add(modNode.Document.ModuleDef); } hashSet.Remove(null); @@ -351,14 +351,14 @@ sealed class SaveTabCtxMenuCommand : MenuItemCommand { this.documentTabService = documentTabService; } - public override bool IsVisible(IMenuItemContext context) => !(GetTabGroup(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetTabGroup(context) is not null; public override string? GetHeader(IMenuItemContext context) => saveService.GetMenuHeader(GetDocumentTab(context)); ITabGroup? GetTabGroup(IMenuItemContext context) { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_DOCUMENTS_TABCONTROL_GUID)) return null; var g = context.Find(); - return !(g is null) && documentTabService.Owns(g) ? g : null; + return g is not null && documentTabService.Owns(g) ? g : null; } IDocumentTab? GetDocumentTab(IMenuItemContext context) { diff --git a/dnSpy/dnSpy/Documents/Tabs/SaveService.cs b/dnSpy/dnSpy/Documents/Tabs/SaveService.cs index fb0845590f..42cd0c72ac 100644 --- a/dnSpy/dnSpy/Documents/Tabs/SaveService.cs +++ b/dnSpy/dnSpy/Documents/Tabs/SaveService.cs @@ -37,7 +37,7 @@ sealed class SaveService : ISaveService { return null; foreach (var provider in tabSaverProviders) { var ts = provider.Create(tab); - if (!(ts is null)) + if (ts is not null) return ts; } return null; @@ -45,7 +45,7 @@ sealed class SaveService : ISaveService { public bool CanSave(IDocumentTab? tab) { var ts = GetTabSaver(tab); - return !(ts is null) && ts.CanSave; + return ts is not null && ts.CanSave; } public string GetMenuHeader(IDocumentTab? tab) { diff --git a/dnSpy/dnSpy/Documents/Tabs/SearchMsdnCommand.cs b/dnSpy/dnSpy/Documents/Tabs/SearchMsdnCommand.cs index 3943fbcc5b..44b6c9cb1b 100644 --- a/dnSpy/dnSpy/Documents/Tabs/SearchMsdnCommand.cs +++ b/dnSpy/dnSpy/Documents/Tabs/SearchMsdnCommand.cs @@ -33,7 +33,7 @@ static class SearchMsdnCtxMenuCommand { [ExportMenuItem(Header = "res:SearchMsdnCommand", Icon = DsImagesAttribute.Search, Group = MenuConstants.GROUP_CTX_DOCVIEWER_OTHER, Order = 10)] sealed class CodeCommand : MenuItemBase { - public override bool IsVisible(IMenuItemContext context) => !(GetMemberRef(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetMemberRef(context) is not null; static IMemberRef? GetMemberRef(IMenuItemContext context) => GetMemberRef(context, MenuConstants.GUIDOBJ_DOCUMENTVIEWERCONTROL_GUID); public override void Execute(IMenuItemContext context) => SearchMsdn(GetMemberRef(context)); @@ -46,7 +46,7 @@ sealed class CodeCommand : MenuItemBase { [ExportMenuItem(Header = "res:SearchMsdnCommand", Icon = DsImagesAttribute.Search, Group = MenuConstants.GROUP_CTX_SEARCH_OTHER, Order = 10)] sealed class SearchCommand : MenuItemBase { - public override bool IsVisible(IMenuItemContext context) => !(GetMemberRef(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetMemberRef(context) is not null; static IMemberRef? GetMemberRef(IMenuItemContext context) => CodeCommand.GetMemberRef(context, MenuConstants.GUIDOBJ_SEARCH_GUID); public override void Execute(IMenuItemContext context) => SearchMsdn(GetMemberRef(context)); } @@ -193,10 +193,10 @@ static bool IsAccessible(TypeDef type) { } static bool IsAccessible(MethodDef method) => - !(method is null) && (method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly); + method is not null && (method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly); static bool IsAccessible(FieldDef field) => - !(field is null) && (field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly); + field is not null && (field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly); static bool IsAccessible(PropertyDef prop) => prop.GetMethods.Any(m => IsAccessible(m)) || @@ -214,7 +214,7 @@ static string GetAddress(IMemberRef memberRef) { if (member is null) return string.Empty; - if (!(member.DeclaringType is null) && member.DeclaringType.IsEnum && member is FieldDef && ((FieldDef)member).IsLiteral) + if (member.DeclaringType is not null && member.DeclaringType.IsEnum && member is FieldDef && ((FieldDef)member).IsLiteral) member = member.DeclaringType; string memberName; @@ -241,7 +241,7 @@ static void ExecuteInternal(IEnumerable nodes) { } public static void SearchMsdn(IMemberRef? memberRef) { - if (!(memberRef is null)) + if (memberRef is not null) SearchMsdn(GetAddress(memberRef)); } diff --git a/dnSpy/dnSpy/Documents/Tabs/SerializedTabs.cs b/dnSpy/dnSpy/Documents/Tabs/SerializedTabs.cs index 89eae8784f..7521cbed03 100644 --- a/dnSpy/dnSpy/Documents/Tabs/SerializedTabs.cs +++ b/dnSpy/dnSpy/Documents/Tabs/SerializedTabs.cs @@ -72,7 +72,7 @@ public void Save(ISettingsSection section) { section.Attribute(INDEX_ATTR, Index); section.Attribute(ISHORIZONTAL_ATTR, IsHorizontal); - if (!(StackedContentState is null)) + if (StackedContentState is not null) StackedContentStateSerializer.Serialize(section.GetOrCreateSection(STACKEDCONTENTSTATE_SECTION), StackedContentState); foreach (var stg in TabGroups) @@ -100,7 +100,7 @@ public static SerializedTabGroupWindow Create(IDocumentTabContentFactoryService yield return o; } - if (!(StackedContentState is null)) + if (StackedContentState is not null) ((TabGroupService)mgr).StackedContentState = StackedContentState; var ary = mgr.TabGroups.ToArray(); @@ -128,7 +128,7 @@ public static SerializedTabGroup Load(ISettingsSection section) { foreach (var tabSection in section.SectionsWithName(TAB_SECTION)) { var tab = SerializedTab.TryLoad(tabSection); - if (!(tab is null)) + if (tab is not null) tg.Tabs.Add(tab); } @@ -148,7 +148,7 @@ public static SerializedTabGroup Create(IDocumentTabContentFactoryService docume foreach (IDocumentTab tab in g.TabContents) { var t = SerializedTab.TryCreate(documentTabContentFactoryService, tab); - if (!(t is null)) + if (t is not null) tg.Tabs.Add(t); } @@ -207,7 +207,7 @@ sealed class SerializedTab { var autoLoadedDocuments = new List(); foreach (var sect in section.SectionsWithName(AUTOLOADED_SECTION)) { var info = DsDocumentInfoSerializer.TryLoad(sect); - if (!(info is null)) + if (info is not null) autoLoadedDocuments.Add(info.Value); } @@ -215,7 +215,7 @@ sealed class SerializedTab { } public void Save(ISettingsSection section) { - Debug2.Assert(!(Content.Attribute(CONTENT_GUID_ATTR) is null)); + Debug2.Assert(Content.Attribute(CONTENT_GUID_ATTR) is not null); section.CreateSection(CONTENT_SECTION).CopyFrom(Content); section.CreateSection(UI_SECTION).CopyFrom(UI); section.CreateSection(TAB_UI_SECTION).CopyFrom(TabUI); @@ -258,7 +258,7 @@ static IEnumerable GetAutoLoadedDocuments(IEnumerable CanOpenNewTabInternal(documentTabService); void OpenNewTab() => OpenNewTabInternal(documentTabService); - bool CanCloseActiveTab => !(documentTabService.TabGroupService.ActiveTabGroup is null) && documentTabService.TabGroupService.ActiveTabGroup.CloseActiveTabCanExecute; + bool CanCloseActiveTab => documentTabService.TabGroupService.ActiveTabGroup is not null && documentTabService.TabGroupService.ActiveTabGroup.CloseActiveTabCanExecute; void CloseActiveTab() { - if (!(documentTabService.TabGroupService.ActiveTabGroup is null)) + if (documentTabService.TabGroupService.ActiveTabGroup is not null) documentTabService.TabGroupService.ActiveTabGroup.CloseActiveTab(); } - bool CanSelectNextTab => !(documentTabService.TabGroupService.ActiveTabGroup is null) && documentTabService.TabGroupService.ActiveTabGroup.SelectNextTabCanExecute; + bool CanSelectNextTab => documentTabService.TabGroupService.ActiveTabGroup is not null && documentTabService.TabGroupService.ActiveTabGroup.SelectNextTabCanExecute; void SelectNextTab() { - if (!(documentTabService.TabGroupService.ActiveTabGroup is null)) + if (documentTabService.TabGroupService.ActiveTabGroup is not null) documentTabService.TabGroupService.ActiveTabGroup.SelectNextTab(); } - bool CanSelectPrevTab => !(documentTabService.TabGroupService.ActiveTabGroup is null) && documentTabService.TabGroupService.ActiveTabGroup.SelectPreviousTabCanExecute; + bool CanSelectPrevTab => documentTabService.TabGroupService.ActiveTabGroup is not null && documentTabService.TabGroupService.ActiveTabGroup.SelectPreviousTabCanExecute; void SelectPrevTab() { - if (!(documentTabService.TabGroupService.ActiveTabGroup is null)) + if (documentTabService.TabGroupService.ActiveTabGroup is not null) documentTabService.TabGroupService.ActiveTabGroup.SelectPreviousTab(); } } @@ -148,7 +148,7 @@ sealed class CloseAllTabsButThisCtxMenuCommand : CtxMenuTabGroupCommand { : base(documentTabService) { } - public override bool IsVisible(TabGroupContext context) => !(context.TabGroup.ActiveTabContent is null); + public override bool IsVisible(TabGroupContext context) => context.TabGroup.ActiveTabContent is not null; public override bool IsEnabled(TabGroupContext context) => context.TabGroup.CloseAllButActiveTabCanExecute; public override void Execute(TabGroupContext context) => context.TabGroup.CloseAllButActiveTab(); } @@ -326,11 +326,11 @@ public override bool IsVisible(IMenuItemContext context) => sealed class OpenReferenceInNewTabCtxMenuCommand : MenuItemBase { public override void Execute(IMenuItemContext context) { var @ref = GetReference(context, out var documentViewer); - if (!(@ref is null)) + if (@ref is not null) documentViewer!.DocumentTab?.FollowReferenceNewTab(@ref); } - public override bool IsVisible(IMenuItemContext context) => !(GetReference(context, out var documentViewer) is null); + public override bool IsVisible(IMenuItemContext context) => GetReference(context, out var documentViewer) is not null; static object? GetReference(IMenuItemContext context, out IDocumentViewer? documentViewer) { documentViewer = null; @@ -395,7 +395,7 @@ sealed class CloseTabCommand : MenuTabGroupCommand { : base(documentTabService) { } - public override bool IsVisible(MenuTabGroupContext context) => !(context.TabGroup is null) && context.TabGroup.CloseActiveTabCanExecute; + public override bool IsVisible(MenuTabGroupContext context) => context.TabGroup is not null && context.TabGroup.CloseActiveTabCanExecute; public override void Execute(MenuTabGroupContext context) => context.TabGroup?.CloseActiveTab(); } @@ -608,7 +608,7 @@ public IEnumerable Create(IMenuItemContext context) { } static string GetShortMenuItemHeader(string s) { - Debug2.Assert(!(s is null)); + Debug2.Assert(s is not null); if (s is null) s = string.Empty; const int MAX_LEN = 40; @@ -637,7 +637,7 @@ void ShowTabsDlg() { // The original tab group gets back its keyboard focus by ShowDialog(). Make sure that // the correct tab is activated. - if (!(vm.LastActivated is null)) + if (vm.LastActivated is not null) vm.LastActivated.Tab.DocumentTabService.SetFocus(vm.LastActivated.Tab); } } diff --git a/dnSpy/dnSpy/Documents/Tabs/TabContentImpl.cs b/dnSpy/dnSpy/Documents/Tabs/TabContentImpl.cs index 72a7c2ed0b..a3cf4d77f5 100644 --- a/dnSpy/dnSpy/Documents/Tabs/TabContentImpl.cs +++ b/dnSpy/dnSpy/Documents/Tabs/TabContentImpl.cs @@ -55,7 +55,7 @@ public DocumentTabUIContext UIContext { private set { uiContextVersion++; var newValue = value; - Debug2.Assert(!(newValue is null)); + Debug2.Assert(newValue is not null); if (newValue is null) newValue = new NullDocumentTabUIContext(); if (uiContext != newValue) { @@ -109,8 +109,8 @@ public object? UIObject { void IFocusable.Focus() { var focusable = UIContext as IFocusable; - Debug2.Assert(!(focusable is null)); - if (!(focusable is null)) + Debug2.Assert(focusable is not null); + if (focusable is not null) focusable.Focus(); } @@ -167,8 +167,8 @@ void ITabContent.OnVisibilityChanged(TabContentVisibilityEvent visEvent) { CancelAsyncWorker(); elementZoomer.Dispose(); var id = documentTabUIContextLocator as IDisposable; - Debug2.Assert(!(id is null)); - if (!(id is null)) + Debug2.Assert(id is not null); + if (id is not null) id.Dispose(); documentTabService.OnRemoved(this); tabHistory.Dispose(); @@ -211,7 +211,7 @@ public void FollowReference(object @ref, DocumentTabContent? sourceContent, Acti void FollowReferenceCore(object @ref, DocumentTabContent? sourceContent, Action? onShown) { var result = TryCreateContentFromReference(@ref, sourceContent); - if (!(result is null)) { + if (result is not null) { Show(result.DocumentTabContent, result.UIState, e => { // Call the original caller (onShown()) first and result last since both could // move the caret. The result should only move the caret if the original caller @@ -222,7 +222,7 @@ void FollowReferenceCore(object @ref, DocumentTabContent? sourceContent, Action< } else { var defaultContent = TryCreateDefaultContent(); - if (!(defaultContent is null)) { + if (defaultContent is not null) { Show(defaultContent, null, e => { onShown?.Invoke(new ShowTabContentEventArgs(ShowTabContentResult.Failed, this)); }); @@ -258,7 +258,7 @@ public void FollowReference(object @ref, bool newTab, Action !(asyncWorkerContext is null); + public bool IsAsyncExecInProgress => asyncWorkerContext is not null; public void AsyncExec(Action preExec, Action asyncAction, Action postExec) { CancelAsyncWorker(); @@ -410,9 +410,9 @@ void CancelAsyncWorker() { } void OnShown(object? uiState, Action? onShownHandler, IShowContext showCtx, ShowTabContentResult result) { - if (!(uiState is null)) + if (uiState is not null) RestoreUIState(uiState); - if (!(onShownHandler is null) || !(showCtx.OnShown is null)) { + if (onShownHandler is not null || showCtx.OnShown is not null) { var e = new ShowTabContentEventArgs(result, this); onShownHandler?.Invoke(e); showCtx.OnShown?.Invoke(e); diff --git a/dnSpy/dnSpy/Documents/Tabs/TabHistory.cs b/dnSpy/dnSpy/Documents/Tabs/TabHistory.cs index a11a547055..5042d0a3d3 100644 --- a/dnSpy/dnSpy/Documents/Tabs/TabHistory.cs +++ b/dnSpy/dnSpy/Documents/Tabs/TabHistory.cs @@ -46,7 +46,7 @@ public TabHistory() { } public void SetCurrent(DocumentTabContent content, bool saveCurrent) { - if (saveCurrent && !(current is null)) + if (saveCurrent && current is not null) oldList.Add(new TabContentState(current, current.DocumentTab?.UIContext.CreateUIState())); current = content ?? throw new ArgumentNullException(nameof(content)); foreach (var state in newList) @@ -68,7 +68,7 @@ public void OverwriteCurrent(DocumentTabContent content) { return null; var old = oldList[oldList.Count - 1]; oldList.RemoveAt(oldList.Count - 1); - Debug2.Assert(!(current is null)); + Debug2.Assert(current is not null); newList.Add(new TabContentState(current, current.DocumentTab?.UIContext.CreateUIState())); current = old.DocumentTabContent; return old.UIState; @@ -80,7 +80,7 @@ public void OverwriteCurrent(DocumentTabContent content) { return null; var old = newList[newList.Count - 1]; newList.RemoveAt(newList.Count - 1); - Debug2.Assert(!(current is null)); + Debug2.Assert(current is not null); oldList.Add(new TabContentState(current, current.DocumentTab?.UIContext.CreateUIState())); current = old.DocumentTabContent; return old.UIState; diff --git a/dnSpy/dnSpy/Documents/Tabs/TreeNodeReferenceDocumentTabContentProvider.cs b/dnSpy/dnSpy/Documents/Tabs/TreeNodeReferenceDocumentTabContentProvider.cs index 405f4ba9b9..7ec97d77e8 100644 --- a/dnSpy/dnSpy/Documents/Tabs/TreeNodeReferenceDocumentTabContentProvider.cs +++ b/dnSpy/dnSpy/Documents/Tabs/TreeNodeReferenceDocumentTabContentProvider.cs @@ -50,7 +50,7 @@ sealed class TreeNodeReferenceDocumentTabContentProvider : IReferenceDocumentTab if (@ref is ITypeDefOrRef) return ((ITypeDefOrRef)@ref).ResolveTypeDef(); - if (@ref is IMethod && !(((IMethod)@ref).MethodSig is null)) { + if (@ref is IMethod && ((IMethod)@ref).MethodSig is not null) { var m = (IMethod)@ref; if (m is MethodSpec) m = ((MethodSpec)m).Method; @@ -82,7 +82,7 @@ sealed class TreeNodeReferenceDocumentTabContentProvider : IReferenceDocumentTab return @ref2 ?? @ref; const int MAX = 100; - for (int i = 0; i < MAX && !(def.DeclaringType is null); i++) + for (int i = 0; i < MAX && def.DeclaringType is not null; i++) def = def.DeclaringType; return def; } @@ -92,7 +92,7 @@ sealed class TreeNodeReferenceDocumentTabContentProvider : IReferenceDocumentTab if (textRef.Reference is IAssembly || textRef.Reference is ModuleDef || textRef.Reference is ModuleRef || textRef.Reference is NamespaceReference) return null; var result = CreateMemberRefResult(documentTabService, textRef.Reference); - if (!(result is null)) + if (result is not null) return result; return CreateLocalRefResult(sourceContent, textRef); @@ -132,14 +132,14 @@ sealed class TreeNodeReferenceDocumentTabContentProvider : IReferenceDocumentTab // Add the assembly to the list again. Next time the user clicks on the link, // FindNode() above will succeed. var def = @ref as IMemberDef ?? (@ref as ParamDef)?.DeclaringMethod; - if (!(def is null)) { + if (def is not null) { DsDocument? document = null; var mod = def.Module; - if (!(mod is null) && !(mod.Assembly is null)) + if (mod is not null && mod.Assembly is not null) document = DsDotNetDocument.CreateAssembly(DsDocumentInfo.CreateDocument(mod.Location), mod, false); - else if (!(mod is null)) + else if (mod is not null) document = DsDotNetDocument.CreateModule(DsDocumentInfo.CreateDocument(mod.Location), mod, false); - if (!(document is null)) { + if (document is not null) { var existingDocument = documentTabService.DocumentTreeView.DocumentService.GetOrAdd(document); if (existingDocument != document) documentTabService.DocumentTreeView.DocumentService.ForceAdd(document, true, null); @@ -150,7 +150,7 @@ sealed class TreeNodeReferenceDocumentTabContentProvider : IReferenceDocumentTab } var content = decompileDocumentTabContentFactory.Create(new DocumentTreeNodeData[] { node }); - if (@ref is MethodStatementReference statementRef && !(statementRef.Offset is null)) { + if (@ref is MethodStatementReference statementRef && statementRef.Offset is not null) { return new DocumentTabReferenceResult(content, null, a => { if (a.Success && !a.HasMovedCaret) { GoToReference(content, resolvedRef, statementRef.Method, statementRef.Offset.Value, content.WasNewContent); diff --git a/dnSpy/dnSpy/Documents/TargetFrameworkAttributeInfo.cs b/dnSpy/dnSpy/Documents/TargetFrameworkAttributeInfo.cs index baedbaa14f..1fb50b2ce8 100644 --- a/dnSpy/dnSpy/Documents/TargetFrameworkAttributeInfo.cs +++ b/dnSpy/dnSpy/Documents/TargetFrameworkAttributeInfo.cs @@ -34,7 +34,7 @@ public TargetFrameworkAttributeInfo(string framework, Version version, string pr public static bool TryCreateTargetFrameworkInfo(ModuleDef module, out TargetFrameworkAttributeInfo info) { var asm = module?.Assembly; - if (!(asm is null)) { + if (asm is not null) { if (asm.TryGetOriginalTargetFrameworkAttribute(out var framework, out var version, out var profile)) { info = new TargetFrameworkAttributeInfo(framework, version, profile); return true; diff --git a/dnSpy/dnSpy/Documents/TreeView/AssemblyDocumentNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/AssemblyDocumentNodeImpl.cs index a55e199d6a..0528c6d0f1 100644 --- a/dnSpy/dnSpy/Documents/TreeView/AssemblyDocumentNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/AssemblyDocumentNodeImpl.cs @@ -31,7 +31,7 @@ You should have received a copy of the GNU General Public License namespace dnSpy.Documents.TreeView { sealed class AssemblyDocumentNodeImpl : AssemblyDocumentNode { public AssemblyDocumentNodeImpl(IDsDotNetDocument document) - : base(document) => Debug2.Assert(!(document.AssemblyDef is null)); + : base(document) => Debug2.Assert(document.AssemblyDef is not null); public override Guid Guid => new Guid(DocumentTreeViewConstants.ASSEMBLY_NODE_GUID); protected override ImageReference GetIcon(IDotNetImageService dnImgMgr) => dnImgMgr.GetImageReference(Document.AssemblyDef!); @@ -43,7 +43,7 @@ public override IEnumerable CreateChildren() { } protected override void WriteCore(ITextColorWriter output, IDecompiler decompiler, DocumentNodeWriteOptions options) { - Debug2.Assert(!(Document.AssemblyDef is null)); + Debug2.Assert(Document.AssemblyDef is not null); if ((options & DocumentNodeWriteOptions.ToolTip) == 0) new NodeFormatter().Write(output, decompiler, Document.AssemblyDef, false, Context.ShowAssemblyVersion, Context.ShowAssemblyPublicKeyToken); else { diff --git a/dnSpy/dnSpy/Documents/TreeView/AssemblyReferenceNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/AssemblyReferenceNodeImpl.cs index 372c4d7d2e..9cf9ee7373 100644 --- a/dnSpy/dnSpy/Documents/TreeView/AssemblyReferenceNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/AssemblyReferenceNodeImpl.cs @@ -63,7 +63,7 @@ public override IEnumerable CreateChildren() { if (document is null) yield break; var mod = document.ModuleDef; - Debug2.Assert(!(mod is null)); + Debug2.Assert(mod is not null); if (mod is null) yield break; foreach (var asmRef in mod.GetAssemblyRefs()) diff --git a/dnSpy/dnSpy/Documents/TreeView/BaseTypeFolderNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/BaseTypeFolderNodeImpl.cs index fb06ab08c8..def83fe519 100644 --- a/dnSpy/dnSpy/Documents/TreeView/BaseTypeFolderNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/BaseTypeFolderNodeImpl.cs @@ -45,7 +45,7 @@ public BaseTypeFolderNodeImpl(ITreeNodeGroup treeNodeGroup, TypeDef type) { public override void Initialize() => TreeNode.LazyLoading = true; public override IEnumerable CreateChildren() { - if (!(type.BaseType is null)) + if (type.BaseType is not null) yield return new BaseTypeNodeImpl(Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.BaseTypeTreeNodeGroupBaseType), type.BaseType, true); foreach (var iface in type.Interfaces) yield return new BaseTypeNodeImpl(Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.InterfaceBaseTypeTreeNodeGroupBaseType), iface.Interface, false); diff --git a/dnSpy/dnSpy/Documents/TreeView/BaseTypeNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/BaseTypeNodeImpl.cs index f6abba5559..077737dcb3 100644 --- a/dnSpy/dnSpy/Documents/TreeView/BaseTypeNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/BaseTypeNodeImpl.cs @@ -34,7 +34,7 @@ sealed class BaseTypeNodeImpl : BaseTypeNode { protected override ImageReference GetIcon(IDotNetImageService dnImgMgr) { var td = TryGetTypeDef(); - if (!(td is null)) + if (td is not null) return dnImgMgr.GetImageReference(td); return isBaseType ? DsImages.ClassPublic : DsImages.InterfacePublic; } @@ -44,10 +44,10 @@ protected override ImageReference GetIcon(IDotNetImageService dnImgMgr) { TypeDef? TryGetTypeDef() { var td = (TypeDef?)weakRefResolvedTypeDef.Target; - if (!(td is null)) + if (td is not null) return td; td = TryGetTypeDefOrRef().ResolveTypeDef(); - if (!(td is null)) + if (td is not null) weakRefResolvedTypeDef = new WeakReference(td); return td; } @@ -89,7 +89,7 @@ public override IEnumerable CreateChildren() { if (td is null) yield break; - if (!(td.BaseType is null)) + if (td.BaseType is not null) yield return new BaseTypeNodeImpl(Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.BaseTypeTreeNodeGroupBaseType), td.BaseType, true); foreach (var iface in td.Interfaces) yield return new BaseTypeNodeImpl(Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.InterfaceBaseTypeTreeNodeGroupBaseType), iface.Interface, false); diff --git a/dnSpy/dnSpy/Documents/TreeView/DefaultDsDocumentNodeProvider.cs b/dnSpy/dnSpy/Documents/TreeView/DefaultDsDocumentNodeProvider.cs index cd60c4245f..9dd685bc8c 100644 --- a/dnSpy/dnSpy/Documents/TreeView/DefaultDsDocumentNodeProvider.cs +++ b/dnSpy/dnSpy/Documents/TreeView/DefaultDsDocumentNodeProvider.cs @@ -26,13 +26,13 @@ namespace dnSpy.Documents.TreeView { sealed class DefaultDsDocumentNodeProvider : IDsDocumentNodeProvider { public DsDocumentNode? Create(IDocumentTreeView documentTreeView, DsDocumentNode? owner, IDsDocument document) { if (document is IDsDotNetDocument dnDocument) { - Debug2.Assert(!(document.ModuleDef is null)); - if (document.AssemblyDef is null || !(owner is null)) + Debug2.Assert(document.ModuleDef is not null); + if (document.AssemblyDef is null || owner is not null) return new ModuleDocumentNodeImpl(dnDocument); return new AssemblyDocumentNodeImpl(dnDocument); } Debug2.Assert(document.AssemblyDef is null && document.ModuleDef is null); - if (!(document.PEImage is null)) + if (document.PEImage is not null) return new PEDocumentNodeImpl(document); return null; diff --git a/dnSpy/dnSpy/Documents/TreeView/DerivedTypeNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/DerivedTypeNodeImpl.cs index 171ce30161..aec4bd90f8 100644 --- a/dnSpy/dnSpy/Documents/TreeView/DerivedTypeNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/DerivedTypeNodeImpl.cs @@ -37,7 +37,7 @@ sealed class DerivedTypeNodeImpl : DerivedTypeNode { protected override ImageReference GetIcon(IDotNetImageService dnImgMgr) { var td = TryGetTypeDef(); - if (!(td is null)) + if (td is not null) return dnImgMgr.GetImageReference(td); return DsImages.ClassPublic; } @@ -54,12 +54,12 @@ public override void Initialize() => public override IEnumerable CreateChildren() { if (!createChildren) yield break; - if (!(derivedTypesFinder is null)) { + if (derivedTypesFinder is not null) { derivedTypesFinder.Cancel(); derivedTypesFinder = null; } var td = TryGetTypeDef(); - if (!(td is null)) + if (td is not null) derivedTypesFinder = new DerivedTypesFinder(this, td); } DerivedTypesFinder? derivedTypesFinder; diff --git a/dnSpy/dnSpy/Documents/TreeView/DerivedTypesFinder.cs b/dnSpy/dnSpy/Documents/TreeView/DerivedTypesFinder.cs index a1f5e797ac..45674e2d9a 100644 --- a/dnSpy/dnSpy/Documents/TreeView/DerivedTypesFinder.cs +++ b/dnSpy/dnSpy/Documents/TreeView/DerivedTypesFinder.cs @@ -38,7 +38,7 @@ public DerivedTypesFinder(DocumentTreeNodeData targetNode, TypeDef type) : base(targetNode) { msgNodeGroup = targetNode.Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.MessageTreeNodeGroupDerivedTypes); derivedTypesGroup = targetNode.Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.DerivedTypeTreeNodeGroupDerivedTypes); - weakModules = targetNode.Context.DocumentTreeView.DocumentService.GetDocuments().Where(a => !(a.ModuleDef is null)).SelectMany(a => !(a.AssemblyDef is null) ? (IEnumerable)a.AssemblyDef.Modules : new[] { a.ModuleDef! }).Select(a => new WeakReference(a)).ToArray(); + weakModules = targetNode.Context.DocumentTreeView.DocumentService.GetDocuments().Where(a => a.ModuleDef is not null).SelectMany(a => a.AssemblyDef is not null ? (IEnumerable)a.AssemblyDef.Modules : new[] { a.ModuleDef! }).Select(a => new WeakReference(a)).ToArray(); this.type = type; Start(); } @@ -81,7 +81,7 @@ IEnumerable FindDerivedTypes(ModuleDef module) { else { foreach (var td in module.GetTypes()) { var bt = td.BaseType; - if (!(bt is null) && new SigComparer().Equals(type, bt.GetScopeType())) + if (bt is not null && new SigComparer().Equals(type, bt.GetScopeType())) yield return td; } } diff --git a/dnSpy/dnSpy/Documents/TreeView/DerivedTypesFolderNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/DerivedTypesFolderNodeImpl.cs index 1d1dbb2c52..75bf628a09 100644 --- a/dnSpy/dnSpy/Documents/TreeView/DerivedTypesFolderNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/DerivedTypesFolderNodeImpl.cs @@ -49,7 +49,7 @@ public override void Initialize() => public override IEnumerable CreateChildren() { if (!createChildren) yield break; - if (!(derivedTypesFinder is null)) + if (derivedTypesFinder is not null) derivedTypesFinder.Cancel(); derivedTypesFinder = new DerivedTypesFinder(this, type); } diff --git a/dnSpy/dnSpy/Documents/TreeView/DocumentTreeNodeGroups.cs b/dnSpy/dnSpy/Documents/TreeView/DocumentTreeNodeGroups.cs index 0310ffd558..32a1480fcb 100644 --- a/dnSpy/dnSpy/Documents/TreeView/DocumentTreeNodeGroups.cs +++ b/dnSpy/dnSpy/Documents/TreeView/DocumentTreeNodeGroups.cs @@ -347,7 +347,7 @@ string GetName(ITypeDefOrRef tdr) { return tdr.Name; int parents = 0; ITypeDefOrRef parent; - for (parent = tdr.DeclaringType; !(parent is null); parent = parent.DeclaringType) + for (parent = tdr.DeclaringType; parent is not null; parent = parent.DeclaringType) parents++; bool needSep = false; // parents should be small so we don't need to use a List/Stack @@ -355,7 +355,7 @@ string GetName(ITypeDefOrRef tdr) { parent = tdr; for (int i = 0; i < parents; i++) { parent = tdr.DeclaringType; - Debug2.Assert(!(parent is null)); + Debug2.Assert(parent is not null); } if (needSep) sb.Append('.'); diff --git a/dnSpy/dnSpy/Documents/TreeView/DocumentTreeView.cs b/dnSpy/dnSpy/Documents/TreeView/DocumentTreeView.cs index 5e437c1c2f..3be39d2bdf 100644 --- a/dnSpy/dnSpy/Documents/TreeView/DocumentTreeView.cs +++ b/dnSpy/dnSpy/Documents/TreeView/DocumentTreeView.cs @@ -285,12 +285,12 @@ void DocumentService_CollectionChanged(object? sender, NotifyDocumentCollectionC var addDocumentInfo = e.Data as AddDocumentInfo; int index; - if (!(addDocumentInfo is null)) { + if (addDocumentInfo is not null) { newNode = addDocumentInfo.DsDocumentNode; index = addDocumentInfo.Index; if (newNode.TreeNode is null) TreeView.Create(newNode); - Debug2.Assert(!(newNode.TreeNode is null)); + Debug2.Assert(newNode.TreeNode is not null); } else { newNode = CreateNode(null, e.Documents[0]); @@ -315,7 +315,7 @@ void DocumentService_CollectionChanged(object? sender, NotifyDocumentCollectionC var list = new List<(DsDocumentNode docNode, int index)>(e.Documents.Select(a => { bool b = dict2.TryGetValue(a, out var node); Debug.Assert(b); - Debug2.Assert(!(node is null)); + Debug2.Assert(node is not null); int j = -1; b = b && dict.TryGetValue(node, out j); Debug.Assert(b); @@ -362,7 +362,7 @@ void DisableMemoryMappedIO(DsDocumentNode[] nodes) { public DsDocumentNode CreateNode(DsDocumentNode? owner, IDsDocument document) { foreach (var provider in dsDocumentNodeProvider) { var result = provider.Value.Create(this, owner, document); - if (!(result is null)) + if (result is not null) return result; } @@ -371,7 +371,7 @@ public DsDocumentNode CreateNode(DsDocumentNode? owner, IDsDocument document) { void ITreeViewListener.OnEvent(ITreeView treeView, TreeViewListenerEventArgs e) { if (e.Event == TreeViewListenerEvent.NodeCreated) { - Debug2.Assert(!(context is null)); + Debug2.Assert(context is not null); var node = (ITreeNode)e.Argument; if (node.Data is DocumentTreeNodeData d) d.Context = context; @@ -419,7 +419,7 @@ public FieldNode Create(FieldDef field) => return FindNode((ModuleDef)@ref); if (@ref is ITypeDefOrRef) return FindNode(((ITypeDefOrRef)@ref).ResolveTypeDef()); - if (@ref is IMethod && !(((IMethod)@ref).MethodSig is null)) + if (@ref is IMethod && ((IMethod)@ref).MethodSig is not null) return FindNode(((IMethod)@ref).ResolveMethodDef()); if (@ref is IField) return FindNode(((IField)@ref).ResolveFieldDef()); @@ -437,7 +437,7 @@ public FieldNode Create(FieldDef field) => foreach (var finder in nodeFinders) { var node = finder.Value.FindNode(this, @ref); - if (!(node is null)) + if (node is not null) return node; } @@ -458,7 +458,7 @@ public FieldNode Create(FieldDef field) => continue; n.TreeNode.EnsureChildrenLoaded(); var found = Find(n.TreeNode.DataChildren.OfType(), document); - if (!(found is null)) + if (found is not null) return found; } return null; @@ -502,7 +502,7 @@ public FieldNode Create(FieldDef field) => return null; var types = new List(); - for (var t = td; !(t is null); t = t.DeclaringType) + for (var t = td; t is not null; t = t.DeclaringType) types.Add(t); types.Reverse(); @@ -734,7 +734,7 @@ void OnDropNodes(int index, int[] nodeIndexes) { } void OnDropFiles(int index, string[] filenames) { - Debug2.Assert(!(mruList is null)); + Debug2.Assert(mruList is not null); if (mruList is null) return; if (!context.CanDragAndDrop) @@ -768,7 +768,7 @@ void OnDropFiles(int index, string[] filenames) { for (int i = 0, j = 0; i < filenames.Length; i++) { #if HAS_COMREFERENCE // Resolve shortcuts - if (!(ws is null)) { + if (ws is not null) { try { // The method seems to only accept files with a lnk extension. If it has no such // extension, it's not a shortcut and we won't get a slow thrown exception. @@ -822,13 +822,13 @@ void OnDropFiles(int index, string[] filenames) { if (newSelectedNode is null) { var filename = origFilenames.FirstOrDefault(a => File.Exists(a)); - if (!(filename is null)) { + if (filename is not null) { var key = new FilenameKey(filename); var document = DocumentService.GetDocuments().FirstOrDefault(a => key.Equals(a.Key)); newSelectedNode = FindNode(document); } } - if (!(newSelectedNode is null)) + if (newSelectedNode is not null) TreeView.SelectItems(new[] { newSelectedNode }); } @@ -853,7 +853,7 @@ static string[] GetFiles(string[] filenames) { return sorted; } - public bool CanSortTopNodes => !(GetNewSortedNodes() is null); + public bool CanSortTopNodes => GetNewSortedNodes() is not null; public void SortTopNodes() { var sortedDocuments = GetNewSortedNodes(); diff --git a/dnSpy/dnSpy/Documents/TreeView/EventNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/EventNodeImpl.cs index 4188ac5958..c10610e5e5 100644 --- a/dnSpy/dnSpy/Documents/TreeView/EventNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/EventNodeImpl.cs @@ -47,11 +47,11 @@ protected override void WriteCore(ITextColorWriter output, IDecompiler decompile } public override IEnumerable CreateChildren() { - if (!(EventDef.AddMethod is null)) + if (EventDef.AddMethod is not null) yield return new MethodNodeImpl(Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.MethodTreeNodeGroupEvent), EventDef.AddMethod); - if (!(EventDef.RemoveMethod is null)) + if (EventDef.RemoveMethod is not null) yield return new MethodNodeImpl(Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.MethodTreeNodeGroupEvent), EventDef.RemoveMethod); - if (!(EventDef.InvokeMethod is null)) + if (EventDef.InvokeMethod is not null) yield return new MethodNodeImpl(Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.MethodTreeNodeGroupEvent), EventDef.InvokeMethod); foreach (var m in EventDef.OtherMethods) yield return new MethodNodeImpl(Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.MethodTreeNodeGroupEvent), m); diff --git a/dnSpy/dnSpy/Documents/TreeView/MemberReferenceFinder.cs b/dnSpy/dnSpy/Documents/TreeView/MemberReferenceFinder.cs index cb11dd4665..e0467fca8a 100644 --- a/dnSpy/dnSpy/Documents/TreeView/MemberReferenceFinder.cs +++ b/dnSpy/dnSpy/Documents/TreeView/MemberReferenceFinder.cs @@ -113,7 +113,7 @@ static bool TryGetTypeDefOrRef(TypeSpec ts, [NotNullWhen(true)] out ITypeDefOrRe type = gis.GenericType?.TypeDefOrRef; else if (sig is TypeDefOrRefSig tdrs) type = tdrs.TypeDefOrRef; - return !(type is null); + return type is not null; } static ITypeDefOrRef GetTypeDefOrRef(ITypeDefOrRef typeRef) { diff --git a/dnSpy/dnSpy/Documents/TreeView/ModuleDocumentNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/ModuleDocumentNodeImpl.cs index 4eff9b560f..a1646d6e9f 100644 --- a/dnSpy/dnSpy/Documents/TreeView/ModuleDocumentNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/ModuleDocumentNodeImpl.cs @@ -43,7 +43,7 @@ protected override ImageReference GetIcon(IDotNetImageService dnImgMgr) => public override void Initialize() => TreeNode.LazyLoading = true; public override IEnumerable CreateChildren() { - Debug2.Assert(!(Document.ModuleDef is null)); + Debug2.Assert(Document.ModuleDef is not null); foreach (var document in Document.Children) yield return Context.DocumentTreeView.CreateNode(this, document); @@ -63,7 +63,7 @@ public override IEnumerable CreateChildren() { } protected override void WriteCore(ITextColorWriter output, IDecompiler decompiler, DocumentNodeWriteOptions options) { - Debug2.Assert(!(Document.ModuleDef is null)); + Debug2.Assert(Document.ModuleDef is not null); if ((options & DocumentNodeWriteOptions.ToolTip) == 0) new NodeFormatter().Write(output, decompiler, Document.ModuleDef, false); else { diff --git a/dnSpy/dnSpy/Documents/TreeView/NamespaceNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/NamespaceNodeImpl.cs index 72b4321821..79252e3eb4 100644 --- a/dnSpy/dnSpy/Documents/TreeView/NamespaceNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/NamespaceNodeImpl.cs @@ -61,7 +61,7 @@ protected override void WriteCore(ITextColorWriter output, IDecompiler decompile public override FilterType GetFilterType(IDocumentTreeNodeFilter filter) { var p = TreeNode.Parent; var parent = p is null ? null : p.Data as ModuleDocumentNode; - Debug2.Assert(!(parent is null)); + Debug2.Assert(parent is not null); if (parent is null) return FilterType.Default; var res = filter.GetResult(Name, parent.Document); diff --git a/dnSpy/dnSpy/Documents/TreeView/PEDocumentNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/PEDocumentNodeImpl.cs index 104eecac4d..4d0f241c12 100644 --- a/dnSpy/dnSpy/Documents/TreeView/PEDocumentNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/PEDocumentNodeImpl.cs @@ -31,7 +31,7 @@ You should have received a copy of the GNU General Public License namespace dnSpy.Documents.TreeView { sealed class PEDocumentNodeImpl : PEDocumentNode { public PEDocumentNodeImpl(IDsDocument document) - : base(document) => Debug2.Assert(!(document.PEImage is null) && document.ModuleDef is null); + : base(document) => Debug2.Assert(document.PEImage is not null && document.ModuleDef is null); public override Guid Guid => new Guid(DocumentTreeViewConstants.PEDOCUMENT_NODE_GUID); protected override ImageReference GetIcon(IDotNetImageService dnImgMgr) => dnImgMgr.GetImageReference(Document.PEImage!); @@ -43,7 +43,7 @@ public override IEnumerable CreateChildren() { } protected override void WriteCore(ITextColorWriter output, IDecompiler decompiler, DocumentNodeWriteOptions options) { - Debug2.Assert(!(Document.PEImage is null)); + Debug2.Assert(Document.PEImage is not null); if ((options & DocumentNodeWriteOptions.ToolTip) == 0) new NodeFormatter().Write(output, decompiler, Document); else { diff --git a/dnSpy/dnSpy/Documents/TreeView/ReferencesFolderNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/ReferencesFolderNodeImpl.cs index 19df09b227..1294c7b818 100644 --- a/dnSpy/dnSpy/Documents/TreeView/ReferencesFolderNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/ReferencesFolderNodeImpl.cs @@ -39,7 +39,7 @@ sealed class ReferencesFolderNodeImpl : ReferencesFolderNode { readonly ModuleDocumentNode moduleNode; public ReferencesFolderNodeImpl(ITreeNodeGroup treeNodeGroup, ModuleDocumentNode moduleNode) { - Debug2.Assert(!(moduleNode.Document.ModuleDef is null)); + Debug2.Assert(moduleNode.Document.ModuleDef is not null); TreeNodeGroup = treeNodeGroup; this.moduleNode = moduleNode; } @@ -53,7 +53,7 @@ protected override void WriteCore(ITextColorWriter output, IDecompiler decompile } public override IEnumerable CreateChildren() { - Debug2.Assert(!(moduleNode.Document.ModuleDef is null)); + Debug2.Assert(moduleNode.Document.ModuleDef is not null); foreach (var asmRef in moduleNode.Document.ModuleDef.GetAssemblyRefs()) yield return new AssemblyReferenceNodeImpl(Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.AssemblyRefTreeNodeGroupReferences), moduleNode.Document.ModuleDef, asmRef); foreach (var modRef in moduleNode.Document.ModuleDef.GetModuleRefs()) diff --git a/dnSpy/dnSpy/Documents/TreeView/Resources/ImageResourceNode.cs b/dnSpy/dnSpy/Documents/TreeView/Resources/ImageResourceNode.cs index 3e3a085ed4..903aedb104 100644 --- a/dnSpy/dnSpy/Documents/TreeView/Resources/ImageResourceNode.cs +++ b/dnSpy/dnSpy/Documents/TreeView/Resources/ImageResourceNode.cs @@ -135,7 +135,7 @@ public ImageResourceNodeImpl(ITreeNodeGroup treeNodeGroup, EmbeddedResource reso public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler, bool showOffset) { var documentViewerOutput = output as IDocumentViewerOutput; - if (!(documentViewerOutput is null)) { + if (documentViewerOutput is not null) { documentViewerOutput.AddUIElement(() => { return new System.Windows.Controls.Image { Source = imageSource, @@ -144,7 +144,7 @@ public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler } base.WriteShort(output, decompiler, showOffset); - if (!(documentViewerOutput is null)) { + if (documentViewerOutput is not null) { documentViewerOutput.AddButton(dnSpy_Resources.SaveResourceButton, () => Save()); documentViewerOutput.WriteLine(); documentViewerOutput.WriteLine(); @@ -194,7 +194,7 @@ public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler protected override IEnumerable GetDeserializedData() { var id = imageData; - Debug2.Assert(!(id is null)); + Debug2.Assert(id is not null); yield return new ResourceData(ResourceElement.Name, token => new MemoryStream(id)); } diff --git a/dnSpy/dnSpy/Documents/TreeView/Resources/ResourceElementSetNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/Resources/ResourceElementSetNodeImpl.cs index 95f32d9395..0db9a99c2c 100644 --- a/dnSpy/dnSpy/Documents/TreeView/Resources/ResourceElementSetNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/Resources/ResourceElementSetNodeImpl.cs @@ -71,7 +71,7 @@ protected override IEnumerable GetDeserializedData() { TreeNode.EnsureChildrenLoaded(); foreach (DocumentTreeNodeData node in TreeNode.DataChildren) { var provider = ResourceDataProviderUtils.GetResourceDataProvider(node); - Debug2.Assert(!(provider is null)); + Debug2.Assert(provider is not null); if (provider is null) continue; foreach (var data in provider.GetResourceData(ResourceDataType.Deserialized)) @@ -90,7 +90,7 @@ public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler public override void RegenerateEmbeddedResource() { var module = this.GetModule(); - Debug2.Assert(!(module is null)); + Debug2.Assert(module is not null); if (module is null) throw new InvalidOperationException(); RegenerateEmbeddedResource(module); diff --git a/dnSpy/dnSpy/Documents/TreeView/Resources/ResourceNodeFactory.cs b/dnSpy/dnSpy/Documents/TreeView/Resources/ResourceNodeFactory.cs index 51a857d864..5338f1316b 100644 --- a/dnSpy/dnSpy/Documents/TreeView/Resources/ResourceNodeFactory.cs +++ b/dnSpy/dnSpy/Documents/TreeView/Resources/ResourceNodeFactory.cs @@ -51,7 +51,7 @@ DocumentTreeNodeData CreateNode(ModuleDef module, Resource resource, ITreeNodeGr foreach (var provider in resourceNodeProviders) { try { var node = provider.Value.Create(module, resource, treeNodeGroup); - if (!(node is null)) + if (node is not null) return node; } catch { @@ -76,7 +76,7 @@ DocumentTreeNodeData CreateNode(ModuleDef module, ResourceElement resourceElemen foreach (var provider in resourceNodeProviders) { try { var node = provider.Value.Create(module, resourceElement, treeNodeGroup); - if (!(node is null)) + if (node is not null) return node; } catch { diff --git a/dnSpy/dnSpy/Documents/TreeView/Resources/SerializedImageListStreamerResourceElementNode.cs b/dnSpy/dnSpy/Documents/TreeView/Resources/SerializedImageListStreamerResourceElementNode.cs index 8b649f7596..6f44d1cf4e 100644 --- a/dnSpy/dnSpy/Documents/TreeView/Resources/SerializedImageListStreamerResourceElementNode.cs +++ b/dnSpy/dnSpy/Documents/TreeView/Resources/SerializedImageListStreamerResourceElementNode.cs @@ -65,7 +65,7 @@ void InitializeImageData(byte[] imageData) { } public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler, bool showOffset) { - Debug2.Assert(!(imageListOptions is null)); + Debug2.Assert(imageListOptions is not null); if (output is IDocumentViewerOutput documentViewerOutput) { for (int i = 0; i < imageListOptions.ImageSources.Count; i++) { if (i > 0) @@ -84,7 +84,7 @@ public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler protected override IEnumerable GetDeserializedData() { var id = imageData; - Debug2.Assert(!(id is null)); + Debug2.Assert(id is not null); yield return new ResourceData(ResourceElement.Name, token => new MemoryStream(id)); } @@ -100,7 +100,7 @@ public override void UpdateData(ResourceElement newResElem) { var binData = (BinaryResourceData)newResElem.ResourceData; SerializedImageListStreamerUtilities.GetImageData(this.GetModule(), binData.TypeName, binData.Data, out var imageData); - Debug2.Assert(!(imageData is null)); + Debug2.Assert(imageData is not null); InitializeImageData(imageData); } } diff --git a/dnSpy/dnSpy/Documents/TreeView/Resources/SerializedImageResourceElementNode.cs b/dnSpy/dnSpy/Documents/TreeView/Resources/SerializedImageResourceElementNode.cs index c088f4dbf1..d17a7ef783 100644 --- a/dnSpy/dnSpy/Documents/TreeView/Resources/SerializedImageResourceElementNode.cs +++ b/dnSpy/dnSpy/Documents/TreeView/Resources/SerializedImageResourceElementNode.cs @@ -79,7 +79,7 @@ public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler protected override IEnumerable GetDeserializedData() { var id = imageData; - Debug2.Assert(!(id is null)); + Debug2.Assert(id is not null); yield return new ResourceData(ResourceElement.Name, token => new MemoryStream(id)); } @@ -112,7 +112,7 @@ public override void UpdateData(ResourceElement newResElem) { var binData = (BinaryResourceData)newResElem.ResourceData; SerializedImageUtilities.GetImageData(this.GetModule(), binData.TypeName, binData.Data, out var imageData); - Debug2.Assert(!(imageData is null)); + Debug2.Assert(imageData is not null); InitializeImageData(imageData); } } diff --git a/dnSpy/dnSpy/Documents/TreeView/RootNode.cs b/dnSpy/dnSpy/Documents/TreeView/RootNode.cs index da1a9e2289..9dbaa79e28 100644 --- a/dnSpy/dnSpy/Documents/TreeView/RootNode.cs +++ b/dnSpy/dnSpy/Documents/TreeView/RootNode.cs @@ -66,13 +66,13 @@ public override void Drop(DragEventArgs e, int index) { return; if (e.Data.GetData(DocumentTreeViewConstants.DATAFORMAT_COPIED_ROOT_NODES) is int[] nodeIndexes) { - Debug2.Assert(!(DropNodes is null)); + Debug2.Assert(DropNodes is not null); DropNodes?.Invoke(index, nodeIndexes); return; } if (e.Data.GetData(DataFormats.FileDrop) is string[] filenames) { - Debug2.Assert(!(DropFiles is null)); + Debug2.Assert(DropFiles is not null); DropFiles?.Invoke(index, filenames); return; } diff --git a/dnSpy/dnSpy/Documents/TreeView/TypeReferencesFolderNodeImpl.cs b/dnSpy/dnSpy/Documents/TreeView/TypeReferencesFolderNodeImpl.cs index f0cd42c89f..c3d9630927 100644 --- a/dnSpy/dnSpy/Documents/TreeView/TypeReferencesFolderNodeImpl.cs +++ b/dnSpy/dnSpy/Documents/TreeView/TypeReferencesFolderNodeImpl.cs @@ -40,7 +40,7 @@ sealed class TypeReferencesFolderNodeImpl : TypeReferencesFolderNode { readonly ModuleDocumentNode moduleNode; public TypeReferencesFolderNodeImpl(ITreeNodeGroup treeNodeGroup, ModuleDocumentNode moduleNode) { - Debug2.Assert(!(moduleNode.Document.ModuleDef is null)); + Debug2.Assert(moduleNode.Document.ModuleDef is not null); TreeNodeGroup = treeNodeGroup; this.moduleNode = moduleNode; } @@ -81,13 +81,13 @@ public TypeSpecsFolderNodeImpl(ITreeNodeGroup treeNodeGroup, Dictionary CreateChildren() { - Debug2.Assert(!(typeDict is null)); + Debug2.Assert(typeDict is not null); foreach (var kv in typeDict) { var type = kv.Key; @@ -124,13 +124,13 @@ public MethodReferencesFolderNodeImpl(ITreeNodeGroup treeNodeGroup, Dictionary CreateChildren() { - Debug2.Assert(!(methodDict is null)); + Debug2.Assert(methodDict is not null); foreach (var kv in methodDict) { var method = kv.Key; @@ -165,13 +165,13 @@ public PropertyReferencesFolderNodeImpl(ITreeNodeGroup treeNodeGroup, Dictionary this.propertyDict = propertyDict; foreach (var kv in propertyDict) { scope = kv.Key.DeclaringType?.Scope; - if (!(scope is null)) + if (scope is not null) break; } } public override IEnumerable CreateChildren() { - Debug2.Assert(!(propertyDict is null)); + Debug2.Assert(propertyDict is not null); foreach (var kv in propertyDict) { var property = kv.Key; @@ -206,13 +206,13 @@ public EventReferencesFolderNodeImpl(ITreeNodeGroup treeNodeGroup, Dictionary CreateChildren() { - Debug2.Assert(!(eventDict is null)); + Debug2.Assert(eventDict is not null); foreach (var kv in eventDict) { var @event = kv.Key; @@ -247,13 +247,13 @@ public FieldReferencesFolderNodeImpl(ITreeNodeGroup treeNodeGroup, Dictionary CreateChildren() { - Debug2.Assert(!(fieldDict is null)); + Debug2.Assert(fieldDict is not null); foreach (var kv in fieldDict) { var field = kv.Key; @@ -297,7 +297,7 @@ public TypeReferenceNodeImpl(ITreeNodeGroup treeNodeGroup, ITypeDefOrRef type, T } public override void Initialize() { - Debug2.Assert(!(typeInfo is null)); + Debug2.Assert(typeInfo is not null); TreeNode.LazyLoading = typeInfo.TypeDict.Count != 0 || typeInfo.MethodDict.Count != 0 || @@ -307,7 +307,7 @@ public override void Initialize() { } public override IEnumerable CreateChildren() { - Debug2.Assert(!(typeInfo is null)); + Debug2.Assert(typeInfo is not null); if (typeInfo.TypeDict.Count != 0) yield return new TypeSpecsFolderNodeImpl(Context.DocumentTreeView.DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.TypeSpecsFolderTreeNodeGroupTypeReference), typeInfo.TypeDict); diff --git a/dnSpy/dnSpy/Events/WeakEventList.cs b/dnSpy/dnSpy/Events/WeakEventList.cs index 9103f8d943..70ad5fd299 100644 --- a/dnSpy/dnSpy/Events/WeakEventList.cs +++ b/dnSpy/dnSpy/Events/WeakEventList.cs @@ -57,7 +57,7 @@ sealed class HardRefInfo : Info { } sealed class InstanceInfo : Info { - public override bool IsAlive => !(target.Target is null); + public override bool IsAlive => target.Target is not null; public override void Execute(object? source, TEventArgs e) { if (target.Target is object self) @@ -71,7 +71,7 @@ public override bool Equals(EventHandler h) => readonly MethodInfo methodInfo; public InstanceInfo(EventHandler handler) { - Debug2.Assert(!(handler.Target is null)); + Debug2.Assert(handler.Target is not null); Debug.Assert(handler.GetInvocationList().Length == 1); target = new WeakReference(handler.Target); methodInfo = handler.Method; diff --git a/dnSpy/dnSpy/Extension/ExtensionService.cs b/dnSpy/dnSpy/Extension/ExtensionService.cs index 842abd11dc..2abeff944a 100644 --- a/dnSpy/dnSpy/Extension/ExtensionService.cs +++ b/dnSpy/dnSpy/Extension/ExtensionService.cs @@ -42,12 +42,12 @@ sealed class ExtensionService : IExtensionService { public IEnumerable LoadedExtensions { get { - Debug2.Assert(!(loadedExtensions is null), "Called too early"); + Debug2.Assert(loadedExtensions is not null, "Called too early"); return (loadedExtensions ?? Array.Empty()); } internal set { Debug2.Assert(loadedExtensions is null); - if (!(loadedExtensions is null)) + if (loadedExtensions is not null) throw new InvalidOperationException(); loadedExtensions = value.ToArray(); } diff --git a/dnSpy/dnSpy/Hex/Adornments/HexToolTipProviderImpl.cs b/dnSpy/dnSpy/Hex/Adornments/HexToolTipProviderImpl.cs index f66ccfb440..0d49781614 100644 --- a/dnSpy/dnSpy/Hex/Adornments/HexToolTipProviderImpl.cs +++ b/dnSpy/dnSpy/Hex/Adornments/HexToolTipProviderImpl.cs @@ -45,7 +45,7 @@ public HexToolTipProviderImpl(WpfHexView wpfHexView) { } public override void ClearToolTip() { - if (!(toolTipAgent is null)) + if (toolTipAgent is not null) spaceReservationManager.RemoveAgent(toolTipAgent); } diff --git a/dnSpy/dnSpy/Hex/Classification/HexClassifierAggregator.cs b/dnSpy/dnSpy/Hex/Classification/HexClassifierAggregator.cs index 66c3703a90..5c2cdf71c4 100644 --- a/dnSpy/dnSpy/Hex/Classification/HexClassifierAggregator.cs +++ b/dnSpy/dnSpy/Hex/Classification/HexClassifierAggregator.cs @@ -64,10 +64,10 @@ void GetClassificationSpansCore(List result, HexClassific var list = new List(); var taggerContext = new HexTaggerContext(context.Line, context.LineSpan); - var tags = !(cancellationToken is null) ? hexTagAggregator.GetAllTags(taggerContext, cancellationToken.Value) : hexTagAggregator.GetAllTags(taggerContext); + var tags = cancellationToken is not null ? hexTagAggregator.GetAllTags(taggerContext, cancellationToken.Value) : hexTagAggregator.GetAllTags(taggerContext); foreach (var tagSpan in tags) { var overlap = textSpan.Overlap(tagSpan.Span); - if (!(overlap is null)) + if (overlap is not null) list.Add(new HexClassificationSpan(overlap.Value, tagSpan.Tag.ClassificationType)); } diff --git a/dnSpy/dnSpy/Hex/Commands/GoToMetadataVM.cs b/dnSpy/dnSpy/Hex/Commands/GoToMetadataVM.cs index b403102c38..9110571b2a 100644 --- a/dnSpy/dnSpy/Hex/Commands/GoToMetadataVM.cs +++ b/dnSpy/dnSpy/Hex/Commands/GoToMetadataVM.cs @@ -35,7 +35,7 @@ sealed class GoToMetadataVM : ViewModelBase { public ICommand GoToMetadataUSCommand => new RelayCommand(a => GoToMetadataKind = GoToMetadataKind.US); public ICommand GoToMetadataGUIDCommand => new RelayCommand(a => GoToMetadataKind = GoToMetadataKind.GUID); public ICommand GoToMetadataTableCommand => new RelayCommand(a => GoToMetadataKind = GoToMetadataKind.Table); - public ICommand GoToMetadataMemberRvaCommand => new RelayCommand(a => GoToMetadataKind = GoToMetadataKind.MemberRva, a => !(peHeaders is null)); + public ICommand GoToMetadataMemberRvaCommand => new RelayCommand(a => GoToMetadataKind = GoToMetadataKind.MemberRva, a => peHeaders is not null); public bool IsOffset { get { @@ -127,7 +127,7 @@ public GoToMetadataVM(HexBuffer buffer, DotNetMetadataHeaders mdHeaders, PeHeade offsetTokenVM = new OffsetTokenVM(buffer, mdHeaders, peHeaders, value, a => HasErrorUpdated()); GoToMetadataCollection = new ObservableCollection(); GoToMetadataCollection.Add(new GoToMetadataKindVM(GoToMetadataKind.Table, dnSpy_Resources.GoToMetadataToken, dnSpy_Resources.ShortCutKeyCtrl1)); - if (!(peHeaders is null)) + if (peHeaders is not null) GoToMetadataCollection.Add(new GoToMetadataKindVM(GoToMetadataKind.MemberRva, dnSpy_Resources.GoToMetadataMethodBody, dnSpy_Resources.ShortCutKeyCtrl2)); GoToMetadataCollection.Add(new GoToMetadataKindVM(GoToMetadataKind.Blob, "#Blob", dnSpy_Resources.ShortCutKeyCtrl3)); GoToMetadataCollection.Add(new GoToMetadataKindVM(GoToMetadataKind.Strings, "#Strings", dnSpy_Resources.ShortCutKeyCtrl4)); @@ -165,7 +165,7 @@ public GoToMetadataKind GoToMetadataKind { protected override string? ConvertToValue(out uint value) { value = SimpleTypeConverter.ParseUInt32(StringValue, Min, Max, out var error); - if (!(error is null)) + if (error is not null) return error; return CheckOffsetToken(value) ? null : dnSpy_Resources.GoToMetadataInvalidOffsetOrToken; } @@ -193,7 +193,7 @@ bool CheckOffsetToken(uint value) { return value != 0 && mdHeaders.GUIDStream?.IsValidIndex(value) == true; case GoToMetadataKind.Table: - return !(GetMDTable(value) is null); + return GetMDTable(value) is not null; case GoToMetadataKind.MemberRva: if (peHeaders is null) diff --git a/dnSpy/dnSpy/Hex/Commands/HexCommandOperations.cs b/dnSpy/dnSpy/Hex/Commands/HexCommandOperations.cs index c55602cd89..2c03b12493 100644 --- a/dnSpy/dnSpy/Hex/Commands/HexCommandOperations.cs +++ b/dnSpy/dnSpy/Hex/Commands/HexCommandOperations.cs @@ -91,7 +91,7 @@ void HexView_Closed(object? sender, EventArgs e) { Dispatcher CurrentDispatcher { get { var wpfHexView = HexView as WpfHexView; - Debug2.Assert(!(wpfHexView is null)); + Debug2.Assert(wpfHexView is not null); return wpfHexView?.VisualElement.Dispatcher ?? Dispatcher.CurrentDispatcher; } } @@ -99,10 +99,10 @@ Dispatcher CurrentDispatcher { Window OwnerWindow { get { var wpfHexView = HexView as WpfHexView; - Debug2.Assert(!(wpfHexView is null)); - if (!(wpfHexView is null)) { + Debug2.Assert(wpfHexView is not null); + if (wpfHexView is not null) { var window = Window.GetWindow(wpfHexView.VisualElement); - if (!(window is null)) + if (window is not null) return window; } return Application.Current.MainWindow; @@ -180,7 +180,7 @@ public override void GoToMetadata(GoToMetadataKind mdKind) { return; var span = GetGoToMetadataSpan(mdHeaders, peHeaders, data.OffsetTokenValue, data.GoToMetadataKind); - Debug2.Assert(!(span is null)); + Debug2.Assert(span is not null); if (span is null) return; var info = UserValueToSelection(span.Value.End, span.Value.Start); diff --git a/dnSpy/dnSpy/Hex/ContextMenuCommands/Commands.cs b/dnSpy/dnSpy/Hex/ContextMenuCommands/Commands.cs index eb51f92863..8d4bf903aa 100644 --- a/dnSpy/dnSpy/Hex/ContextMenuCommands/Commands.cs +++ b/dnSpy/dnSpy/Hex/ContextMenuCommands/Commands.cs @@ -191,7 +191,7 @@ public override void Execute(HexViewContext context) { } public IEnumerable Create(IMenuItemContext context) { var ctx = CreateContext(context); - Debug2.Assert(!(ctx is null)); + Debug2.Assert(ctx is not null); if (ctx is null) yield break; var hexView = ctx.HexView; @@ -217,7 +217,7 @@ public override void Execute(HexViewContext context) { } public IEnumerable Create(IMenuItemContext context) { var ctx = CreateContext(context); - Debug2.Assert(!(ctx is null)); + Debug2.Assert(ctx is not null); if (ctx is null) yield break; var hexView = ctx.HexView; diff --git a/dnSpy/dnSpy/Hex/Editor/ActiveColumnHighlighter.cs b/dnSpy/dnSpy/Hex/Editor/ActiveColumnHighlighter.cs index 1e8bd2b04d..05e82674e3 100644 --- a/dnSpy/dnSpy/Hex/Editor/ActiveColumnHighlighter.cs +++ b/dnSpy/dnSpy/Hex/Editor/ActiveColumnHighlighter.cs @@ -201,7 +201,7 @@ void RecreateRectangles() { RemoveAllRectangles(); if (!enabled) return; - Debug2.Assert(!(adornmentLayer is null)); + Debug2.Assert(adornmentLayer is not null); if (wpfHexView.ViewportHeight == 0) return; diff --git a/dnSpy/dnSpy/Hex/Editor/ColumnLineSeparators.cs b/dnSpy/dnSpy/Hex/Editor/ColumnLineSeparators.cs index b044d21011..0ef0498806 100644 --- a/dnSpy/dnSpy/Hex/Editor/ColumnLineSeparators.cs +++ b/dnSpy/dnSpy/Hex/Editor/ColumnLineSeparators.cs @@ -232,7 +232,7 @@ void RecreateColumnLines() { RemoveAllLines(); if (!enabled) return; - Debug2.Assert(!(adornmentLayer is null)); + Debug2.Assert(adornmentLayer is not null); if (wpfHexView.ViewportHeight == 0) return; @@ -282,7 +282,7 @@ HexColumnLineKind GetColumnLineKind(LineElementKind lineElemKind) { newPen = InitializePen(new Pen(scBrush, PEN_THICKNESS), lineKind); newPen.Freeze(); } - else if (!((newPen = props[VSTC.MarkerFormatDefinition.BorderId] as Pen) is null)) { + else if ((newPen = props[VSTC.MarkerFormatDefinition.BorderId] as Pen) is not null) { if (newPen.CanFreeze) newPen.Freeze(); } diff --git a/dnSpy/dnSpy/Hex/Editor/CurrentLineHighlighter.cs b/dnSpy/dnSpy/Hex/Editor/CurrentLineHighlighter.cs index 959fe58077..8c40d62a04 100644 --- a/dnSpy/dnSpy/Hex/Editor/CurrentLineHighlighter.cs +++ b/dnSpy/dnSpy/Hex/Editor/CurrentLineHighlighter.cs @@ -138,7 +138,7 @@ void PositionLineElement() { adornmentLayer?.RemoveAllAdornments(); return; } - Debug2.Assert(!(adornmentLayer is null)); + Debug2.Assert(adornmentLayer is not null); var line = wpfHexView.Caret.ContainingHexViewLine; if (line.IsVisible()) { @@ -236,7 +236,7 @@ public void SetLine(HexViewLine line, double width) { if (line is null) throw new ArgumentNullException(nameof(line)); var newRect = new Rect(PEN_THICKNESS / 2, PEN_THICKNESS / 2, Math.Max(0, width - PEN_THICKNESS), Math.Max(0, line.TextHeight + HexFormattedLineImpl.DEFAULT_BOTTOM_SPACE - PEN_THICKNESS)); - if (!(geometry is null) && newRect == geometryRect) + if (geometry is not null && newRect == geometryRect) return; geometryRect = newRect; if (geometryRect.Height == 0 || geometryRect.Width == 0) @@ -251,7 +251,7 @@ public void SetLine(HexViewLine line, double width) { protected override void OnRender(DrawingContext drawingContext) { base.OnRender(drawingContext); - if (!(geometry is null)) + if (geometry is not null) drawingContext.DrawGeometry(BackgroundBrush, pen, geometry); } } diff --git a/dnSpy/dnSpy/Hex/Editor/CurrentValueHighlighter.cs b/dnSpy/dnSpy/Hex/Editor/CurrentValueHighlighter.cs index 156aeb7885..113c52fc92 100644 --- a/dnSpy/dnSpy/Hex/Editor/CurrentValueHighlighter.cs +++ b/dnSpy/dnSpy/Hex/Editor/CurrentValueHighlighter.cs @@ -54,8 +54,8 @@ sealed class CurrentValueHighlighterHexViewTaggerProvider : HexViewTaggerProvide public override IHexTagger? CreateTagger(HexView hexView, HexBuffer buffer) { var wpfHexView = hexView as WpfHexView; - Debug2.Assert(!(wpfHexView is null)); - if (!(wpfHexView is null)) { + Debug2.Assert(wpfHexView is not null); + if (wpfHexView is not null) { return wpfHexView.Properties.GetOrCreateSingletonProperty(typeof(CurrentValueHighlighterTagger), () => new CurrentValueHighlighterTagger(currentValueHighlighterProvider.Get(wpfHexView))) as IHexTagger; } @@ -239,7 +239,7 @@ void DelayUpdateCurrentValue() { } if (delayDispatcherTimer is null) { - if (!(savedValue is null) && !TryUpdateCurrentValue()) + if (savedValue is not null && !TryUpdateCurrentValue()) return; savedValue = null; // Make sure old highlighting gets cleared immediately @@ -259,7 +259,7 @@ void DelayUpdateCurrentValue() { void StopTimer() { var timer = delayDispatcherTimer; delayDispatcherTimer = null; - if (!(timer is null)) { + if (timer is not null) { timer.Stop(); timer.Tick -= Timer_Tick; } @@ -302,14 +302,14 @@ bool TryUpdateCurrentValue() { } void Buffer_BufferSpanInvalidated(object? sender, HexBufferSpanInvalidatedEventArgs e) { - if (!(savedValue is null) && savedValue.BufferSpan.Span.OverlapsWith(e.Span)) { + if (savedValue is not null && savedValue.BufferSpan.Span.OverlapsWith(e.Span)) { if (!savedValue.UpdateValue()) RefreshAll(); } } void Buffer_ChangedLowPriority(object? sender, HexContentChangedEventArgs e) { - if (!(savedValue is null)) { + if (savedValue is not null) { foreach (var change in e.Changes) { if (savedValue.BufferSpan.Span.OverlapsWith(change.OldSpan)) { if (!savedValue.UpdateValue()) @@ -346,7 +346,7 @@ internal IEnumerable> GetTags(HexTaggerContext con else lastCell = cell; } - if (!(startCell is null)) + if (startCell is not null) yield return new HexTextTagSpan(VST.Span.FromBounds(startCell.CellSpan.Start, lastCell!.CellSpan.End), markerTag); } static readonly HexMarkerTag valueCellMarkerTag = new HexMarkerTag(CTC.ThemeClassificationTypeNameKeys.HexCurrentValueCell); @@ -357,7 +357,7 @@ internal IEnumerable> GetTags(NormalizedHexBufferSpanC } internal void Register(CurrentValueHighlighterTagger currentValueHighlighterTagger) { - if (!(this.currentValueHighlighterTagger is null)) + if (this.currentValueHighlighterTagger is not null) throw new InvalidOperationException(); this.currentValueHighlighterTagger = currentValueHighlighterTagger ?? throw new ArgumentNullException(nameof(currentValueHighlighterTagger)); } diff --git a/dnSpy/dnSpy/Hex/Editor/DefaultHexViewMouseProcessor.cs b/dnSpy/dnSpy/Hex/Editor/DefaultHexViewMouseProcessor.cs index 8e1063396e..340b6fda8c 100644 --- a/dnSpy/dnSpy/Hex/Editor/DefaultHexViewMouseProcessor.cs +++ b/dnSpy/dnSpy/Hex/Editor/DefaultHexViewMouseProcessor.cs @@ -160,11 +160,11 @@ void GetSelectionOrCaretIfNoSelection(out HexBufferPoint start, out HexBufferPoi public override void OnMouseMove(object? sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { - if (!(mouseLeftDownInfo is null) && !mouseLeftDownInfo.Value.TryUpdateBufferLines(wpfHexView.BufferLines)) { + if (mouseLeftDownInfo is not null && !mouseLeftDownInfo.Value.TryUpdateBufferLines(wpfHexView.BufferLines)) { CancelMouseLeftButtonSelection(); return; } - if (!mouseCaptured && !(mouseLeftDownInfo is null)) { + if (!mouseCaptured && mouseLeftDownInfo is not null) { var mouseLoc = GetLocation(e); var dist = mouseLeftDownInfo.Value.Point - mouseLoc.Point; bool movedEnough = Math.Abs(dist.X) >= SystemParameters.MinimumHorizontalDragDistance || @@ -177,7 +177,7 @@ public override void OnMouseMove(object? sender, MouseEventArgs e) { } else if (mouseCaptured) { e.Handled = true; - Debug2.Assert(!(mouseLeftDownInfo is null)); + Debug2.Assert(mouseLeftDownInfo is not null); if (mouseLeftDownInfo is null) StopScrolling(); else if (mouseLeftDownInfo.Value.Clicks == 2 || mouseLeftDownInfo.Value.Clicks == 3) { @@ -241,7 +241,7 @@ void UpdateScrolling(MouseEventArgs e) { return; } - if (!(dispatcherTimer is null)) { + if (dispatcherTimer is not null) { // It resets the timer if we write a new value, even if it's identical to the original value if (dispatcherTimer.Interval != interval) dispatcherTimer.Interval = interval; diff --git a/dnSpy/dnSpy/Hex/Editor/HexAdornmentLayerImpl.cs b/dnSpy/dnSpy/Hex/Editor/HexAdornmentLayerImpl.cs index 6601744e7a..41837a1376 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexAdornmentLayerImpl.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexAdornmentLayerImpl.cs @@ -52,7 +52,7 @@ public HexAdornmentLayerImpl(WpfHexView hexView, HexLayerKind layerKind, Metadat public override bool AddAdornment(VSTE.AdornmentPositioningBehavior behavior, HexBufferSpan? visualSpan, object? tag, UIElement adornment, VSTE.AdornmentRemovedCallback? removedCallback) { if (adornment is null) throw new ArgumentNullException(nameof(adornment)); - if (!(visualSpan is null) && visualSpan.Value.IsDefault) + if (visualSpan is not null && visualSpan.Value.IsDefault) throw new ArgumentException(); if (visualSpan is null && behavior == VSTE.AdornmentPositioningBehavior.TextRelative) throw new ArgumentNullException(nameof(visualSpan)); @@ -61,7 +61,7 @@ public override bool AddAdornment(VSTE.AdornmentPositioningBehavior behavior, He if (layerKind != HexLayerKind.Normal) { if (behavior != VSTE.AdornmentPositioningBehavior.OwnerControlled) throw new ArgumentOutOfRangeException(nameof(behavior), "Special layers must use AdornmentPositioningBehavior.OwnerControlled"); - if (!(visualSpan is null)) + if (visualSpan is not null) throw new ArgumentOutOfRangeException(nameof(visualSpan), "Special layers must use a null visual span"); } bool canAdd = visualSpan is null || HexView.HexViewLines.IntersectsBufferSpan(visualSpan.Value); @@ -128,7 +128,7 @@ public override void RemoveMatchingAdornments(HexBufferSpan visualSpan, Predicat throw new ArgumentNullException(nameof(match)); for (int i = adornmentLayerElements.Count - 1; i >= 0; i--) { var elem = adornmentLayerElements[i]; - if (!(elem.VisualSpan is null) && visualSpan.OverlapsWith(GetOverlapsWithSpan(elem.VisualSpan.Value)) && match(elem)) { + if (elem.VisualSpan is not null && visualSpan.OverlapsWith(GetOverlapsWithSpan(elem.VisualSpan.Value)) && match(elem)) { adornmentLayerElements.RemoveAt(i); canvas.Children.RemoveAt(i); elem.RemovedCallback?.Invoke(elem.Tag, elem.Adornment); @@ -158,8 +158,8 @@ internal void OnLayoutChanged(HexViewLayoutChangedEventArgs e) { var elem = adornmentLayerElements[i]; // All adornments that exist in spans that have been removed or in reformatted lines are always removed. - if (!(elem.VisualSpan is null) && - (!HexView.HexViewLines.IntersectsBufferSpan(elem.VisualSpan.Value) || !(GetLine(e.NewOrReformattedLines, GetOverlapsWithSpan(elem.VisualSpan.Value)) is null))) { + if (elem.VisualSpan is not null && + (!HexView.HexViewLines.IntersectsBufferSpan(elem.VisualSpan.Value) || GetLine(e.NewOrReformattedLines, GetOverlapsWithSpan(elem.VisualSpan.Value)) is not null)) { adornmentLayerElements.RemoveAt(i); canvas.Children.RemoveAt(i); elem.RemovedCallback?.Invoke(elem.Tag, elem.Adornment); @@ -176,9 +176,9 @@ internal void OnLayoutChanged(HexViewLayoutChangedEventArgs e) { break; case VSTE.AdornmentPositioningBehavior.TextRelative: - Debug2.Assert(!(elem.VisualSpan is null)); + Debug2.Assert(elem.VisualSpan is not null); var translatedLine = GetLine(e.TranslatedLines, GetOverlapsWithSpan(elem.VisualSpan.Value)); - if (!(translatedLine is null)) { + if (translatedLine is not null) { // Only y is updated, x is owner controlled Canvas.SetTop(elem.Adornment, ToDefault(Canvas.GetTop(elem.Adornment), 0) + translatedLine.DeltaY); } diff --git a/dnSpy/dnSpy/Hex/Editor/HexCaretImpl.cs b/dnSpy/dnSpy/Hex/Editor/HexCaretImpl.cs index e8b6d2ac11..3f29f4a604 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexCaretImpl.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexCaretImpl.cs @@ -201,7 +201,7 @@ void CancelCompositionString() { } void InitializeIME() { - if (!(imeState.HwndSource is null)) + if (imeState.HwndSource is not null) return; imeState.HwndSource = PresentationSource.FromVisual(hexView.VisualElement) as HwndSource; if (imeState.HwndSource is null) @@ -365,7 +365,7 @@ IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool hand } void MoveImeCompositionWindow() { - Debug2.Assert(!(imeState.HwndSource is null)); + Debug2.Assert(imeState.HwndSource is not null); if (!IsValuesCaretPresent && !IsAsciiCaretPresent) return; if (imeState.Context == IntPtr.Zero) @@ -386,11 +386,11 @@ void MoveImeCompositionWindow() { var rootVisual = imeState.HwndSource.RootVisual; GeneralTransform? generalTransform = null; - if (!(rootVisual is null) && rootVisual.IsAncestorOf(hexView.VisualElement)) + if (rootVisual is not null && rootVisual.IsAncestorOf(hexView.VisualElement)) generalTransform = hexView.VisualElement.TransformToAncestor(rootVisual); var compTarget = imeState.HwndSource.CompositionTarget; - if (!(generalTransform is null) && !(compTarget is null)) { + if (generalTransform is not null && compTarget is not null) { var transform = compTarget.TransformToDevice; compForm.dwStyle = CFS_FORCE_POSITION; @@ -721,7 +721,7 @@ void SavePreferredXCoordinate() { void SavePreferredYCoordinate() { var line = GetVisibleCaretLine(); - if (!(line is null)) + if (line is not null) __preferredYCoordinate = (line.Top + line.Bottom) / 2 - hexView.ViewportTop; else __preferredYCoordinate = 0; diff --git a/dnSpy/dnSpy/Hex/Editor/HexCaretLayer.cs b/dnSpy/dnSpy/Hex/Editor/HexCaretLayer.cs index 4b3a30b1d2..038a614f40 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexCaretLayer.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexCaretLayer.cs @@ -331,7 +331,7 @@ void StopTimer() { } void StartTimer() { - if (!(dispatcherTimer is null)) + if (dispatcherTimer is not null) throw new InvalidOperationException(); // Make sure the caret doesn't blink when it's moved layer.Opacity = 1; diff --git a/dnSpy/dnSpy/Hex/Editor/HexEditorFactoryServiceImpl.cs b/dnSpy/dnSpy/Hex/Editor/HexEditorFactoryServiceImpl.cs index e7c63cc2a0..1972cb306b 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexEditorFactoryServiceImpl.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexEditorFactoryServiceImpl.cs @@ -103,7 +103,7 @@ public IEnumerable GetGuidObjects(GuidObjectsProviderArgs args) { yield return new GuidObject(MenuConstants.GUIDOBJ_WPF_HEXVIEW_GUID, wpfHexView); yield return new GuidObject(MenuConstants.GUIDOBJ_HEXEDITORPOSITION_GUID, wpfHexView.Caret.Position); - if (!(createGuidObjects is null)) { + if (createGuidObjects is not null) { foreach (var guidObject in createGuidObjects(args)) yield return guidObject; } @@ -150,7 +150,7 @@ public override WpfHexView Create(HexBuffer buffer, VSTE.ITextViewRoleSet roles, var wpfHexView = new WpfHexViewImpl(buffer, roles, parentOptions, hexEditorOptionsFactoryService, commandService, formattedHexSourceFactoryService, hexViewClassifierAggregatorService, hexAndAdornmentSequencerFactoryService, hexBufferLineFormatterFactoryService, classificationFormatMapService, editorFormatMapService, adornmentLayerDefinitionService, lineTransformProviderService, spaceReservationStackProvider, wpfHexViewCreationListeners, hexViewCreationListeners, classificationTypeRegistryService, hexCursorProviderFactories); - if (!(options?.MenuGuid is null)) { + if (options?.MenuGuid is not null) { var guidObjectsProvider = new GuidObjectsProvider(wpfHexView, options.CreateGuidObjects); menuService.InitializeContextMenu(wpfHexView.VisualElement, options.MenuGuid.Value, guidObjectsProvider, new HexContextMenuInitializer(wpfHexView)); } diff --git a/dnSpy/dnSpy/Hex/Editor/HexEditorOptions.cs b/dnSpy/dnSpy/Hex/Editor/HexEditorOptions.cs index 0ef7407006..6da430b699 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexEditorOptions.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexEditorOptions.cs @@ -68,7 +68,7 @@ public HexEditorOptions(HexEditorOptionsFactoryServiceImpl service, HexEditorOpt } void UpdateOptions(HexEditorOptions? oldParent) { - if (!(oldParent is null)) { + if (oldParent is not null) { for (int i = 0; i < oldParent.weakChildren.Count; i++) { if (oldParent.weakChildren[i].Target == this) { oldParent.weakChildren.RemoveAt(i); @@ -76,10 +76,10 @@ void UpdateOptions(HexEditorOptions? oldParent) { } } } - if (!(parent is null)) + if (parent is not null) parent.weakChildren.Add(new WeakReference(this)); - if (!(parent is null) || !(oldParent is null)) { + if (parent is not null || oldParent is not null) { foreach (var o in SupportedOptions) { if (dict.ContainsKey(o.Name)) continue; @@ -92,10 +92,10 @@ void UpdateOptions(HexEditorOptions? oldParent) { } bool TryGetValue(string optionId, [NotNullWhen(true)] out object? value) { - if (!(scope is null) && !service.GetOption(optionId).IsApplicableToScope(scope)) + if (scope is not null && !service.GetOption(optionId).IsApplicableToScope(scope)) throw new InvalidOperationException(); HexEditorOptions? p = this; - while (!(p is null)) { + while (p is not null) { if (p.dict.TryGetValue(optionId, out value)) return true; p = p.parent; @@ -128,7 +128,7 @@ void OnChanged(string optionId) { public bool IsOptionDefined(string optionId, bool localScopeOnly) { if (optionId is null) throw new ArgumentNullException(nameof(optionId)); - if (!(parent is null) && localScopeOnly) + if (parent is not null && localScopeOnly) return dict.ContainsKey(optionId); var def = service.GetOption(optionId); return scope is null || def.IsApplicableToScope(scope); @@ -160,7 +160,7 @@ public void SetOptionValue(string optionId, object? value) { if (optionId is null) throw new ArgumentNullException(nameof(optionId)); var def = service.GetOption(optionId); - if (!(scope is null) && !def.IsApplicableToScope(scope)) + if (scope is not null && !def.IsApplicableToScope(scope)) throw new InvalidOperationException(); if (!def.IsValid(ref value)) throw new ArgumentException(); diff --git a/dnSpy/dnSpy/Hex/Editor/HexGlyphMargin.cs b/dnSpy/dnSpy/Hex/Editor/HexGlyphMargin.cs index 019e690911..20258c7fb5 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexGlyphMargin.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexGlyphMargin.cs @@ -192,7 +192,7 @@ HexMouseProcessor[] CreateMouseProcessors() { } void InitializeGlyphFactories() { - Debug2.Assert(!(iconCanvas is null)); + Debug2.Assert(iconCanvas is not null); var oldFactories = new Dictionary(); foreach (var info in glyphFactories.Values) oldFactories[info.FactoryProvider] = info.Factory; @@ -203,7 +203,7 @@ void InitializeGlyphFactories() { foreach (var lazy in lazyGlyphFactoryProviders) { HexGlyphFactory? glyphFactory = null; foreach (var type in lazy.Metadata.TagTypes) { - Debug2.Assert(!(type is null)); + Debug2.Assert(type is not null); if (type is null) break; Debug.Assert(!glyphFactories.ContainsKey(type)); @@ -241,7 +241,7 @@ void InitializeGlyphFactories() { } void Initialize() { - if (!(mouseProcessorCollection is null)) + if (mouseProcessorCollection is not null) return; iconCanvas = new Canvas { Background = Brushes.Transparent }; canvas.Children.Add(iconCanvas); @@ -269,7 +269,7 @@ void GlyphMargin_IsVisibleChanged(object? sender, DependencyPropertyChangedEvent } void RefreshEverything() { - Debug2.Assert(!(lineInfos is null)); + Debug2.Assert(lineInfos is not null); lineInfos.Clear(); foreach (var c in childCanvases) c.Children.Clear(); @@ -283,7 +283,7 @@ void HexView_LayoutChanged(object? sender, HexViewLayoutChangedEventArgs e) { } void OnNewLayout(IReadOnlyList newOrReformattedLines, IReadOnlyList translatedLines) { - Debug2.Assert(!(lineInfos is null)); + Debug2.Assert(lineInfos is not null); var newInfos = new Dictionary(); foreach (var line in newOrReformattedLines) @@ -318,7 +318,7 @@ void OnNewLayout(IReadOnlyList newOrReformattedLines, IReadOnlyList void AddLine(Dictionary newInfos, HexViewLine line) { var wpfLine = line as WpfHexViewLine; - Debug2.Assert(!(wpfLine is null)); + Debug2.Assert(wpfLine is not null); if (wpfLine is null) return; var info = new LineInfo(line, CreateIconInfos(wpfLine)); @@ -330,7 +330,7 @@ void AddLine(Dictionary newInfos, HexViewLine line) { List CreateIconInfos(WpfHexViewLine line) { var icons = new List(); foreach (var glyphTag in GetGlyphTags(line)) { - Debug2.Assert(!(glyphTag is null)); + Debug2.Assert(glyphTag is not null); if (glyphTag is null) continue; // Fails if someone forgot to Export(typeof(HexGlyphFactoryProvider)) with the correct tag types @@ -352,7 +352,7 @@ List CreateIconInfos(WpfHexViewLine line) { } IEnumerable GetGlyphTags(WpfHexViewLine line) { - Debug2.Assert(!(tagAggregator is null)); + Debug2.Assert(tagAggregator is not null); foreach (var tagSpan in tagAggregator.GetTags(line.BufferSpan)) { if (line.IntersectsBufferSpan(tagSpan.Span)) yield return tagSpan.Tag; @@ -392,7 +392,7 @@ void Update(HexBufferSpan span, ref HashSet? checkedLines) { } void Update(WpfHexViewLine line) { - Debug2.Assert(!(lineInfos is null)); + Debug2.Assert(lineInfos is not null); Debug.Assert(line.VisibilityState != VSTF.VisibilityState.Unattached); if (!lineInfos.TryGetValue(line.IdentityTag, out var info)) return; @@ -426,8 +426,8 @@ void RegisterEvents() { return; if (wpfHexViewHost.IsClosed) return; - Debug2.Assert(!(editorFormatMap is null)); - Debug2.Assert(!(tagAggregator is null)); + Debug2.Assert(editorFormatMap is not null); + Debug2.Assert(tagAggregator is not null); hasRegisteredEvents = true; editorFormatMap.FormatMappingChanged += EditorFormatMap_FormatMappingChanged; tagAggregator.BatchedTagsChanged += TagAggregator_BatchedTagsChanged; @@ -436,9 +436,9 @@ void RegisterEvents() { void UnregisterEvents() { hasRegisteredEvents = false; - if (!(editorFormatMap is null)) + if (editorFormatMap is not null) editorFormatMap.FormatMappingChanged -= EditorFormatMap_FormatMappingChanged; - if (!(tagAggregator is null)) + if (tagAggregator is not null) tagAggregator.BatchedTagsChanged -= TagAggregator_BatchedTagsChanged; wpfHexViewHost.HexView.LayoutChanged -= HexView_LayoutChanged; } diff --git a/dnSpy/dnSpy/Hex/Editor/HexIntraTextAdornmentService.cs b/dnSpy/dnSpy/Hex/Editor/HexIntraTextAdornmentService.cs index 4871e394bd..be3dc36f6e 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexIntraTextAdornmentService.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexIntraTextAdornmentService.cs @@ -46,7 +46,7 @@ sealed class IntraTextAdornmentServiceSpaceNegotiatingAdornmentTaggerProvider : if (hexView.Buffer != buffer) return null; var wpfHexView = hexView as WpfHexView; - Debug2.Assert(!(wpfHexView is null)); + Debug2.Assert(wpfHexView is not null); if (wpfHexView is null) return null; return wpfHexView.Properties.GetOrCreateSingletonProperty( @@ -158,14 +158,14 @@ bool IsSelected(AdornmentTagInfo adornmentInfo, HexViewLine? line) { return false; if (wpfHexView.Selection.IsEmpty) return false; - if (!(adornmentInfo.HexTagSpan is null)) { + if (adornmentInfo.HexTagSpan is not null) { foreach (var span in wpfHexView.Selection.SelectedSpans) { if (span.Contains(adornmentInfo.BufferSpan)) return true; } } else { - Debug2.Assert(!(adornmentInfo.HexTextTagSpan is null)); + Debug2.Assert(adornmentInfo.HexTextTagSpan is not null); foreach (var span in wpfHexView.Selection.GetSelectionOnHexViewLine(line)) { if (span.Contains(adornmentInfo.HexTextTagSpan.Span)) return true; @@ -180,7 +180,7 @@ sealed class AdornmentTagInfo { public ZoomingUIElement? TopUIElement; public object? LineIdentityTag; - // The full buffer line span if !(HexTextTagSpan is null), else it's an accurate span + // The full buffer line span if HexTextTagSpan is not null, else it's an accurate span public readonly HexBufferSpan BufferSpan; // Mutually exclusive with HexTextTagSpan public readonly IHexTagSpan? HexTagSpan; @@ -208,7 +208,7 @@ public void Initialize() { void WpfHexView_LayoutChanged(object? sender, HexViewLayoutChangedEventArgs e) { if (adornmentTagInfos.Count > 0) { - Debug2.Assert(!(layer is null)); + Debug2.Assert(layer is not null); currentLineIdentityTags.Clear(); foreach (var line in wpfHexView.HexViewLines) currentLineIdentityTags.Add(line.IdentityTag); @@ -228,11 +228,11 @@ void WpfHexView_LayoutChanged(object? sender, HexViewLayoutChangedEventArgs e) { foreach (var identityTag in tags) { var adornmentInfo = identityTag as AdornmentTagInfo; - Debug2.Assert(!(adornmentInfo is null)); + Debug2.Assert(adornmentInfo is not null); if (adornmentInfo is null) continue; var bounds = line.GetAdornmentBounds(identityTag); - Debug2.Assert(!(bounds is null)); + Debug2.Assert(bounds is not null); if (bounds is null) continue; @@ -249,7 +249,7 @@ void WpfHexView_LayoutChanged(object? sender, HexViewLayoutChangedEventArgs e) { foreach (var identityTag in tags) { var adornmentInfo = identityTag as AdornmentTagInfo; - Debug2.Assert(!(adornmentInfo is null)); + Debug2.Assert(adornmentInfo is not null); if (adornmentInfo is null) continue; var bounds = line.GetAdornmentBounds(identityTag); @@ -274,7 +274,7 @@ void WpfHexView_LayoutChanged(object? sender, HexViewLayoutChangedEventArgs e) { } void UpdateAdornmentUIState(HexViewLine line, AdornmentTagInfo adornmentInfo, VSTF.TextBounds bounds) { - Debug2.Assert(!(adornmentInfo.TopUIElement is null)); + Debug2.Assert(adornmentInfo.TopUIElement is not null); double verticalScale = line.LineTransform.VerticalScale; adornmentInfo.TopUIElement.SetScale(verticalScale); Canvas.SetTop(adornmentInfo.TopUIElement, bounds.TextTop + line.Baseline - verticalScale * adornmentInfo.Tag!.Baseline); @@ -282,8 +282,8 @@ void UpdateAdornmentUIState(HexViewLine line, AdornmentTagInfo adornmentInfo, VS } bool AddAdornment(AdornmentTagInfo adornmentInfo, HexViewLine line) { - Debug2.Assert(!(adornmentInfo.TopUIElement is null)); - Debug2.Assert(!(layer is null)); + Debug2.Assert(adornmentInfo.TopUIElement is not null); + Debug2.Assert(layer is not null); SizeChangedEventHandler sizeChanged = (a, e) => { var bounds = line.GetAdornmentBounds(adornmentInfo); @@ -301,10 +301,10 @@ bool AddAdornment(AdornmentTagInfo adornmentInfo, HexViewLine line) { adornmentTagInfos.Remove(adornmentInfo); adornmentInfo.TopUIElement.SizeChanged -= sizeChanged; adornmentInfo.TopUIElement.OnRemoved(); - if (!(adornmentInfo.HexTagSpan is null)) + if (adornmentInfo.HexTagSpan is not null) adornmentInfo.HexTagSpan.Tag.RemovalCallback?.Invoke(adornmentInfo.HexTagSpan, b); else { - Debug2.Assert(!(adornmentInfo.HexTextTagSpan is null)); + Debug2.Assert(adornmentInfo.HexTextTagSpan is not null); adornmentInfo.HexTextTagSpan.Tag.RemovalCallback?.Invoke(adornmentInfo.HexTextTagSpan, b); } }; @@ -330,7 +330,7 @@ public void SetScale(double value) => } public override void RegisterTagger(IIntraTextAdornmentServiceSpaceNegotiatingAdornmentTagger tagger) { - if (!(this.tagger is null)) + if (this.tagger is not null) throw new InvalidOperationException(); this.tagger = tagger ?? throw new ArgumentNullException(nameof(tagger)); } diff --git a/dnSpy/dnSpy/Hex/Editor/HexKeyProcessorCollection.cs b/dnSpy/dnSpy/Hex/Editor/HexKeyProcessorCollection.cs index a5605ae756..78f91365f4 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexKeyProcessorCollection.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexKeyProcessorCollection.cs @@ -141,7 +141,7 @@ void Reinitialize() { if (!wpfHexView.Roles.ContainsAny(provider.Metadata.TextViewRoles)) continue; var keyProcessor = provider.Value.GetAssociatedProcessor(wpfHexView); - if (!(keyProcessor is null)) + if (keyProcessor is not null) list.Add(keyProcessor); } keyProcessors = list.ToArray(); diff --git a/dnSpy/dnSpy/Hex/Editor/HexMarginContextMenuServiceImpl.cs b/dnSpy/dnSpy/Hex/Editor/HexMarginContextMenuServiceImpl.cs index d3d69f0896..bc1f70ce90 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexMarginContextMenuServiceImpl.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexMarginContextMenuServiceImpl.cs @@ -50,16 +50,16 @@ public GuidObjectsProvider(WpfHexViewHost wpfHexViewHost, WpfHexViewMargin margi } void InitializeHandlers() { - if (!(handlers is null)) + if (handlers is not null) return; var list = new List(marginContextMenuHandlerProviders.Length); foreach (var lazy in marginContextMenuHandlerProviders) { if (!StringComparer.OrdinalIgnoreCase.Equals(lazy.Metadata.MarginName, marginName)) continue; - if (!(lazy.Metadata.TextViewRoles is null) && !wpfHexViewHost.HexView.Roles.ContainsAny(lazy.Metadata.TextViewRoles)) + if (lazy.Metadata.TextViewRoles is not null && !wpfHexViewHost.HexView.Roles.ContainsAny(lazy.Metadata.TextViewRoles)) continue; var handler = lazy.Value.Create(wpfHexViewHost, margin); - if (!(handler is null)) + if (handler is not null) list.Add(handler); } handlers = list.ToArray(); @@ -68,7 +68,7 @@ void InitializeHandlers() { public IEnumerable GetGuidObjects(GuidObjectsProviderArgs args) { if (handlers is null) InitializeHandlers(); - Debug2.Assert(!(handlers is null)); + Debug2.Assert(handlers is not null); var point = Mouse.PrimaryDevice.GetPosition(margin.VisualElement); diff --git a/dnSpy/dnSpy/Hex/Editor/HexMarkerService.cs b/dnSpy/dnSpy/Hex/Editor/HexMarkerService.cs index a0681e901a..b257f8859c 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexMarkerService.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexMarkerService.cs @@ -202,13 +202,13 @@ void TagAggregator_BatchedTagsChanged(object? sender, HexBatchedTagsChangedEvent List? intersectionSpans = null; foreach (var span in e.Spans) { var intersection = wpfHexView.HexViewLines.FormattedSpan.Intersection(span); - if (!(intersection is null)) { + if (intersection is not null) { if (intersectionSpans is null) intersectionSpans = new List(); intersectionSpans.Add(intersection.Value); } } - if (!(intersectionSpans is null)) + if (intersectionSpans is not null) UpdateRange(new NormalizedHexBufferSpanCollection(intersectionSpans)); } @@ -246,8 +246,8 @@ void AddMarkerElements(NormalizedHexBufferSpanCollection spans) { var pos = overlap.Value.Start; for (;;) { var line = wpfHexView.WpfHexViewLines.GetWpfHexViewLineContainingBufferPosition(pos); - Debug2.Assert(!(line is null)); - if (!(line is null)) { + Debug2.Assert(line is not null); + if (line is not null) { var taggerContext = new HexTaggerContext(line.BufferLine, line.BufferLine.TextSpan); foreach (var tag in tagAggregator.GetLineTags(taggerContext)) { if (tag.Tag?.Type is null) @@ -261,7 +261,7 @@ void AddMarkerElements(NormalizedHexBufferSpanCollection spans) { markerElements.Add(markerElement); } } - Debug2.Assert(!(line is null)); + Debug2.Assert(line is not null); pos = line.BufferEnd; if (pos > overlap.Value.End || pos >= formattedEnd) @@ -340,7 +340,7 @@ Brush GetBackgroundBrush(ResourceDictionary props) { newPen = new Pen(scBrush, PEN_THICKNESS); newPen.Freeze(); } - else if (!((newPen = props[VSTC.MarkerFormatDefinition.BorderId] as Pen) is null)) { + else if ((newPen = props[VSTC.MarkerFormatDefinition.BorderId] as Pen) is not null) { if (newPen.CanFreeze) newPen.Freeze(); } @@ -349,7 +349,7 @@ Brush GetBackgroundBrush(ResourceDictionary props) { } MarkerElement? TryCreateMarkerElement(HexBufferSpan span, HexSpanSelectionFlags flags, HexMarkerTag tag) { - Debug2.Assert(!(tag.Type is null)); + Debug2.Assert(tag.Type is not null); var overlap = wpfHexView.WpfHexViewLines.FormattedSpan.Overlap(span); if (overlap is null) return null; @@ -357,7 +357,7 @@ Brush GetBackgroundBrush(ResourceDictionary props) { } MarkerElement? TryCreateMarkerElement(WpfHexViewLine line, VST.Span span, HexMarkerTag tag) { - Debug2.Assert(!(tag.Type is null)); + Debug2.Assert(tag.Type is not null); return TryCreateMarkerElementCore(wpfHexView.WpfHexViewLines.GetLineMarkerGeometry(line, span), line.BufferSpan, tag); } diff --git a/dnSpy/dnSpy/Hex/Editor/HexMouseLocation.cs b/dnSpy/dnSpy/Hex/Editor/HexMouseLocation.cs index f81e26d427..0d86a9e8de 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexMouseLocation.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexMouseLocation.cs @@ -46,7 +46,7 @@ public static HexMouseLocation Create(WpfHexView wpfHexView, MouseEventArgs e, b var point = GetTextPoint(wpfHexView, e); var line = wpfHexView.HexViewLines.GetHexViewLineContainingYCoordinate(point.Y); - if (!(line is null)) + if (line is not null) hexViewLine = line; else if (point.Y <= wpfHexView.ViewportTop) hexViewLine = wpfHexView.HexViewLines.FirstVisibleLine; diff --git a/dnSpy/dnSpy/Hex/Editor/HexMouseProcessorCollection.cs b/dnSpy/dnSpy/Hex/Editor/HexMouseProcessorCollection.cs index 4ecc4913eb..614b587c02 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexMouseProcessorCollection.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexMouseProcessorCollection.cs @@ -53,7 +53,7 @@ public HexMouseProcessorCollection(UIElement mouseElement, UIElement? manipulati mouseElement.AddHandler(UIElement.DragOverEvent, new DragEventHandler(MouseElement_DragOver), true); mouseElement.AddHandler(UIElement.DragLeaveEvent, new DragEventHandler(MouseElement_DragLeave), true); mouseElement.AddHandler(UIElement.DragEnterEvent, new DragEventHandler(MouseElement_DragEnter), true); - if (!(manipulationElement is null)) { + if (manipulationElement is not null) { manipulationElement.AddHandler(UIElement.TouchUpEvent, new EventHandler(ManipulationElement_TouchUp), true); manipulationElement.AddHandler(UIElement.TouchDownEvent, new EventHandler(ManipulationElement_TouchDown), true); manipulationElement.AddHandler(UIElement.StylusSystemGestureEvent, new StylusSystemGestureEventHandler(ManipulationElement_StylusSystemGesture), true); @@ -393,7 +393,7 @@ public void Dispose() { mouseElement.RemoveHandler(UIElement.DragOverEvent, new DragEventHandler(MouseElement_DragOver)); mouseElement.RemoveHandler(UIElement.DragLeaveEvent, new DragEventHandler(MouseElement_DragLeave)); mouseElement.RemoveHandler(UIElement.DragEnterEvent, new DragEventHandler(MouseElement_DragEnter)); - if (!(manipulationElement is null)) { + if (manipulationElement is not null) { manipulationElement.RemoveHandler(UIElement.TouchUpEvent, new EventHandler(ManipulationElement_TouchUp)); manipulationElement.RemoveHandler(UIElement.TouchDownEvent, new EventHandler(ManipulationElement_TouchDown)); manipulationElement.RemoveHandler(UIElement.StylusSystemGestureEvent, new StylusSystemGestureEventHandler(ManipulationElement_StylusSystemGesture)); diff --git a/dnSpy/dnSpy/Hex/Editor/HexPopupSpaceReservationAgent.cs b/dnSpy/dnSpy/Hex/Editor/HexPopupSpaceReservationAgent.cs index 4d2b667412..41a127d067 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexPopupSpaceReservationAgent.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexPopupSpaceReservationAgent.cs @@ -33,7 +33,7 @@ You should have received a copy of the GNU General Public License namespace dnSpy.Hex.Editor { sealed class HexPopupSpaceReservationAgent : HexSpaceReservationAgent { - bool IsVisible => !(popup.Child is null); + bool IsVisible => popup.Child is not null; public override bool HasFocus => IsVisible && popup.IsKeyboardFocusWithin; public override bool IsMouseOver => IsVisible && popup.IsMouseOver; public override event EventHandler? GotFocus; @@ -344,7 +344,7 @@ void AddEvents() { if (content is FrameworkElement fwElem) fwElem.SizeChanged += Content_SizeChanged; var window = Window.GetWindow(wpfHexView.VisualElement); - if (!(window is null)) + if (window is not null) window.LocationChanged += Window_LocationChanged; content.GotFocus += Content_GotFocus; content.LostFocus += Content_LostFocus; @@ -360,7 +360,7 @@ void RemoveEvents() { if (content is FrameworkElement fwElem) fwElem.SizeChanged -= Content_SizeChanged; var window = Window.GetWindow(wpfHexView.VisualElement); - if (!(window is null)) + if (window is not null) window.LocationChanged -= Window_LocationChanged; content.GotFocus -= Content_GotFocus; content.LostFocus -= Content_LostFocus; diff --git a/dnSpy/dnSpy/Hex/Editor/HexSelectionImpl.cs b/dnSpy/dnSpy/Hex/Editor/HexSelectionImpl.cs index 3c2726ca07..6012051d6e 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexSelectionImpl.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexSelectionImpl.cs @@ -143,7 +143,7 @@ public override void Select(HexBufferPoint anchorPoint, HexBufferPoint activePoi if (anchorPoint < activePoint) { var anchorCell = GetCell(bufferLines, anchorPoint); var activeCell = GetCell(bufferLines, activePoint - 1); - if (!(anchorCell is null) && !(activeCell is null)) { + if (anchorCell is not null && activeCell is not null) { anchorPoint = anchorCell.BufferStart; activePoint = activeCell.BufferEnd; } @@ -151,7 +151,7 @@ public override void Select(HexBufferPoint anchorPoint, HexBufferPoint activePoi else { var activeCell = GetCell(bufferLines, activePoint); var anchorCell = GetCell(bufferLines, anchorPoint - 1); - if (!(anchorCell is null) && !(activeCell is null)) { + if (anchorCell is not null && activeCell is not null) { activePoint = activeCell.BufferStart; anchorPoint = anchorCell.BufferEnd; } diff --git a/dnSpy/dnSpy/Hex/Editor/HexSelectionLayer.cs b/dnSpy/dnSpy/Hex/Editor/HexSelectionLayer.cs index f1f2f4833b..5ce6c5a0a0 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexSelectionLayer.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexSelectionLayer.cs @@ -65,7 +65,7 @@ void UpdateBackgroundBrush() { if (TWPF.BrushComparer.Equals(newBackgroundBrush, backgroundBrush)) return; backgroundBrush = newBackgroundBrush; - if (!(markerElement is null)) + if (markerElement is not null) markerElement.BackgroundBrush = backgroundBrush; } Brush? backgroundBrush; diff --git a/dnSpy/dnSpy/Hex/Editor/HexSpaceReservationStackImpl.cs b/dnSpy/dnSpy/Hex/Editor/HexSpaceReservationStackImpl.cs index 1b96c00243..d747d62673 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexSpaceReservationStackImpl.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexSpaceReservationStackImpl.cs @@ -42,7 +42,7 @@ public override bool IsMouseOver { IEnumerable SpaceReservationManagers { get { foreach (var mgr in spaceReservationManagers) { - if (!(mgr is null)) + if (mgr is not null) yield return mgr; } } @@ -124,7 +124,7 @@ void WpfHexView_Closed(object? sender, EventArgs e) { wpfHexView.Closed -= WpfHexView_Closed; for (int i = 0; i < spaceReservationManagers.Length; i++) { var mgr = spaceReservationManagers[i]; - if (!(mgr is null)) { + if (mgr is not null) { spaceReservationManagers[i] = null; mgr.GotAggregateFocus -= HexSpaceReservationManager_GotAggregateFocus; mgr.LostAggregateFocus -= HexSpaceReservationManager_LostAggregateFocus; diff --git a/dnSpy/dnSpy/Hex/Editor/HexStructureInfoAggregatorFactoryImpl.cs b/dnSpy/dnSpy/Hex/Editor/HexStructureInfoAggregatorFactoryImpl.cs index 2e23367c55..ea6820ef70 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexStructureInfoAggregatorFactoryImpl.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexStructureInfoAggregatorFactoryImpl.cs @@ -39,7 +39,7 @@ public override HexStructureInfoAggregator Create(HexView hexView) { var list = new List(hexStructureInfoProviderFactories.Length); foreach (var lz in hexStructureInfoProviderFactories) { var provider = lz.Value.Create(hexView); - if (!(provider is null)) + if (provider is not null) list.Add(provider); } return new HexStructureInfoAggregatorImpl(list.ToArray()); diff --git a/dnSpy/dnSpy/Hex/Editor/HexViewMouseProcessorCollection.cs b/dnSpy/dnSpy/Hex/Editor/HexViewMouseProcessorCollection.cs index 1e763557dc..a9c9497cbe 100644 --- a/dnSpy/dnSpy/Hex/Editor/HexViewMouseProcessorCollection.cs +++ b/dnSpy/dnSpy/Hex/Editor/HexViewMouseProcessorCollection.cs @@ -45,7 +45,7 @@ public HexViewMouseProcessorCollection(WpfHexView wpfHexView, HexEditorOperation } bool AllowMouseEvent(MouseEventArgs e) { - if (!(wpfHexViewImpl is null) && wpfHexViewImpl.IsMouseOverOverlayLayerElement(e)) { + if (wpfHexViewImpl is not null && wpfHexViewImpl.IsMouseOverOverlayLayerElement(e)) { e.Handled = true; return false; } @@ -59,7 +59,7 @@ void Reinitialize() { if (!wpfHexView.Roles.ContainsAny(provider.Metadata.TextViewRoles)) continue; var mouseProcessor = provider.Value.GetAssociatedProcessor(wpfHexView); - if (!(mouseProcessor is null)) + if (mouseProcessor is not null) list.Add(mouseProcessor); } UIElement? manipulationElem = null;//TODO: diff --git a/dnSpy/dnSpy/Hex/Editor/Search/HexSearchServiceFactory.cs b/dnSpy/dnSpy/Hex/Editor/Search/HexSearchServiceFactory.cs index b5fae4aa45..b1302ba24f 100644 --- a/dnSpy/dnSpy/Hex/Editor/Search/HexSearchServiceFactory.cs +++ b/dnSpy/dnSpy/Hex/Editor/Search/HexSearchServiceFactory.cs @@ -56,7 +56,7 @@ public override bool IsSearchDataValid(HexDataKind dataKind, string searchString case HexDataKind.UInt64: case HexDataKind.Single: case HexDataKind.Double: - return !(DataParser.TryParseData(searchString, dataKind, isBigEndian) is null); + return DataParser.TryParseData(searchString, dataKind, isBigEndian) is not null; default: throw new InvalidOperationException(); diff --git a/dnSpy/dnSpy/Hex/Editor/Search/HexViewSearchService.cs b/dnSpy/dnSpy/Hex/Editor/Search/HexViewSearchService.cs index 76d8c2a4af..29cbf76b1f 100644 --- a/dnSpy/dnSpy/Hex/Editor/Search/HexViewSearchService.cs +++ b/dnSpy/dnSpy/Hex/Editor/Search/HexViewSearchService.cs @@ -279,7 +279,7 @@ public override CommandTargetStatus CanExecuteSearchControl(Guid group, int cmdI return CommandTargetStatus.NotHandled; if (!IsSearchControlVisible) return CommandTargetStatus.NotHandled; - Debug2.Assert(!(searchControl is null)); + Debug2.Assert(searchControl is not null); if (inIncrementalSearch) { if (group == CommandConstants.HexEditorGroup) { @@ -315,7 +315,7 @@ public override CommandTargetStatus ExecuteSearchControl(Guid group, int cmdId, return CommandTargetStatus.NotHandled; if (!IsSearchControlVisible) return CommandTargetStatus.NotHandled; - Debug2.Assert(!(searchControl is null)); + Debug2.Assert(searchControl is not null); if (group == CommandConstants.HexEditorGroup && cmdId == (int)HexEditorIds.CANCEL) { if (inIncrementalSearch) @@ -334,7 +334,7 @@ public override CommandTargetStatus ExecuteSearchControl(Guid group, int cmdId, case HexEditorIds.TYPECHAR: var s = args as string; - if (!(s is null) && s.IndexOfAny(CT.LineConstants.newLineChars) < 0) + if (s is not null && s.IndexOfAny(CT.LineConstants.newLineChars) < 0) SetIncrementalSearchString(SearchString + s); else CancelIncrementalSearch(); @@ -389,7 +389,7 @@ void SetIncrementalSearchString(string newSearchString) { } bool isIncrementalSearchCaretMove; - bool IsSearchControlVisible => !(layer is null) && !layer.IsEmpty; + bool IsSearchControlVisible => layer is not null && !layer.IsEmpty; void UseGlobalSettingsIfUiIsHidden(bool canOverwriteSearchString) { if (!IsSearchControlVisible) @@ -466,7 +466,7 @@ void ShowSearchControl(SearchKind searchKind, bool canOverwriteSearchString) { static void SelectAllWhenFocused(TextBox textBox) => textBox.GotKeyboardFocus += (s, e) => textBox.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => textBox.SelectAll())); - public bool HasSearchControlFocus => !(searchControl is null) && searchControl.IsKeyboardFocusWithin; + public bool HasSearchControlFocus => searchControl is not null && searchControl.IsKeyboardFocusWithin; void SearchControl_LostKeyboardFocus(object? sender, KeyboardFocusChangedEventArgs e) => OnPropertyChanged(nameof(HasSearchControlFocus)); void SearchControl_GotKeyboardFocus(object? sender, KeyboardFocusChangedEventArgs e) { CloseSearchControlIfIncrementalSearch(); @@ -525,7 +525,7 @@ void Caret_PositionChanged(object? sender, HexCaretPositionChangedEventArgs e) { } void FocusSearchStringTextBox() { - Debug2.Assert(!(searchControl is null)); + Debug2.Assert(searchControl is not null); Action? callback = null; // If it hasn't been loaded yet, it has no binding and we must select it in its Loaded event if (searchControl.searchStringTextBox.Text.Length == 0 && SearchString.Length != 0) @@ -536,7 +536,7 @@ void FocusSearchStringTextBox() { } void FocusReplaceStringTextBox() { - Debug2.Assert(!(searchControl is null)); + Debug2.Assert(searchControl is not null); Action? callback = null; // If it hasn't been loaded yet, it has no binding and we must select it in its Loaded event if (searchControl.replaceStringTextBox.Text.Length == 0 && ReplaceString.Length != 0) @@ -547,7 +547,7 @@ void FocusReplaceStringTextBox() { } void RepositionControl(bool recalcSize = false) { - Debug2.Assert(!(searchControl is null)); + Debug2.Assert(searchControl is not null); if (recalcSize) searchControl.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); PositionSearchControl(SearchControlPosition.Default); @@ -712,7 +712,7 @@ static char ToHexChar(int val, bool upper) { void UpdateSearchStringFromCaretPosition(bool canSearch) { var newSearchString = TryGetSearchStringAtCaret(); - if (!(newSearchString is null)) + if (newSearchString is not null) SetSearchString(newSearchString, canSearch); } @@ -775,7 +775,7 @@ HexBufferPoint GetNextSearchPosition(HexBufferSpan span, bool forward) { } } - bool IsReplaceStringValid() => !(DataParser.TryParseData(ReplaceString, DataKind, IsBigEndian) is null); + bool IsReplaceStringValid() => DataParser.TryParseData(ReplaceString, DataKind, IsBigEndian) is not null; byte[]? TryGetReplaceStringData(HexBufferSpan replaceSpan) { var data = DataParser.TryParseData(ReplaceString, DataKind, IsBigEndian); @@ -804,7 +804,7 @@ void ReplaceNext() { if (!wpfHexView.Selection.IsEmpty && wpfHexView.Selection.StreamSelectionSpan == vres) { try { var newData = TryGetReplaceStringData(res.Value); - Debug2.Assert(!(newData is null) && newData.Length == res.Value.Length); + Debug2.Assert(newData is not null && newData.Length == res.Value.Length); if (newData is null || newData.Length != res.Value.Length) return; @@ -872,7 +872,7 @@ void ReplaceAll() { foreach (var res in GetAllResultsForReplaceAll()) { if (newData is null) newData = TryGetReplaceStringData(res); - Debug2.Assert(!(newData is null) && newData.Length == res.Length); + Debug2.Assert(newData is not null && newData.Length == res.Length); if (newData is null || newData.Length != res.Length) return; // Ignore errors due to read-only regions @@ -1005,7 +1005,7 @@ void FindNextCore(OurFindOptions options, HexBufferPoint? startingPosition, bool if (findAsyncSearcher != findAsyncSearcherTmp) return; CancelFindAsyncSearcher(); - if (!(foundSpan is null)) { + if (foundSpan is not null) { try { isIncrementalSearchCaretMove = isIncrementalSearch; ShowSearchResult(foundSpan.Value); @@ -1210,15 +1210,15 @@ void UpdateHexMarkerSearch() { IAsyncSearcher? searcher = null; searcher = FindAsync(searchOptions, (result, foundSpan) => { if (result == FindAsyncResult.InvalidSearchOptions) { - bool refresh = !(hexMarkerSearchService is null); + bool refresh = hexMarkerSearchService is not null; hexMarkerSearchService = null; if (refresh) RefreshAllTags(); // We could be here if the input string is invalid, in which case we tell the user there was nothing found FoundMatch = SearchString.Length == 0; } - else if (result == FindAsyncResult.HasResult && !(searcher is null) && searcher.HexSearchService == hexMarkerSearchService) { - FoundMatch = !(foundSpan is null); + else if (result == FindAsyncResult.HasResult && searcher is not null && searcher.HexSearchService == hexMarkerSearchService) { + FoundMatch = foundSpan is not null; lastMatch = foundSpan is null ? HexPosition.Zero : foundSpan.Value.Span.Start; } }); diff --git a/dnSpy/dnSpy/Hex/Editor/WpfHexViewContainerMargin.cs b/dnSpy/dnSpy/Hex/Editor/WpfHexViewContainerMargin.cs index db8a3a83bb..46965bcf2e 100644 --- a/dnSpy/dnSpy/Hex/Editor/WpfHexViewContainerMargin.cs +++ b/dnSpy/dnSpy/Hex/Editor/WpfHexViewContainerMargin.cs @@ -89,7 +89,7 @@ void UpdateMarginChildren() { foreach (var info in margins) { var margin = info.Margin.GetHexViewMargin(marginName); - if (!(margin is null)) + if (margin is not null) return margin; } diff --git a/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.LayoutHelper.cs b/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.LayoutHelper.cs index 0bbbd26c02..afa0cabc59 100644 --- a/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.LayoutHelper.cs +++ b/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.LayoutHelper.cs @@ -94,11 +94,11 @@ public void LayoutLines(HexBufferPoint bufferPosition, VSTE.ViewRelativePosition // just like in VS' WpfHexViewLine collection. var firstInfo = infos[0]; var prevLine = AddLineTransform(GetLineBefore(firstInfo.Line), firstInfo.Y, VSTE.ViewRelativePosition.Bottom); - if (!(prevLine is null)) + if (prevLine is not null) infos.Insert(0, new LineInfo(prevLine, firstInfo.Y - prevLine.Height)); var lastInfo = infos[infos.Count - 1]; var nextLine = AddLineTransform(GetLineAfter(lastInfo.Line), lastInfo.Y + lastInfo.Line.Height, VSTE.ViewRelativePosition.Top); - if (!(nextLine is null)) + if (nextLine is not null) infos.Add(new LineInfo(nextLine, lastInfo.Y + lastInfo.Line.Height)); var keptLines = new HashSet(); @@ -162,7 +162,7 @@ public void LayoutLines(HexBufferPoint bufferPosition, VSTE.ViewRelativePosition List CreateLineInfos(HexBufferPoint bufferPosition, VSTE.ViewRelativePosition relativeTo, double verticalDistance, double viewportHeightOverride) { var lineInfos = new List(); var startLine = GetLine(bufferPosition); - Debug2.Assert(!(startLine is null)); + Debug2.Assert(startLine is not null); double newViewportBottom = NewViewportTop + viewportHeightOverride; double lineStartY; @@ -218,7 +218,7 @@ List CreateLineInfos(HexBufferPoint bufferPosition, VSTE.ViewRelativeP } HexFormattedLine? AddLineTransform(HexFormattedLine? line, double yPosition, VSTE.ViewRelativePosition placement) { - if (!(line is null)) { + if (line is not null) { var lineTransform = lineTransformProvider.GetLineTransform(line, yPosition, placement); if (lineTransform != line.LineTransform) { line.SetLineTransform(lineTransform); diff --git a/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.MouseHoverHelper.cs b/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.MouseHoverHelper.cs index 5249f7ff81..352003c796 100644 --- a/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.MouseHoverHelper.cs +++ b/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.MouseHoverHelper.cs @@ -152,9 +152,9 @@ void Timer_Tick(object? sender, EventArgs e) { ClearMouseHoverPositionAndStopTimer(); return; } - Debug2.Assert(!(timerStart is null)); + Debug2.Assert(timerStart is not null); var list = GetHandlersToNotify(); - if (!(list is null)) { + if (list is not null) { var mhe = new HexMouseHoverEventArgs(owner, position.Value.Line, position.Value.Column); foreach (var h in list) { h.Raised = true; diff --git a/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.cs b/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.cs index b0025c7af2..c2f95c38f8 100644 --- a/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.cs +++ b/dnSpy/dnSpy/Hex/Editor/WpfHexViewImpl.cs @@ -270,12 +270,12 @@ public Cursor Cursor { double priority = double.NegativeInfinity; foreach (var providerInfo in providerInfos) { var info = providerInfo.CursorInfo; - if (!(info.Cursor is null) && info.Priority > priority) { + if (info.Cursor is not null && info.Priority > priority) { cursor = info.Cursor; priority = info.Priority; } } - Debug2.Assert(!(cursor is null)); + Debug2.Assert(cursor is not null); return cursor ?? defaultCursor; } } @@ -292,7 +292,7 @@ public HexCursorProviderInfoCollection(HexCursorProvider[] hexCursorProviders, C void Provider_CursorInfoChanged(object? sender, EventArgs e) { var providerInfo = providerInfos.FirstOrDefault(a => a.Provider == sender); - Debug2.Assert(!(providerInfo is null)); + Debug2.Assert(providerInfo is not null); if (providerInfo is null) return; providerInfo.CursorInfo = providerInfo.Provider.CursorInfo; @@ -315,7 +315,7 @@ HexCursorProvider[] CreateCursorProviders(Lazy 0) @@ -677,7 +677,7 @@ public override void Close() { spaceReservationStack.LostAggregateFocus -= SpaceReservationStack_LostAggregateFocus; hexCursorProviderInfoCollection.CursorChanged -= HexCursorProviderInfoCollection_CursorChanged; hexCursorProviderInfoCollection.Dispose(); - if (!(metroWindow is null)) + if (metroWindow is not null) metroWindow.WindowDpiChanged -= MetroWindow_WindowDpiChanged; } @@ -729,12 +729,12 @@ public override WpfHexViewLine GetWpfHexViewLineContainingBufferPosition(HexBuff foreach (var pline in visiblePhysicalLines) { var lline = pline.FindFormattedLineByBufferPosition(bufferPosition); - if (!(lline is null)) + if (lline is not null) return lline; } var cachedLine = physicalLineCache.FindFormattedLineByBufferPosition(bufferPosition); - if (!(cachedLine is null)) + if (cachedLine is not null) return cachedLine; var physLine = CreatePhysicalLineNoCache(bufferPosition, ViewportWidth); @@ -768,7 +768,7 @@ void DisplayLines(HexBufferPoint bufferPosition, double verticalDistance, VSTE.V throw new InvalidOperationException(); var oldBufferLines = hexBufferLineFormatter; var oldHexBufferLineFormatterOptions = hexBufferLineFormatterOptions; - Debug2.Assert(!(oldBufferLines is null)); + Debug2.Assert(oldBufferLines is not null); bool raiseBufferLinesChangedEvent = false; bool revalidateBufferPosition = false; @@ -848,10 +848,10 @@ void DisplayLines(HexBufferPoint bufferPosition, double verticalDistance, VSTE.V } } layoutHelper.LayoutLines(bufferPosition, relativeTo, verticalDistance, ViewportLeft, viewportWidthOverride, viewportHeightOverride); - Debug2.Assert(!(layoutHelper.AllVisibleLines is null)); - Debug2.Assert(!(layoutHelper.NewOrReformattedLines is null)); - Debug2.Assert(!(layoutHelper.TranslatedLines is null)); - Debug2.Assert(!(layoutHelper.AllVisiblePhysicalLines is null)); + Debug2.Assert(layoutHelper.AllVisibleLines is not null); + Debug2.Assert(layoutHelper.NewOrReformattedLines is not null); + Debug2.Assert(layoutHelper.TranslatedLines is not null); + Debug2.Assert(layoutHelper.AllVisiblePhysicalLines is not null); visiblePhysicalLines.AddRange(layoutHelper.AllVisiblePhysicalLines); wpfHexViewLineCollection = new WpfHexViewLineCollectionImpl(this, layoutHelper.AllVisibleLines); @@ -997,9 +997,9 @@ void UpdateVisibleLines(double viewportWidthOverride, double ViewportHeightOverr void InitializeZoom() { var window = Window.GetWindow(canvas); metroWindow = window as MetroWindow; - if (!(window is null) && metroWindow is null) + if (window is not null && metroWindow is null) return; - if (!(metroWindow is null)) { + if (metroWindow is not null) { metroWindow.WindowDpiChanged += MetroWindow_WindowDpiChanged; MetroWindow_WindowDpiChanged(metroWindow, EventArgs.Empty); ZoomLevelChanged?.Invoke(this, new VSTE.ZoomLevelChangedEventArgs(ZoomLevel, canvas.LayoutTransform)); @@ -1014,8 +1014,8 @@ void WpfHexView_Loaded(object? sender, RoutedEventArgs e) { canvas.Loaded -= WpfHexView_Loaded; var window = Window.GetWindow(canvas); metroWindow = window as MetroWindow; - Debug2.Assert(!(window is null)); - if (!(metroWindow is null)) { + Debug2.Assert(window is not null); + if (metroWindow is not null) { metroWindow.WindowDpiChanged += MetroWindow_WindowDpiChanged; MetroWindow_WindowDpiChanged(metroWindow, EventArgs.Empty); ZoomLevelChanged?.Invoke(this, new VSTE.ZoomLevelChangedEventArgs(ZoomLevel, canvas.LayoutTransform)); @@ -1024,7 +1024,7 @@ void WpfHexView_Loaded(object? sender, RoutedEventArgs e) { } void MetroWindow_WindowDpiChanged(object? sender, EventArgs e) { - Debug2.Assert(!(sender is null) && sender == metroWindow); + Debug2.Assert(sender is not null && sender == metroWindow); ((MetroWindow)sender).SetScaleTransform(canvas, ZoomLevel / 100); } @@ -1034,7 +1034,7 @@ HexLineTransformProvider LineTransformProvider { __lineTransformProvider = lineTransformProviderService.Create(this, removeExtraTextLineVerticalPixels); recreateLineTransformProvider = false; } - Debug2.Assert(!(__lineTransformProvider is null)); + Debug2.Assert(__lineTransformProvider is not null); return __lineTransformProvider; } } diff --git a/dnSpy/dnSpy/Hex/Editor/WpfHexViewLineCollectionImpl.cs b/dnSpy/dnSpy/Hex/Editor/WpfHexViewLineCollectionImpl.cs index 878bfb9572..a2f3bec6ab 100644 --- a/dnSpy/dnSpy/Hex/Editor/WpfHexViewLineCollectionImpl.cs +++ b/dnSpy/dnSpy/Hex/Editor/WpfHexViewLineCollectionImpl.cs @@ -142,7 +142,7 @@ public override bool IntersectsBufferSpan(HexBufferSpan bufferSpan) { HexMarkerHelper.AddGeometries(hexView, textBounds, isLineGeometry, clipToViewport, padding, 0, ref geo, ref createOutlinedPath); if (createOutlinedPath) geo = geo!.GetOutlinedPathGeometry(); - if (!(geo is null) && geo.CanFreeze) + if (geo is not null && geo.CanFreeze) geo.Freeze(); return geo; } @@ -167,7 +167,7 @@ public override bool IntersectsBufferSpan(HexBufferSpan bufferSpan) { HexMarkerHelper.AddGeometries(hexView, textBounds, isLineGeometry, clipToViewport, padding, 0, ref geo, ref createOutlinedPath); if (createOutlinedPath) geo = geo!.GetOutlinedPathGeometry(); - if (!(geo is null) && geo.CanFreeze) + if (geo is not null && geo.CanFreeze) geo.Freeze(); return geo; } diff --git a/dnSpy/dnSpy/Hex/Editor/WpfHexViewMarginProviderCollectionImpl.cs b/dnSpy/dnSpy/Hex/Editor/WpfHexViewMarginProviderCollectionImpl.cs index 9282bc75c8..726faddbd2 100644 --- a/dnSpy/dnSpy/Hex/Editor/WpfHexViewMarginProviderCollectionImpl.cs +++ b/dnSpy/dnSpy/Hex/Editor/WpfHexViewMarginProviderCollectionImpl.cs @@ -86,7 +86,7 @@ void UpdateMargins() { } else { var margin = lazy.Value.CreateMargin(wpfHexViewHost, marginContainer); - if (!(margin is null)) + if (margin is not null) newInfos.Add(new WpfHexViewMarginInfo(lazy.Value, lazy.Metadata, margin)); } } diff --git a/dnSpy/dnSpy/Hex/Editor/ZoomControlMargin.cs b/dnSpy/dnSpy/Hex/Editor/ZoomControlMargin.cs index a88586a58c..0eb5962385 100644 --- a/dnSpy/dnSpy/Hex/Editor/ZoomControlMargin.cs +++ b/dnSpy/dnSpy/Hex/Editor/ZoomControlMargin.cs @@ -89,8 +89,8 @@ protected override void OnKeyDown(KeyEventArgs e) { return; } if (Keyboard.Modifiers == ModifierKeys.None && e.Key == Key.Escape) { - Debug2.Assert(!(originalZoomLevel is null)); - if (!(originalZoomLevel is null)) + Debug2.Assert(originalZoomLevel is not null); + if (originalZoomLevel is not null) HexViewZoomLevel = originalZoomLevel.Value; UpdateTextWithZoomLevel(); owner.wpfHexViewHost.HexView.VisualElement.Focus(); @@ -118,11 +118,11 @@ void ZoomControlMargin_IsVisibleChanged(object? sender, DependencyPropertyChange // The combobox is too tall, but I want to use the style from the UI.Wpf dll if (horizontalScrollBarMargin is null) { horizontalScrollBarMargin = owner.wpfHexViewHost.GetHexViewMargin(PredefinedHexMarginNames.HorizontalScrollBar); - Debug2.Assert(!(horizontalScrollBarMargin is null)); - if (!(horizontalScrollBarMargin is null)) + Debug2.Assert(horizontalScrollBarMargin is not null); + if (horizontalScrollBarMargin is not null) horizontalScrollBarMargin.VisualElement.SizeChanged += VisualElement_SizeChanged; } - if (!(horizontalScrollBarMargin is null)) + if (horizontalScrollBarMargin is not null) Height = horizontalScrollBarMargin.VisualElement.Height; } else @@ -148,7 +148,7 @@ bool TryUpdateZoomLevel() { public void Dispose() { IsVisibleChanged -= ZoomControlMargin_IsVisibleChanged; - if (!(horizontalScrollBarMargin is null)) + if (horizontalScrollBarMargin is not null) horizontalScrollBarMargin.VisualElement.SizeChanged -= VisualElement_SizeChanged; } } diff --git a/dnSpy/dnSpy/Hex/Files/DefaultHexStructureInfoProvider.cs b/dnSpy/dnSpy/Hex/Files/DefaultHexStructureInfoProvider.cs index 35728665e8..0e72d5fb07 100644 --- a/dnSpy/dnSpy/Hex/Files/DefaultHexStructureInfoProvider.cs +++ b/dnSpy/dnSpy/Hex/Files/DefaultHexStructureInfoProvider.cs @@ -65,13 +65,13 @@ public override IEnumerable GetFields(HexPosition position) { var structure = info.Value.Structure; var field = structure.GetSimpleField(position); - Debug2.Assert(!(field is null)); + Debug2.Assert(field is not null); if (field is null) yield break; yield return new HexStructureField(field.Data.Span, HexStructureFieldKind.CurrentField); var indexes = hexFileStructureInfoService.GetSubStructureIndexes(position); - if (!(indexes is null)) { + if (indexes is not null) { if (indexes.Length == 0) { for (int i = 0; i < structure.FieldCount; i++) { var span = structure.GetFieldByIndex(i).Data.Span; diff --git a/dnSpy/dnSpy/Hex/Files/DnSpy/DefaultHexFileStructureInfoProvider.cs b/dnSpy/dnSpy/Hex/Files/DnSpy/DefaultHexFileStructureInfoProvider.cs index 53dc66e723..edccb87de3 100644 --- a/dnSpy/dnSpy/Hex/Files/DnSpy/DefaultHexFileStructureInfoProvider.cs +++ b/dnSpy/dnSpy/Hex/Files/DnSpy/DefaultHexFileStructureInfoProvider.cs @@ -67,7 +67,7 @@ public DefaultHexFileStructureInfoProvider(ToolTipCreatorFactory toolTipCreatorF ImageReference GetImage(ComplexData structure, HexPosition position) { foreach (var lz in hexFileImageReferenceProviders) { var imgRef = lz.Value.GetImage(structure, position); - if (!(imgRef is null)) + if (imgRef is not null) return imgRef.Value; } return DsImages.FieldPublic; diff --git a/dnSpy/dnSpy/Hex/Files/DnSpy/DotNetHexFileStructureInfoProvider.cs b/dnSpy/dnSpy/Hex/Files/DnSpy/DotNetHexFileStructureInfoProvider.cs index f7ff8b8c0e..71401eb883 100644 --- a/dnSpy/dnSpy/Hex/Files/DnSpy/DotNetHexFileStructureInfoProvider.cs +++ b/dnSpy/dnSpy/Hex/Files/DnSpy/DotNetHexFileStructureInfoProvider.cs @@ -114,11 +114,11 @@ void WriteTokens(HexFieldFormatter writer, IList tokens) { object? GetToolTip(DotNetEmbeddedResource resource, HexPosition position) { var mdHeaders = resource.ResourceProvider.File.GetHeaders(); - Debug2.Assert(!(mdHeaders is null)); + Debug2.Assert(mdHeaders is not null); if (mdHeaders is null) return null; var rec = mdHeaders.TablesStream?.GetRecord(resource.Token); - Debug2.Assert(!(rec is null)); + Debug2.Assert(rec is not null); if (rec is null) return null; const int NameColumn = 2; @@ -266,7 +266,7 @@ ImageReference GetResourceImage(DotNetEmbeddedResource resource, string filename var mdTable = tablesHeap.MDTables[(int)tableRecord.Token.Table]; int offset = (int)(position - tableRecord.Span.Span.Start).ToUInt64(); var column = mdTable.Columns.FirstOrDefault(a => a.Offset <= offset && offset < a.Offset + a.Size); - Debug2.Assert(!(column is null)); + Debug2.Assert(column is not null); if (column is null) return null; var mdHeaders = tablesHeap.Metadata; diff --git a/dnSpy/dnSpy/Hex/Files/DnSpy/ToolTipObjectFactoryImpl.cs b/dnSpy/dnSpy/Hex/Files/DnSpy/ToolTipObjectFactoryImpl.cs index af69d2fdaa..01b4494f5f 100644 --- a/dnSpy/dnSpy/Hex/Files/DnSpy/ToolTipObjectFactoryImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/DnSpy/ToolTipObjectFactoryImpl.cs @@ -54,7 +54,7 @@ sealed class ToolTipObjectFactoryImpl : ToolTipObjectFactory { res.Children.Add(CreateTextElement(text)); } var imgRef = content.Image as ImageReference?; - if (!(imgRef is null)) { + if (imgRef is not null) { var img = new DsImage { ImageReference = imgRef.Value, Margin = new Thickness(0, 0, 4, 0), diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/BlobHeapImpl.cs b/dnSpy/dnSpy/Hex/Files/DotNet/BlobHeapImpl.cs index 94c5242b19..28ee6fa429 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/BlobHeapImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/BlobHeapImpl.cs @@ -81,7 +81,7 @@ public BlobHeapImpl(HexBufferSpan span) } void Initialize() { - if (!(blobDataInfos is null)) + if (blobDataInfos is not null) return; if (metadata is null) return; @@ -90,7 +90,7 @@ void Initialize() { public override ComplexData? GetStructure(HexPosition position) { var info = GetBlobDataInfo(position); - if (!(info is null)) + if (info is not null) return GetStructure(info.Value, position); return null; @@ -141,7 +141,7 @@ void Initialize() { var index = GetIndex(position); if (index < 0) return null; - Debug2.Assert(!(blobDataInfos is null)); + Debug2.Assert(blobDataInfos is not null); return blobDataInfos[index]; } diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetHexFileStructureInfoProvider.cs b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetHexFileStructureInfoProvider.cs index 3a7aea574b..0c78361c18 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetHexFileStructureInfoProvider.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetHexFileStructureInfoProvider.cs @@ -61,11 +61,11 @@ sealed class DotNetHexFileStructureInfoProvider : HexFileStructureInfoProvider { } var stringsRec = structure as StringsHeapRecordData; - if (!(stringsRec?.Terminator is null)) + if (stringsRec?.Terminator is not null) return stringsRecordIndexes; if (structure is USHeapRecordData usRec) { - if (!(usRec.TerminalByte is null)) + if (usRec.TerminalByte is not null) return usRecordIndexes3; return usRecordIndexes2; } @@ -147,19 +147,19 @@ sealed class DotNetHexFileStructureInfoProvider : HexFileStructureInfoProvider { HexSpan? GetFieldReferenceSpan(HexBufferFile file, DotNetCor20Data cor20, HexPosition position) { HexSpan? span; - if (!((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.Metadata.Data, position)) is null)) + if ((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.Metadata.Data, position)) is not null) return span; - if (!((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.Resources.Data, position)) is null)) + if ((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.Resources.Data, position)) is not null) return span; - if (!((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.StrongNameSignature.Data, position)) is null)) + if ((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.StrongNameSignature.Data, position)) is not null) return span; - if (!((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.CodeManagerTable.Data, position)) is null)) + if ((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.CodeManagerTable.Data, position)) is not null) return span; - if (!((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.VTableFixups.Data, position)) is null)) + if ((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.VTableFixups.Data, position)) is not null) return span; - if (!((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.ExportAddressTableJumps.Data, position)) is null)) + if ((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.ExportAddressTableJumps.Data, position)) is not null) return span; - if (!((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.ManagedNativeHeader.Data, position)) is null)) + if ((span = DataDirectoryDataUtils.TryGetSpan(file, cor20.ManagedNativeHeader.Data, position)) is not null) return span; if (cor20.EntryPointTokenOrRVA.Data.Span.Span.Contains(position)) { @@ -233,7 +233,7 @@ sealed class DotNetHexFileStructureInfoProvider : HexFileStructureInfoProvider { HexSpan? GetFieldReferenceSpan(HexBufferFile file, FatMethodBody fatBody, HexPosition position) { var ehTable = fatBody.EHTable; - if (!(ehTable is null)) { + if (ehTable is not null) { if (!ehTable.Data.Span.Span.Contains(position)) return null; @@ -245,9 +245,9 @@ sealed class DotNetHexFileStructureInfoProvider : HexFileStructureInfoProvider { if (clause is null) return null; HexSpan? span; - if (!((span = TryGetSpan(fatBody, position, clause.TryOffset.Data, clause.TryLength.Data)) is null)) + if ((span = TryGetSpan(fatBody, position, clause.TryOffset.Data, clause.TryLength.Data)) is not null) return span; - if (!((span = TryGetSpan(fatBody, position, clause.HandlerOffset.Data, clause.HandlerLength.Data)) is null)) + if ((span = TryGetSpan(fatBody, position, clause.HandlerOffset.Data, clause.HandlerLength.Data)) is not null) return span; if (clause.ClassTokenOrFilterOffset.Data.Span.Span.Contains(position)) { if (clause.Flags.Data.ReadValue() == 0) @@ -264,9 +264,9 @@ sealed class DotNetHexFileStructureInfoProvider : HexFileStructureInfoProvider { if (clause is null) return null; HexSpan? span; - if (!((span = TryGetSpan(fatBody, position, clause.TryOffset.Data, clause.TryLength.Data)) is null)) + if ((span = TryGetSpan(fatBody, position, clause.TryOffset.Data, clause.TryLength.Data)) is not null) return span; - if (!((span = TryGetSpan(fatBody, position, clause.HandlerOffset.Data, clause.HandlerLength.Data)) is null)) + if ((span = TryGetSpan(fatBody, position, clause.HandlerOffset.Data, clause.HandlerLength.Data)) is not null) return span; if (clause.ClassTokenOrFilterOffset.Data.Span.Span.Contains(position)) { if (clause.Flags.Data.ReadValue() == 0) diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMethodProviderImpl.cs b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMethodProviderImpl.cs index 39b6e4752f..3421ac1673 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMethodProviderImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMethodProviderImpl.cs @@ -108,7 +108,7 @@ MethodBodyInfo ParseMethodBody(int nextMethodIndex, IList tokens, HexPosit if (endPos < methodBodyPosition) endPos = methodBodyPosition; var info = new MethodBodyReader(File, tokens, methodBodyPosition, endPos).Read(); - if (!(info is null)) + if (info is not null) return info.Value; // The file could be obfuscated (encrypted methods), assume the method ends at the next method body RVA diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMultiFileResourceHeaderDataImpl.cs b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMultiFileResourceHeaderDataImpl.cs index 3108aab9b9..2f2f780261 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMultiFileResourceHeaderDataImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMultiFileResourceHeaderDataImpl.cs @@ -54,7 +54,7 @@ public DotNetMultiFileResourceHeaderDataImpl(HexBufferSpan span, Bit7String? res HeaderSize = new StructField("HeaderSize", new UInt32Data(buffer, pos + 8)); if (resourceTypeSpan is null) { - if (!(resourceSetTypeSpan is null)) + if (resourceSetTypeSpan is not null) throw new ArgumentException(); UnknownHeader = new StructField>("Header", ArrayData.CreateVirtualByteArray(new HexBufferSpan(buffer, HexSpan.FromBounds(pos + 0x0C, versionPosition)))); } @@ -97,11 +97,11 @@ public DotNetMultiFileResourceHeaderDataImpl(HexBufferSpan span, Bit7String? res list.Add(MagicNum); list.Add(ResMgrHeaderVersion); list.Add(HeaderSize); - if (!(UnknownHeader is null)) + if (UnknownHeader is not null) list.Add(UnknownHeader); - if (!(ReaderType is null)) + if (ReaderType is not null) list.Add(ReaderType); - if (!(ResourceSetType is null)) + if (ResourceSetType is not null) list.Add(ResourceSetType); list.Add(Version); list.Add(NumResources); diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMultiFileResourcesImpl.cs b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMultiFileResourcesImpl.cs index fbb7c40817..fe4f4da5c5 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMultiFileResourcesImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetMultiFileResourcesImpl.cs @@ -184,7 +184,7 @@ Data[] CreateDataArray(Bit7String[] typeNames, int numResources, HexPosition nam foreach (var elem in elems) { list.Add(new UnicodeNameAndOffsetData(elem, elem.UnicodeName)); - if (!(elem.ResData is null)) + if (elem.ResData is not null) list.Add(new ResourceInfoData(elem, elem.ResData.FullSpan)); } @@ -390,7 +390,7 @@ public TypeResData(ResourceTypeCode typeCode, HexSpan codeSpan, HexSpan dataSpan return Header; var data = GetData(position); - if (!(data is null)) + if (data is not null) return GetStructure(data); return null; @@ -412,7 +412,7 @@ public TypeResData(ResourceTypeCode typeCode, HexSpan codeSpan, HexSpan dataSpan string resName = Encoding.Unicode.GetString(File.Buffer.ReadBytes(info.UnicodeName.StringSpan)); string? typeName = null; var typeData = resData as TypeResData; - if (!(typeData is null)) + if (typeData is not null) typeName = Encoding.UTF8.GetString(File.Buffer.ReadBytes(typeData.Utf8TypeName.StringSpan)); var resInfo = new MultiResourceInfo(resName, resData.TypeCode, typeName); switch (resData.TypeCode) { diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetResourceProviderImpl.cs b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetResourceProviderImpl.cs index 9aff8c82ac..1597210ac3 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetResourceProviderImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetResourceProviderImpl.cs @@ -57,7 +57,7 @@ public int Compare([AllowNull] ResourceInfo x, [AllowNull] ResourceInfo y) { public DotNetResourceProviderImpl(HexBufferFile file, PeHeaders peHeaders, DotNetMetadataHeaders? metadataHeaders, HexSpan? resourcesSpan) : base(file) { this.peHeaders = peHeaders ?? throw new ArgumentNullException(nameof(peHeaders)); - if (!(metadataHeaders?.TablesStream is null) && !(resourcesSpan is null)) { + if (metadataHeaders?.TablesStream is not null && resourcesSpan is not null) { Debug.Assert(file.Span.Contains(resourcesSpan.Value));// Verified by caller ResourcesSpan = resourcesSpan.Value; resourceInfos = CreateResourceInfos(file, metadataHeaders.TablesStream.MDTables[(int)Table.ManifestResource], metadataHeaders.StringsStream); diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetStructureProvider.cs b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetStructureProvider.cs index 4f7240b618..fe839a385f 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetStructureProvider.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetStructureProvider.cs @@ -51,7 +51,7 @@ sealed class DotNetStructureProvider : StructureProvider { public override bool Initialize() { HexSpan? resourcesSpan = null; var peHeaders = file.GetHeaders(); - if (!(peHeaders is null)) { + if (peHeaders is not null) { if (peHeaders.OptionalHeader.DataDirectory.Data.FieldCount < 15) return false; // Mono ignores the size field @@ -75,14 +75,14 @@ public override bool Initialize() { ReadDotNetMetadataHeader(file.Span); } - if (!(mdHeader is null) && !(dotNetHeaps is null)) + if (mdHeader is not null && dotNetHeaps is not null) dotNetMetadataHeaders = new DotNetMetadataHeadersImpl(metadataSpan, mdHeader, dotNetHeaps); - if (!(peHeaders is null) && !(cor20 is null)) { + if (peHeaders is not null && cor20 is not null) { dotNetMethodProvider = new DotNetMethodProviderImpl(file, peHeaders, dotNetMetadataHeaders?.TablesStream); dotNetResourceProvider = new DotNetResourceProviderImpl(file, peHeaders, dotNetMetadataHeaders, resourcesSpan); dotNetHeaders = new DotNetHeadersImpl(peHeaders, cor20, dotNetMetadataHeaders, strongNameSignature, dotNetMethodProvider, dotNetResourceProvider); } - return !(cor20 is null) || !metadataSpan.IsEmpty; + return cor20 is not null || !metadataSpan.IsEmpty; } HexSpan? Read(PeHeaders peHeaders, DataDirectoryData dir, bool allowZeroSize) { @@ -111,7 +111,7 @@ void ReadDotNetMetadataHeader(HexSpan span) { var mdReader = DotNetMetadataHeaderReader.TryCreate(file, span); if (mdReader is null) return; - Debug2.Assert(!(mdReader.StorageStreamHeaders is null)); + Debug2.Assert(mdReader.StorageStreamHeaders is not null); mdHeader = DotNetMetadataHeaderDataImpl.TryCreate(file, mdReader.MetadataHeaderSpan, (int)mdReader.VersionStringSpan.Length.ToUInt64(), mdReader.StorageStreamHeaders); if (mdHeader is null) return; @@ -129,16 +129,16 @@ void ReadStrongNameSignature(PeHeaders peHeaders, HexSpan? span) { public override ComplexData? GetStructure(HexPosition position) { var cor20 = this.cor20; - if (!(cor20 is null)) { + if (cor20 is not null) { if (cor20.Span.Span.Contains(position)) return cor20; if (strongNameSignature?.Span.Span.Contains(position) == true) return strongNameSignature; var body = dotNetMethodProvider?.GetMethodBody(position); - if (!(body is null)) + if (body is not null) return body; var resource = dotNetResourceProvider?.GetResource(position); - if (!(resource is null)) + if (resource is not null) return resource; } diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetTableSizes.cs b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetTableSizes.cs index 6cdc4cbcd7..aaaa562423 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/DotNetTableSizes.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/DotNetTableSizes.cs @@ -42,7 +42,7 @@ sealed class DotNetTableSizes { /// true if #Blob size >= 0x10000 /// Count of rows in each table public void InitializeSizes(bool bigStrings, bool bigGuid, bool bigBlob, uint[] rowCounts) { - Debug2.Assert(!(tableInfos is null)); + Debug2.Assert(tableInfos is not null); this.bigStrings = bigStrings; this.bigGuid = bigGuid; this.bigBlob = bigBlob; @@ -63,7 +63,7 @@ public void InitializeSizes(bool bigStrings, bool bigGuid, bool bigBlob, uint[] } int GetSize(ColumnSize columnSize) { - Debug2.Assert(!(rowCounts is null)); + Debug2.Assert(rowCounts is not null); if (ColumnSize.Module <= columnSize && columnSize <= ColumnSize.CustomDebugInformation) { int table = (int)(columnSize - ColumnSize.Module); uint count = table >= rowCounts.Length ? 0 : rowCounts[table]; diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/FatMethodBodyImpl.cs b/dnSpy/dnSpy/Hex/Files/DotNet/FatMethodBodyImpl.cs index b944b7348a..bf411142f4 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/FatMethodBodyImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/FatMethodBodyImpl.cs @@ -75,9 +75,9 @@ public FatMethodBodyImpl(DotNetMethodProvider methodProvider, HexBufferSpan span LocalVarSigTok, Instructions, }; - if (!(Padding is null)) + if (Padding is not null) fields.Add(Padding); - if (!(EHTable is null)) + if (EHTable is not null) fields.Add(EHTable); Fields = fields.ToArray(); } diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/MultiResourceStructureProviderFactory.cs b/dnSpy/dnSpy/Hex/Files/DotNet/MultiResourceStructureProviderFactory.cs index c0c51b8897..1114164a19 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/MultiResourceStructureProviderFactory.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/MultiResourceStructureProviderFactory.cs @@ -39,7 +39,7 @@ sealed class MultiResourceStructureProvider : StructureProvider { public override bool Initialize() { multiFileResources = DotNetMultiFileResourcesImpl.TryRead(file); - return !(multiFileResources is null); + return multiFileResources is not null; } public override ComplexData? GetStructure(HexPosition position) => diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/PdbHeapImpl.cs b/dnSpy/dnSpy/Hex/Files/DotNet/PdbHeapImpl.cs index b488441130..3093fbddd4 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/PdbHeapImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/PdbHeapImpl.cs @@ -33,7 +33,7 @@ public override PdbStreamHeaderData Header { get { if (!initialized) Initialize(); - Debug2.Assert(!(pdbStreamHeaderData is null)); + Debug2.Assert(pdbStreamHeaderData is not null); return pdbStreamHeaderData; } } @@ -42,7 +42,7 @@ public override ReadOnlyCollection PdbId { get { if (!initialized) Initialize(); - Debug2.Assert(!(pdbId is null)); + Debug2.Assert(pdbId is not null); return pdbId; } } @@ -67,7 +67,7 @@ public override ReadOnlyCollection TypeSystemTableRows { get { if (!initialized) Initialize(); - Debug2.Assert(!(typeSystemTableRowsReadOnly is null)); + Debug2.Assert(typeSystemTableRowsReadOnly is not null); return typeSystemTableRowsReadOnly; } } diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/StringsHeapImpl.cs b/dnSpy/dnSpy/Hex/Files/DotNet/StringsHeapImpl.cs index 60366702eb..b5afc2622e 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/StringsHeapImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/StringsHeapImpl.cs @@ -65,7 +65,7 @@ public StringZ(HexSpan stringSpan, int terminatorLength) { public override ComplexData? GetStructure(HexPosition position) { var info = GetStringInfo(position); - if (!(info is null)) + if (info is not null) return new StringsHeapRecordData(Span.Buffer, info.Value.String.StringSpan, info.Value.String.HasTerminator, this, info.Value.Tokens); return null; @@ -77,7 +77,7 @@ public StringZ(HexSpan stringSpan, int terminatorLength) { var index = GetIndex(position); if (index < 0) return null; - Debug2.Assert(!(knownStringInfos is null)); + Debug2.Assert(knownStringInfos is not null); var pos = knownStringInfos[index].Span.Start; var end = HexPosition.Min(Span.Span.End, pos + 0x1000); @@ -109,7 +109,7 @@ StringZ GetStringSpan(HexPosition position, HexPosition end) { } void Initialize() { - if (!(knownStringInfos is null)) + if (knownStringInfos is not null) return; if (metadata is null) return; diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/TablesHeapImpl.cs b/dnSpy/dnSpy/Hex/Files/DotNet/TablesHeapImpl.cs index 881498b8b4..ef0f6fba07 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/TablesHeapImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/TablesHeapImpl.cs @@ -32,7 +32,7 @@ public override ReadOnlyCollection MDTables { get { if (!initialized) Initialize(); - Debug2.Assert(!(mdTablesReadOnly is null)); + Debug2.Assert(mdTablesReadOnly is not null); return mdTablesReadOnly; } } @@ -57,7 +57,7 @@ public override TablesHeaderData Header { get { if (!initialized) Initialize(); - Debug2.Assert(!(tablesHeaderData is null)); + Debug2.Assert(tablesHeaderData is not null); return tablesHeaderData; } } @@ -233,7 +233,7 @@ TableRecordDataFactory CreateFactory(MDTable mdTable) { return Header; var mdTable = GetTable(position); - if (!(mdTable is null)) + if (mdTable is not null) return GetRecord(mdTable, position); return null; @@ -249,7 +249,7 @@ TableRecordDataFactory CreateFactory(MDTable mdTable) { public override TableRecordData? GetRecord(MDToken token) { if (!initialized) Initialize(); - Debug2.Assert(!(tableRecordDataFactories is null)); + Debug2.Assert(tableRecordDataFactories is not null); int tableIndex = (int)token.Table; if ((uint)tableIndex >= (uint)tableRecordDataFactories.Length) return null; @@ -259,7 +259,7 @@ TableRecordDataFactory CreateFactory(MDTable mdTable) { MDTable? GetTable(HexPosition position) { if (!initialized) Initialize(); - Debug2.Assert(!(mdTables is null)); + Debug2.Assert(mdTables is not null); var array = mdTables; int lo = 0, hi = array.Length - 1; while (lo <= hi) { diff --git a/dnSpy/dnSpy/Hex/Files/DotNet/USHeapImpl.cs b/dnSpy/dnSpy/Hex/Files/DotNet/USHeapImpl.cs index 06388e53a0..3aac5b34b8 100644 --- a/dnSpy/dnSpy/Hex/Files/DotNet/USHeapImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/DotNet/USHeapImpl.cs @@ -36,7 +36,7 @@ public USHeapImpl(HexBufferSpan span) public override ComplexData? GetStructure(HexPosition position) { var info = GetStringInfo(position); - if (!(info is null)) + if (info is not null) return new USHeapRecordData(Span.Buffer, info.Value.LengthSpan, info.Value.StringSpan, info.Value.TerminalByteSpan, this); return null; @@ -48,12 +48,12 @@ public USHeapImpl(HexBufferSpan span) var index = GetIndex(position); if (index < 0) return null; - Debug2.Assert(!(usStringInfos is null)); + Debug2.Assert(usStringInfos is not null); return usStringInfos[index]; } void Initialize() { - if (!(usStringInfos is null)) + if (usStringInfos is not null) return; usStringInfos = CreateUSStringInfos(); } @@ -90,7 +90,7 @@ int GetIndex(HexPosition position) { if (array is null) { Initialize(); array = usStringInfos; - Debug2.Assert(!(array is null)); + Debug2.Assert(array is not null); } int lo = 0, hi = array.Length - 1; while (lo <= hi) { diff --git a/dnSpy/dnSpy/Hex/Files/HexBufferFileImpl.cs b/dnSpy/dnSpy/Hex/Files/HexBufferFileImpl.cs index b18afcb92e..79418e57af 100644 --- a/dnSpy/dnSpy/Hex/Files/HexBufferFileImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/HexBufferFileImpl.cs @@ -94,7 +94,7 @@ void CreateStructureProviders(bool initialize) { var list = new List(structureProviderFactories.Length); foreach (var lz in structureProviderFactories) { var provider = lz.Value.Create(this); - if (!(provider is null)) + if (provider is not null) list.Add(provider); } structureProviders = list.ToArray(); @@ -118,18 +118,18 @@ void CreateStructureProviders(bool initialize) { // Always initialize this first to make sure nested files get created CreateStructureProviders(true); - Debug2.Assert(!(structureProviders is null)); + Debug2.Assert(structureProviders is not null); if (checkNestedFiles && files.Count != 0) { var file = files.FindData(position); var info = file?.GetFileAndStructure(position, checkNestedFiles); - if (!(info is null)) + if (info is not null) return info; } foreach (var provider in structureProviders) { var structure = provider.GetStructure(position); - if (!(structure is null)) + if (structure is not null) return new FileAndStructure(this, structure); } return null; @@ -137,10 +137,10 @@ void CreateStructureProviders(bool initialize) { public override ComplexData? GetStructure(string id) { CreateStructureProviders(true); - Debug2.Assert(!(structureProviders is null)); + Debug2.Assert(structureProviders is not null); foreach (var provider in structureProviders) { var structure = provider.GetStructure(id); - if (!(structure is null)) + if (structure is not null) return structure; } return null; @@ -152,22 +152,22 @@ void CreateStructureProviders(bool initialize) { var list = new List(bufferFileHeadersProviderFactories.Length); foreach (var lz in bufferFileHeadersProviderFactories) { var provider = lz.Value.Create(this); - if (!(provider is null)) + if (provider is not null) list.Add(provider); } bufferFileHeadersProviders = list.ToArray(); } - Debug2.Assert(!(structureProviders is null)); + Debug2.Assert(structureProviders is not null); foreach (var provider in structureProviders) { var headers = provider.GetHeaders(); - if (!(headers is null)) + if (headers is not null) return headers; } foreach (var provider in bufferFileHeadersProviders) { var headers = provider.GetHeaders(); - if (!(headers is null)) + if (headers is not null) return headers; } diff --git a/dnSpy/dnSpy/Hex/Files/HexFieldFormatterImpl.cs b/dnSpy/dnSpy/Hex/Files/HexFieldFormatterImpl.cs index 71b36081fc..f82756442a 100644 --- a/dnSpy/dnSpy/Hex/Files/HexFieldFormatterImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/HexFieldFormatterImpl.cs @@ -100,11 +100,11 @@ public override void WriteValue(ComplexData structure, HexPosition position) { if (!structure.Span.Span.Contains(position)) throw new ArgumentOutOfRangeException(nameof(position)); var field = structure.GetSimpleField(position); - Debug2.Assert(!(field is null)); + Debug2.Assert(field is not null); if (field is null) return; var data = field.Data as SimpleData; - Debug2.Assert(!(data is null)); + Debug2.Assert(data is not null); if (data is null) return; try { diff --git a/dnSpy/dnSpy/Hex/Files/HexFileStructureInfoServiceImpl.cs b/dnSpy/dnSpy/Hex/Files/HexFileStructureInfoServiceImpl.cs index 8a33d360a6..4a188679af 100644 --- a/dnSpy/dnSpy/Hex/Files/HexFileStructureInfoServiceImpl.cs +++ b/dnSpy/dnSpy/Hex/Files/HexFileStructureInfoServiceImpl.cs @@ -52,7 +52,7 @@ HexFileStructureInfoProvider[] CreateProviders() { var providers = new List(hexFileStructureInfoProviderFactories.Length); foreach (var lz in hexFileStructureInfoProviderFactories) { var provider = lz.Value.Create(hexView); - if (!(provider is null)) + if (provider is not null) providers.Add(provider); } return providers.ToArray(); @@ -106,7 +106,7 @@ static bool IsValidIndexes(HexIndexes[] indexes, ComplexData structure) { var structure = info.Value.Structure; foreach (var provider in HexFileStructureInfoProviders) { var toolTip = provider.GetToolTip(file, structure, position); - if (!(toolTip is null)) + if (toolTip is not null) return toolTip; } @@ -122,7 +122,7 @@ static bool IsValidIndexes(HexIndexes[] indexes, ComplexData structure) { var structure = info.Value.Structure; foreach (var provider in HexFileStructureInfoProviders) { var toolTip = provider.GetReference(file, structure, position); - if (!(toolTip is null)) + if (toolTip is not null) return toolTip; } @@ -140,13 +140,13 @@ static bool IsValidIndexes(HexIndexes[] indexes, ComplexData structure) { HexSpan? span; foreach (var provider in HexFileStructureInfoProviders) { span = provider.GetFieldReferenceSpan(file, structure, position); - if (!(span is null)) + if (span is not null) return span; } var field = structure.GetSimpleField(position); span = (field?.Data as SimpleData)?.GetFieldReferenceSpan(file); - if (!(span is null)) + if (span is not null) return span; return null; diff --git a/dnSpy/dnSpy/Hex/Files/PE/PeHeadersReader.cs b/dnSpy/dnSpy/Hex/Files/PE/PeHeadersReader.cs index 00510180d0..d92504ffbd 100644 --- a/dnSpy/dnSpy/Hex/Files/PE/PeHeadersReader.cs +++ b/dnSpy/dnSpy/Hex/Files/PE/PeHeadersReader.cs @@ -129,7 +129,7 @@ bool GuessIsFileLayout() { } var b = DotNetCheckIsFileLayout(); - if (!(b is null)) + if (b is not null) return b.Value; if (!file.IsNestedFile && file.Buffer.IsMemory) { @@ -147,7 +147,7 @@ bool GuessIsFileLayout() { } bool? DotNetCheckIsFileLayout() { - Debug2.Assert(!(OptionalHeader is null)); + Debug2.Assert(OptionalHeader is not null); if (OptionalHeader.DataDirectory.Data.FieldCount <= 14) return null; var dataDir = OptionalHeader.DataDirectory.Data[14]; @@ -195,7 +195,7 @@ bool CheckDotNet(uint cor20Rva, Func rvaToPos) { HexPosition MemoryLayout_ToBufferPosition(uint rva) => file.Span.Start + rva; HexPosition FileLayout_ToBufferPosition(uint rva) { - Debug2.Assert(!(SectionHeaders is null)); + Debug2.Assert(SectionHeaders is not null); var fileSpan = file.Span; foreach (var sect in SectionHeaders) { if (rva >= sect.VirtualAddress && rva < sect.VirtualAddress + Math.Max(sect.VirtualSize, sect.SizeOfRawData)) diff --git a/dnSpy/dnSpy/Hex/Files/PE/PeHexFileStructureInfoProvider.cs b/dnSpy/dnSpy/Hex/Files/PE/PeHexFileStructureInfoProvider.cs index 09e6e5a5ec..c1779b0fd8 100644 --- a/dnSpy/dnSpy/Hex/Files/PE/PeHexFileStructureInfoProvider.cs +++ b/dnSpy/dnSpy/Hex/Files/PE/PeHexFileStructureInfoProvider.cs @@ -59,9 +59,9 @@ sealed class PeHexFileStructureInfoProvider : HexFileStructureInfoProvider { return null; HexSpan? span; - if (!((span = TryGetRvaSpan(file, position, data.VirtualAddress.Data, data.VirtualSize.Data)) is null)) + if ((span = TryGetRvaSpan(file, position, data.VirtualAddress.Data, data.VirtualSize.Data)) is not null) return span; - if (!((span = TryGetFileSpan(file, position, data.PointerToRawData.Data, data.SizeOfRawData.Data)) is null)) + if ((span = TryGetFileSpan(file, position, data.PointerToRawData.Data, data.SizeOfRawData.Data)) is not null) return span; return null; diff --git a/dnSpy/dnSpy/Hex/Files/PE/PeStructureProvider.cs b/dnSpy/dnSpy/Hex/Files/PE/PeStructureProvider.cs index 66e327e689..cc8ff70065 100644 --- a/dnSpy/dnSpy/Hex/Files/PE/PeStructureProvider.cs +++ b/dnSpy/dnSpy/Hex/Files/PE/PeStructureProvider.cs @@ -55,7 +55,7 @@ public override bool Initialize() { peHeadersImpl = new PeHeadersImpl(reader, file.Span); peHeadersSpan = GetSpan(peHeadersImpl.DosHeader.Span.Span, peHeadersImpl.FileHeader.Span.Span, peHeadersImpl.OptionalHeader.Span.Span, peHeadersImpl.Sections.Span.Span); } - return !(peHeadersImpl is null); + return peHeadersImpl is not null; } HexSpan GetSpan(params HexSpan[] spans) { diff --git a/dnSpy/dnSpy/Hex/Formatting/HexAndAdornmentSequencerImpl.cs b/dnSpy/dnSpy/Hex/Formatting/HexAndAdornmentSequencerImpl.cs index e504522222..32665d0772 100644 --- a/dnSpy/dnSpy/Hex/Formatting/HexAndAdornmentSequencerImpl.cs +++ b/dnSpy/dnSpy/Hex/Formatting/HexAndAdornmentSequencerImpl.cs @@ -89,7 +89,7 @@ public override HexAndAdornmentCollection CreateHexAndAdornmentCollection(HexBuf sequenceList.Add(new HexSequenceElementImpl(textSpan)); if (info.Span.Start != end || (info.Span.Length == 0 && info.AdornmentElement.Affinity == VST.PositionAffinity.Predecessor)) { bool canAppend = true; - if (!(lastAddedAdornment is null) && lastAddedAdornment.Value.Span.End > info.Span.Start) + if (lastAddedAdornment is not null && lastAddedAdornment.Value.Span.End > info.Span.Start) canAppend = false; if (canAppend) { sequenceList.Add(info.AdornmentElement); diff --git a/dnSpy/dnSpy/Hex/Formatting/HexFormattedLineImpl.cs b/dnSpy/dnSpy/Hex/Formatting/HexFormattedLineImpl.cs index 37c630e798..47b3bd4759 100644 --- a/dnSpy/dnSpy/Hex/Formatting/HexFormattedLineImpl.cs +++ b/dnSpy/dnSpy/Hex/Formatting/HexFormattedLineImpl.cs @@ -247,7 +247,7 @@ public override bool HasAdornments { if (!IsValid) throw new ObjectDisposedException(nameof(HexFormattedLineImpl)); foreach (var part in linePartsCollection.LineParts) { - if (!(part.AdornmentElement is null)) + if (part.AdornmentElement is not null) return true; } return false; @@ -427,7 +427,7 @@ public override int GetVirtualLinePositionFromXCoordinate(double xCoordinate) { throw new ObjectDisposedException(nameof(HexFormattedLineImpl)); var pos = GetLinePositionFromXCoordinate(xCoordinate); - if (!(pos is null)) + if (pos is not null) return pos.Value; if (xCoordinate <= TextLeft) return TextSpan.Start; @@ -441,7 +441,7 @@ public override int GetInsertionLinePositionFromXCoordinate(double xCoordinate) throw new ObjectDisposedException(nameof(HexFormattedLineImpl)); var pos = GetLinePositionFromXCoordinate(xCoordinate); - if (!(pos is null)) { + if (pos is not null) { if (pos.Value < TextSpan.End) { var bounds = GetExtendedCharacterBounds(pos.Value); // Get closest buffer position @@ -496,7 +496,7 @@ int GetFirstColumn(int position) => int GetLastColumn(int position) { int column = FilterColumn(linePartsCollection.ConvertLinePositionToColumn(position)); var part = linePartsCollection.GetLinePartFromColumn(column); - if (!(part is null)) { + if (part is not null) { var lineParts = linePartsCollection.LineParts; int lineIndex = position - linePartsCollection.Span.Start; for (int i = part.Value.Index + 1; i < lineParts.Count; i++, column++) { @@ -543,13 +543,13 @@ VSTF.TextBounds GetTextBounds(int column) { column -= textSpan.Length; } - return (column == 0 || IsLastVisualLine) && !(lastTextSpan is null) ? lastTextSpan.Value.Properties : null; + return (column == 0 || IsLastVisualLine) && lastTextSpan is not null ? lastTextSpan.Value.Properties : null; } public override Collection GetNormalizedTextBounds(VST.Span lineSpan) { var list = new List(); var bounds = TryGetNormalizedTextBounds(lineSpan); - if (!(bounds is null)) + if (bounds is not null) list.Add(bounds.Value); return new Collection(list); } @@ -586,7 +586,7 @@ VSTF.TextBounds GetTextBounds(int column) { foreach (var info in bufferLine.GetSpans(pos.Value, flags)) { var valuesSpan = TryGetNormalizedTextBounds(info.TextSpan); - if (!(valuesSpan is null)) + if (valuesSpan is not null) list.Add(valuesSpan.Value); } diff --git a/dnSpy/dnSpy/Hex/Formatting/HexFormattedLineSourceImpl.cs b/dnSpy/dnSpy/Hex/Formatting/HexFormattedLineSourceImpl.cs index e7b3e896a4..fc3039b4f0 100644 --- a/dnSpy/dnSpy/Hex/Formatting/HexFormattedLineSourceImpl.cs +++ b/dnSpy/dnSpy/Hex/Formatting/HexFormattedLineSourceImpl.cs @@ -171,7 +171,7 @@ void Add(List list, int column, HexClassificationSpan cspan, VST.Sp if (list.Count > 0) { var last = list[list.Count - 1]; if (last.AdornmentElement is null && last.TextRunProperties == props && last.Span.End == cspan.Span.Start) { - Debug2.Assert(!(last.TextRunProperties is null)); + Debug2.Assert(last.TextRunProperties is not null); list[list.Count - 1] = new HexLinePart(list.Count - 1, last.Column, VST.Span.FromBounds(last.Span.Start - startOffs, cspan.Span.End - startOffs), last.TextRunProperties); return; } diff --git a/dnSpy/dnSpy/Hex/Formatting/HexHtmlBuilderServiceImpl.cs b/dnSpy/dnSpy/Hex/Formatting/HexHtmlBuilderServiceImpl.cs index c195d19810..a1131ea584 100644 --- a/dnSpy/dnSpy/Hex/Formatting/HexHtmlBuilderServiceImpl.cs +++ b/dnSpy/dnSpy/Hex/Formatting/HexHtmlBuilderServiceImpl.cs @@ -70,7 +70,7 @@ string GenerateHtmlFragmentCore(HexBufferLineFormatter bufferLines, NormalizedHe HexClassifier? classifier = null; try { VSTC.IClassificationFormatMap classificationFormatMap; - if (!(hexView is null)) { + if (hexView is not null) { classifier = viewClassifierAggregatorService.GetClassifier(hexView); classificationFormatMap = classificationFormatMapService.GetClassificationFormatMap(hexView); } @@ -82,7 +82,7 @@ string GenerateHtmlFragmentCore(HexBufferLineFormatter bufferLines, NormalizedHe const int tabSize = 4; var builder = new HexHtmlBuilder(classificationFormatMap, delimiter, tabSize); if (spans.Count != 0) { - Debug2.Assert(!(classifier is null)); + Debug2.Assert(classifier is not null); builder.Add(bufferLines, classifier, spans, cancellationToken); } return builder.Create(); diff --git a/dnSpy/dnSpy/Hex/Formatting/HexLinePart.cs b/dnSpy/dnSpy/Hex/Formatting/HexLinePart.cs index 5391c72273..be4d240610 100644 --- a/dnSpy/dnSpy/Hex/Formatting/HexLinePart.cs +++ b/dnSpy/dnSpy/Hex/Formatting/HexLinePart.cs @@ -35,7 +35,7 @@ readonly struct HexLinePart { /// /// Length in column characters. This is never zero. /// - public int ColumnLength => !(AdornmentElement is null) ? 1 : Span.Length; + public int ColumnLength => AdornmentElement is not null ? 1 : Span.Length; /// /// Span relative to the start of the physical line () @@ -58,8 +58,8 @@ readonly struct HexLinePart { public readonly int Index; public HexLinePart(int index, int column, VST.Span span, HexAdornmentElement adornmentElement, TextRunProperties textRunProperties) { - Debug2.Assert(!(adornmentElement is null)); - Debug2.Assert(!(textRunProperties is null)); + Debug2.Assert(adornmentElement is not null); + Debug2.Assert(textRunProperties is not null); Index = index; Column = column; Span = span; @@ -69,7 +69,7 @@ public HexLinePart(int index, int column, VST.Span span, HexAdornmentElement ado public HexLinePart(int index, int column, VST.Span span, TextRunProperties textRunProperties) { Debug.Assert(!span.IsEmpty); - Debug2.Assert(!(textRunProperties is null)); + Debug2.Assert(textRunProperties is not null); Index = index; Column = column; Span = span; @@ -95,7 +95,7 @@ public bool BelongsTo(int lineIndex) { } public override string ToString() { - if (!(AdornmentElement is null)) + if (AdornmentElement is not null) return $"{Span.ToString()} {AdornmentElement.ToString()}"; return Span.ToString(); } diff --git a/dnSpy/dnSpy/Hex/Formatting/HexLinePartsCollection.cs b/dnSpy/dnSpy/Hex/Formatting/HexLinePartsCollection.cs index 4c45b6aa80..e9b990afbd 100644 --- a/dnSpy/dnSpy/Hex/Formatting/HexLinePartsCollection.cs +++ b/dnSpy/dnSpy/Hex/Formatting/HexLinePartsCollection.cs @@ -77,7 +77,7 @@ public int ConvertLinePositionToColumn(int linePosition) { linePart = LineParts[LineParts.Count - 1]; if (linePart is null) return 0; - if (!(linePart.Value.AdornmentElement is null)) + if (linePart.Value.AdornmentElement is not null) return linePart.Value.Column; return linePart.Value.Column + ((linePosition - Span.Start) - linePart.Value.Span.Start); } @@ -98,7 +98,7 @@ public int ConvertColumnToLinePosition(int column) { linePart = LineParts[LineParts.Count - 1]; if (linePart is null) return null; - if (!(linePart.Value.AdornmentElement is null)) + if (linePart.Value.AdornmentElement is not null) return null; return Span.Start + linePart.Value.Span.Start + (column - linePart.Value.Column); } diff --git a/dnSpy/dnSpy/Hex/Formatting/HexLinePartsTextSource.cs b/dnSpy/dnSpy/Hex/Formatting/HexLinePartsTextSource.cs index 52ef9b17f3..01439b237e 100644 --- a/dnSpy/dnSpy/Hex/Formatting/HexLinePartsTextSource.cs +++ b/dnSpy/dnSpy/Hex/Formatting/HexLinePartsTextSource.cs @@ -48,7 +48,7 @@ public override TextRun GetTextRun(int textSourceCharacterIndex) { if (linePart is null) return endOfLine; var part = linePart.Value; - if (!(part.AdornmentElement is null)) + if (part.AdornmentElement is not null) return new AdornmentTextRun(part); else { int offs = textSourceCharacterIndex - part.Column; @@ -75,7 +75,7 @@ sealed class AdornmentTextRun : TextEmbeddedObject { readonly HexAdornmentElement adornmentElement; public AdornmentTextRun(HexLinePart linePart) { - Debug2.Assert(!(linePart.AdornmentElement is null)); + Debug2.Assert(linePart.AdornmentElement is not null); adornmentElement = linePart.AdornmentElement; if (linePart.Span.Length != 0 || adornmentElement.Affinity == VST.PositionAffinity.Successor) { BreakBefore = LineBreakCondition.BreakPossible; @@ -105,7 +105,7 @@ public override TextEmbeddedObjectMetrics Format(double remainingParagraphWidth) public int GetColumnOfFirstNonWhitespace() { int column = 0; foreach (var part in linePartsCollection.LineParts) { - if (!(part.AdornmentElement is null)) + if (part.AdornmentElement is not null) break; int len = part.Span.Length; int start = part.Span.Start; diff --git a/dnSpy/dnSpy/Hex/Formatting/HexLineTransformProviderService.cs b/dnSpy/dnSpy/Hex/Formatting/HexLineTransformProviderService.cs index 3b27896249..6cf74c31e4 100644 --- a/dnSpy/dnSpy/Hex/Formatting/HexLineTransformProviderService.cs +++ b/dnSpy/dnSpy/Hex/Formatting/HexLineTransformProviderService.cs @@ -48,7 +48,7 @@ public override HexLineTransformProvider Create(WpfHexView hexView, bool removeE if (!hexView.Roles.ContainsAny(lz.Metadata.TextViewRoles)) continue; var source = lz.Value.Create(hexView); - if (!(source is null)) + if (source is not null) list.Add(source); } return new HexLineTransformProviderImpl(list.ToArray(), removeExtraTextLineVerticalPixels); diff --git a/dnSpy/dnSpy/Hex/Formatting/PhysicalLineCache.cs b/dnSpy/dnSpy/Hex/Formatting/PhysicalLineCache.cs index acc2f2100e..57a959eb51 100644 --- a/dnSpy/dnSpy/Hex/Formatting/PhysicalLineCache.cs +++ b/dnSpy/dnSpy/Hex/Formatting/PhysicalLineCache.cs @@ -41,7 +41,7 @@ public PhysicalLineCache(int maxCacheSize) { for (int i = 0; i < cache.Count; i++) { var physLine = cache[i]; var line = physLine.FindFormattedLineByBufferPosition(point); - if (!(line is null)) + if (line is not null) return line; } return null; diff --git a/dnSpy/dnSpy/Hex/HexBufferImpl.cs b/dnSpy/dnSpy/Hex/HexBufferImpl.cs index 028231e645..98c99e4502 100644 --- a/dnSpy/dnSpy/Hex/HexBufferImpl.cs +++ b/dnSpy/dnSpy/Hex/HexBufferImpl.cs @@ -83,11 +83,11 @@ void VerifyAccess() { } HexEditImpl? hexEditInProgress; - public override bool EditInProgress => !(hexEditInProgress is null); + public override bool EditInProgress => hexEditInProgress is not null; public override bool CheckEditAccess() => CheckAccess(); public override void TakeThreadOwnership() { - if (!(ownerThread is null) && ownerThread != Thread.CurrentThread) + if (ownerThread is not null && ownerThread != Thread.CurrentThread) throw new InvalidOperationException(); ownerThread = Thread.CurrentThread; } diff --git a/dnSpy/dnSpy/Hex/HexBufferLineFormatterImpl.cs b/dnSpy/dnSpy/Hex/HexBufferLineFormatterImpl.cs index 6f4813b4a5..dd2d22b70a 100644 --- a/dnSpy/dnSpy/Hex/HexBufferLineFormatterImpl.cs +++ b/dnSpy/dnSpy/Hex/HexBufferLineFormatterImpl.cs @@ -564,7 +564,7 @@ HexCell[] WriteValues(HexBytes hexBytes, HexSpan visibleBytesSpan, out VST.Span bufferSpan = new HexBufferSpan(new HexBufferPoint(buffer, pos), new HexBufferPoint(buffer, endPos)); } else { - if (!(visStart is null) && visEnd is null) + if (visStart is not null && visEnd is null) visEnd = CurrentTextIndex; stringBuilder.Append(' ', valueFormatter.FormattedLength); spaces = valueFormatter.FormattedLength; @@ -587,7 +587,7 @@ HexCell[] WriteValues(HexBytes hexBytes, HexSpan visibleBytesSpan, out VST.Span } if (pos != end) throw new InvalidOperationException(); - if (!(visStart is null) && visEnd is null) + if (visStart is not null && visEnd is null) visEnd = CurrentTextIndex; visibleSpan = visStart is null ? default : VST.Span.FromBounds(visStart.Value, visEnd!.Value); fullSpan = VST.Span.FromBounds(fullStart, CurrentTextIndex); @@ -624,7 +624,7 @@ HexCell[] WriteAscii(HexBytes hexBytes, HexSpan visibleBytesSpan, out VST.Span f bufferSpan = new HexBufferSpan(buffer, new HexSpan(pos, 1)); } else { - if (!(visStart is null) && visEnd is null) + if (visStart is not null && visEnd is null) visEnd = CurrentTextIndex; stringBuilder.Append(' '); bufferSpan = default; @@ -637,7 +637,7 @@ HexCell[] WriteAscii(HexBytes hexBytes, HexSpan visibleBytesSpan, out VST.Span f } if ((ulong)fullStart + bytesPerLine != (ulong)CurrentTextIndex) throw new InvalidOperationException(); - if (!(visStart is null) && visEnd is null) + if (visStart is not null && visEnd is null) visEnd = CurrentTextIndex; visibleSpan = visStart is null ? default : VST.Span.FromBounds(visStart.Value, visEnd!.Value); fullSpan = VST.Span.FromBounds(fullStart, CurrentTextIndex); diff --git a/dnSpy/dnSpy/Hex/HexCachedBufferStreamImpl.cs b/dnSpy/dnSpy/Hex/HexCachedBufferStreamImpl.cs index 4e1dce2abc..8ed047b491 100644 --- a/dnSpy/dnSpy/Hex/HexCachedBufferStreamImpl.cs +++ b/dnSpy/dnSpy/Hex/HexCachedBufferStreamImpl.cs @@ -441,7 +441,7 @@ public override HexBytes ReadHexBytes(HexPosition position, long length) { } } - if (!(bitArray is null)) + if (bitArray is not null) return new HexBytes(destination, bitArray); if (invalidBytes == bytesRead) return new HexBytes(destination, false); diff --git a/dnSpy/dnSpy/Hex/HexGroups/HexViewOptionsGroupImpl.cs b/dnSpy/dnSpy/Hex/HexGroups/HexViewOptionsGroupImpl.cs index ab0f4526b6..9b4eab8def 100644 --- a/dnSpy/dnSpy/Hex/HexGroups/HexViewOptionsGroupImpl.cs +++ b/dnSpy/dnSpy/Hex/HexGroups/HexViewOptionsGroupImpl.cs @@ -46,12 +46,12 @@ public HexViewOptionsGroupImpl(HexViewOptionsGroupServiceImpl owner, string grou this.groupName = groupName ?? throw new ArgumentNullException(nameof(groupName)); foreach (var option in defaultOptions) { - Debug2.Assert(!(option.Name is null)); + Debug2.Assert(option.Name is not null); if (option.Name is null) continue; var subGroup = option.SubGroup; - Debug2.Assert(!(subGroup is null)); + Debug2.Assert(subGroup is not null); if (subGroup is null) continue; diff --git a/dnSpy/dnSpy/Hex/HexGroups/HexViewOptionsGroupServiceImpl.cs b/dnSpy/dnSpy/Hex/HexGroups/HexViewOptionsGroupServiceImpl.cs index 434494acf5..a6410c95e3 100644 --- a/dnSpy/dnSpy/Hex/HexGroups/HexViewOptionsGroupServiceImpl.cs +++ b/dnSpy/dnSpy/Hex/HexGroups/HexViewOptionsGroupServiceImpl.cs @@ -56,7 +56,7 @@ sealed class HexViewOptionsGroupServiceImpl : HexViewOptionsGroupService { internal string? GetSubGroup(WpfHexView hexView) { foreach (var lz in tagOptionDefinitionProviders) { var subGroup = lz.Value.GetSubGroup(hexView); - if (!(subGroup is null)) + if (subGroup is not null) return subGroup; } return null; @@ -80,7 +80,7 @@ TagOptionDefinition[] GetDefaultOptions(string groupName) { continue; options.AddRange(lz.Value.GetOptions()); } - return options.Where(a => !(a.SubGroup is null) && !(a.Name is null) && !(a.Type is null)).ToArray(); + return options.Where(a => a.SubGroup is not null && a.Name is not null && a.Type is not null).ToArray(); } internal void HexViewCreated(WpfHexView hexView) { @@ -90,7 +90,7 @@ internal void HexViewCreated(WpfHexView hexView) { foreach (var lz in hexViewOptionsGroupNameProviders) { var name = lz.Value.TryGetGroupName(hexView); - if (!(name is null)) { + if (name is not null) { var group = GetGroupCore(name); group.HexViewCreated(hexView); break; diff --git a/dnSpy/dnSpy/Hex/HexGroups/OptionsStorage.cs b/dnSpy/dnSpy/Hex/HexGroups/OptionsStorage.cs index 102d2edb34..beeba758b7 100644 --- a/dnSpy/dnSpy/Hex/HexGroups/OptionsStorage.cs +++ b/dnSpy/dnSpy/Hex/HexGroups/OptionsStorage.cs @@ -142,7 +142,7 @@ bool TryGetValue(HexViewGroupOption option, string textValue, out object? value) value = c.ConvertFromInvariantString(textValue); if (type.IsValueType && value is null) return false; - if (!(value is null) && !type.IsAssignableFrom(value.GetType())) + if (value is not null && !type.IsAssignableFrom(value.GetType())) return false; return true; } diff --git a/dnSpy/dnSpy/Hex/Intellisense/DnSpy/QuickInfoCommandTargetFilter.cs b/dnSpy/dnSpy/Hex/Intellisense/DnSpy/QuickInfoCommandTargetFilter.cs index cb5a88fbbc..65423d10a1 100644 --- a/dnSpy/dnSpy/Hex/Intellisense/DnSpy/QuickInfoCommandTargetFilter.cs +++ b/dnSpy/dnSpy/Hex/Intellisense/DnSpy/QuickInfoCommandTargetFilter.cs @@ -76,7 +76,7 @@ public CommandTargetStatus Execute(Guid group, int cmdId, object? args, ref obje } void TriggerQuickInfo() { - if (!(quickInfoSession is null)) { + if (quickInfoSession is not null) { quickInfoSession.Dismissed -= QuickInfoSession_Dismissed; quickInfoSession.Dismiss(); quickInfoSession = null; diff --git a/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseControllerService.cs b/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseControllerService.cs index 4678f689f8..ad22f0d87e 100644 --- a/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseControllerService.cs +++ b/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseControllerService.cs @@ -44,7 +44,7 @@ public HexViewState(WpfHexView hexView, Lazy[ var list = new List(intellisenseControllerProviders.Length); foreach (var provider in intellisenseControllerProviders) { var controller = provider.Value.TryCreateIntellisenseController(hexView); - if (!(controller is null)) + if (controller is not null) list.Add(controller); } intellisenseControllers = list.ToArray(); diff --git a/dnSpy/dnSpy/Hex/Intellisense/HexIntellisensePresenterFactoryService.cs b/dnSpy/dnSpy/Hex/Intellisense/HexIntellisensePresenterFactoryService.cs index 5dffceac2d..722af3ce63 100644 --- a/dnSpy/dnSpy/Hex/Intellisense/HexIntellisensePresenterFactoryService.cs +++ b/dnSpy/dnSpy/Hex/Intellisense/HexIntellisensePresenterFactoryService.cs @@ -41,7 +41,7 @@ sealed class HexIntellisensePresenterFactoryServiceImpl : HexIntellisensePresent throw new ArgumentNullException(nameof(session)); foreach (var lz in intellisensePresenterProviders) { var presenter = lz.Value.TryCreateIntellisensePresenter(session); - if (!(presenter is null)) + if (presenter is not null) return presenter; } return null; diff --git a/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseSessionStackImpl.CommandTargetFilter.cs b/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseSessionStackImpl.CommandTargetFilter.cs index b8ec708f8c..759e5573ba 100644 --- a/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseSessionStackImpl.CommandTargetFilter.cs +++ b/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseSessionStackImpl.CommandTargetFilter.cs @@ -56,7 +56,7 @@ public void UnhookKeyboard() { public CommandTargetStatus CanExecute(Guid group, int cmdId) { if (group == CommandConstants.HexEditorGroup) { - if (!(TryGetIntellisenseKeyboardCommand((HexEditorIds)cmdId) is null)) + if (TryGetIntellisenseKeyboardCommand((HexEditorIds)cmdId) is not null) return CommandTargetStatus.Handled; } return CommandTargetStatus.NotHandled; @@ -70,7 +70,7 @@ public CommandTargetStatus Execute(Guid group, int cmdId, object? args) { public CommandTargetStatus Execute(Guid group, int cmdId, object? args, ref object? result) { if (group == CommandConstants.HexEditorGroup) { var command = TryGetIntellisenseKeyboardCommand((HexEditorIds)cmdId); - if (!(command is null) && owner.ExecuteKeyboardCommand(command.Value)) + if (command is not null && owner.ExecuteKeyboardCommand(command.Value)) return CommandTargetStatus.Handled; } return CommandTargetStatus.NotHandled; diff --git a/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseSessionStackImpl.cs b/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseSessionStackImpl.cs index e1a47537e4..9ebf3b362d 100644 --- a/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseSessionStackImpl.cs +++ b/dnSpy/dnSpy/Hex/Intellisense/HexIntellisenseSessionStackImpl.cs @@ -49,7 +49,7 @@ sealed class SessionState { public IHexPopupIntellisensePresenter? PopupIntellisensePresenter { get; set; } public SessionState(HexIntellisenseSession session) => Session = session; public void SetSpaceReservationManager(HexSpaceReservationManager manager) { - if (!(SpaceReservationManager is null)) + if (SpaceReservationManager is not null) throw new InvalidOperationException(); SpaceReservationManager = manager ?? throw new ArgumentNullException(nameof(manager)); } @@ -217,7 +217,7 @@ SessionState GetSessionState(HexIntellisenseSession session) { void PresenterUpdated(HexIntellisenseSession session) { var sessionState = GetSessionState(session); - if (!(sessionState.SpaceReservationAgent is null)) + if (sessionState.SpaceReservationAgent is not null) sessionState.SpaceReservationManager!.RemoveAgent(sessionState.SpaceReservationAgent); Debug2.Assert(sessionState.SpaceReservationAgent is null); @@ -225,7 +225,7 @@ void PresenterUpdated(HexIntellisenseSession session) { if (presenter is IHexPopupIntellisensePresenter popupPresenter) { if (sessionState.SpaceReservationManager is null) { sessionState.SetSpaceReservationManager(wpfHexView.GetSpaceReservationManager(popupPresenter.SpaceReservationManagerName)); - Debug2.Assert(!(sessionState.SpaceReservationManager is null)); + Debug2.Assert(sessionState.SpaceReservationManager is not null); sessionState.SpaceReservationManager.AgentChanged += SpaceReservationManager_AgentChanged; } UnregisterPopupIntellisensePresenterEvents(sessionState.PopupIntellisensePresenter); @@ -234,7 +234,7 @@ void PresenterUpdated(HexIntellisenseSession session) { var presentationSpan = popupPresenter.PresentationSpan; var surfaceElement = popupPresenter.SurfaceElement; - if (!presentationSpan.IsDefault && !(surfaceElement is null)) { + if (!presentationSpan.IsDefault && surfaceElement is not null) { sessionState.SpaceReservationAgent = sessionState.SpaceReservationManager.CreatePopupAgent(presentationSpan, popupPresenter.PopupStyles, surfaceElement); sessionState.SpaceReservationManager.AddAgent(sessionState.SpaceReservationAgent); } @@ -248,7 +248,7 @@ void PresenterUpdated(HexIntellisenseSession session) { } void RegisterPopupIntellisensePresenterEvents(IHexPopupIntellisensePresenter? popupPresenter) { - if (!(popupPresenter is null)) { + if (popupPresenter is not null) { popupPresenter.PopupStylesChanged += PopupIntellisensePresenter_PopupStylesChanged; popupPresenter.PresentationSpanChanged += PopupIntellisensePresenter_PresentationSpanChanged; popupPresenter.SurfaceElementChanged += PopupIntellisensePresenter_SurfaceElementChanged; @@ -256,7 +256,7 @@ void RegisterPopupIntellisensePresenterEvents(IHexPopupIntellisensePresenter? po } void UnregisterPopupIntellisensePresenterEvents(IHexPopupIntellisensePresenter? popupPresenter) { - if (!(popupPresenter is null)) { + if (popupPresenter is not null) { popupPresenter.PopupStylesChanged -= PopupIntellisensePresenter_PopupStylesChanged; popupPresenter.PresentationSpanChanged -= PopupIntellisensePresenter_PresentationSpanChanged; popupPresenter.SurfaceElementChanged -= PopupIntellisensePresenter_SurfaceElementChanged; @@ -278,7 +278,7 @@ void PopupIntellisensePresenter_PropertyChanged(IHexPopupIntellisensePresenter p return; } var sessionState = TryGetSessionState(popupPresenter); - Debug2.Assert(!(sessionState is null)); + Debug2.Assert(sessionState is not null); if (sessionState is null) return; if (propertyName == nameof(popupPresenter.PresentationSpan) || propertyName == nameof(popupPresenter.PopupStyles)) { @@ -296,7 +296,7 @@ void SpaceReservationManager_AgentChanged(object? sender, HexSpaceReservationAge if (wpfHexView.IsClosed) return; var sessionState = TryGetSessionState(e.OldAgent); - if (!(sessionState is null)) { + if (sessionState is not null) { sessionState.SpaceReservationAgent = null; // Its popup was hidden, so dismiss the session sessionState.Session.Dismiss(); @@ -305,7 +305,7 @@ void SpaceReservationManager_AgentChanged(object? sender, HexSpaceReservationAge void Session_Dismissed(object? sender, EventArgs e) { var session = sender as HexIntellisenseSession; - Debug2.Assert(!(session is null)); + Debug2.Assert(session is not null); if (session is null) return; int index = sessions.IndexOf(session); @@ -322,9 +322,9 @@ void RemoveSessionAt(int index) { session.Dismissed -= Session_Dismissed; session.PresenterChanged -= Session_PresenterChanged; var sessionState = GetSessionState(session); - if (!(sessionState.SpaceReservationAgent is null)) + if (sessionState.SpaceReservationAgent is not null) sessionState.SpaceReservationManager!.RemoveAgent(sessionState.SpaceReservationAgent); - if (!(sessionState.SpaceReservationManager is null)) + if (sessionState.SpaceReservationManager is not null) sessionState.SpaceReservationManager.AgentChanged -= SpaceReservationManager_AgentChanged; UnregisterPopupIntellisensePresenterEvents(sessionState.PopupIntellisensePresenter); sessionStates.Remove(sessionState); diff --git a/dnSpy/dnSpy/Hex/Intellisense/HexQuickInfoPresenter.cs b/dnSpy/dnSpy/Hex/Intellisense/HexQuickInfoPresenter.cs index c66f7bbe00..4f05056dfc 100644 --- a/dnSpy/dnSpy/Hex/Intellisense/HexQuickInfoPresenter.cs +++ b/dnSpy/dnSpy/Hex/Intellisense/HexQuickInfoPresenter.cs @@ -34,7 +34,7 @@ sealed class HexQuickInfoPresenter : HexQuickInfoPresenterBase, IHexCustomIntell public HexQuickInfoPresenter(HexQuickInfoSession session) : base(session) { wpfHexView = session.HexView as WpfHexView; - Debug2.Assert(!(wpfHexView is null)); + Debug2.Assert(wpfHexView is not null); popup = new Popup { PlacementTarget = wpfHexView?.VisualElement, Placement = PlacementMode.Relative, @@ -74,7 +74,7 @@ bool RenderCore() { return false; var line = session.HexView.HexViewLines.GetHexViewLineContainingBufferPosition(point.BufferPosition); - Debug2.Assert(!(line is null) && line.VisibilityState != VSTF.VisibilityState.Unattached); + Debug2.Assert(line is not null && line.VisibilityState != VSTF.VisibilityState.Unattached); if (line is null || line.VisibilityState == VSTF.VisibilityState.Unattached) return false; @@ -110,7 +110,7 @@ void DismissIfNeeded(MouseEventArgs e) { } bool ShouldDismiss(MouseEventArgs e) { - Debug2.Assert(!(wpfHexView is null)); + Debug2.Assert(wpfHexView is not null); var mousePos = GetMousePoint(e.MouseDevice); if (mousePos is null) return true; @@ -153,7 +153,7 @@ void ClosePopup() { protected override void OnSessionDismissed() { ClosePopup(); - if (!(wpfHexView is null)) { + if (wpfHexView is not null) { wpfHexView.VisualElement.MouseLeave -= VisualElement_MouseLeave; wpfHexView.VisualElement.MouseMove -= VisualElement_MouseMove; popup.RemoveHandler(UIElement.MouseLeaveEvent, new MouseEventHandler(Popup_MouseLeave)); diff --git a/dnSpy/dnSpy/Hex/Intellisense/HexQuickInfoSessionImpl.cs b/dnSpy/dnSpy/Hex/Intellisense/HexQuickInfoSessionImpl.cs index 1760fb551b..37bf5c44dd 100644 --- a/dnSpy/dnSpy/Hex/Intellisense/HexQuickInfoSessionImpl.cs +++ b/dnSpy/dnSpy/Hex/Intellisense/HexQuickInfoSessionImpl.cs @@ -78,7 +78,7 @@ HexQuickInfoSource[] CreateQuickInfoSources() { List? list = null; foreach (var provider in quickInfoSourceProviders) { var source = provider.Value.TryCreateQuickInfoSource(HexView); - if (!(source is null)) { + if (source is not null) { if (list is null) list = new List(); list.Add(source); @@ -88,7 +88,7 @@ HexQuickInfoSource[] CreateQuickInfoSources() { } void DisposeQuickInfoSources() { - if (!(quickInfoSources is null)) { + if (quickInfoSources is not null) { foreach (var source in quickInfoSources) source.Dispose(); quickInfoSources = null; diff --git a/dnSpy/dnSpy/Hex/Intellisense/HexToolTipService.cs b/dnSpy/dnSpy/Hex/Intellisense/HexToolTipService.cs index d565826b76..de27b0b8a3 100644 --- a/dnSpy/dnSpy/Hex/Intellisense/HexToolTipService.cs +++ b/dnSpy/dnSpy/Hex/Intellisense/HexToolTipService.cs @@ -90,19 +90,19 @@ public HexToolTipInfoCollection(HexToolTipInfo[] infos) { FullBufferSpan = HexBufferSpan.FromBounds(start, end); Array.Sort(infos, (a, b) => { - if ((!(a.ToolTip is null)) != (!(b.ToolTip is null))) - return !(a.ToolTip is null) ? -1 : 1; + if ((a.ToolTip is not null) != (b.ToolTip is not null)) + return a.ToolTip is not null ? -1 : 1; if (a.BufferSpan.Length != b.BufferSpan.Length) return a.BufferSpan.Length.CompareTo(b.BufferSpan.Length); return Array.IndexOf(infos, a) - Array.IndexOf(infos, b); }); BufferSpan = infos[0].BufferSpan; - Debug2.Assert(!(infos[0].ToolTip is null)); + Debug2.Assert(infos[0].ToolTip is not null); int index = 0; foreach (var info in infos.OrderBy(a => a.BufferSpan.Start)) { if (info.ClassificationType is null) { - info.ClassificationType = !(info.ToolTip is null) ? + info.ClassificationType = info.ToolTip is not null ? CTC.ThemeClassificationTypeNameKeys.HexToolTipServiceCurrentField : (index & 1) == 0 ? CTC.ThemeClassificationTypeNameKeys.HexToolTipServiceField0 : CTC.ThemeClassificationTypeNameKeys.HexToolTipServiceField1; @@ -158,13 +158,13 @@ public override void AugmentQuickInfoSession(HexQuickInfoSession session, IList< hexToolTipService.SetActiveToolTip(toolTipInfoCollection); session.Dismissed += Session_Dismissed; foreach (var info in toolTipInfoCollection) { - if (!(info.ToolTip is null)) + if (info.ToolTip is not null) quickInfoContent.Add(info.ToolTip); } } void RemoveToolTipInfo() { - if (!(toolTipInfoCollection is null)) { + if (toolTipInfoCollection is not null) { hexToolTipService.RemoveActiveToolTip(toolTipInfoCollection); toolTipInfoCollection = null; } @@ -238,7 +238,7 @@ void UpdateHighlightStructureUnderMouseCursor() { if (newValue == highlightStructureUnderMouseCursor) return; highlightStructureUnderMouseCursor = newValue; - if (!(activeToolTipInfoCollection is null)) + if (activeToolTipInfoCollection is not null) tagger?.RaiseTagsChanged(activeToolTipInfoCollection.FullBufferSpan); } @@ -264,7 +264,7 @@ void UpdateHighlightStructureUnderMouseCursor() { if (!tagSpan.Span.Contains(position)) continue; - if (!(tagSpan.Tag.ToolTip is null)) { + if (tagSpan.Tag.ToolTip is not null) { if (!tagSpan.Tag.BufferSpan.Contains(position)) continue; toolTips++; @@ -321,7 +321,7 @@ public override IEnumerable> GetTags(NormalizedHexBuff } public override void RegisterTagger(IHexToolTipServiceTagger tagger) { - if (!(this.tagger is null)) + if (this.tagger is not null) throw new InvalidOperationException(); this.tagger = tagger ?? throw new ArgumentNullException(nameof(tagger)); } diff --git a/dnSpy/dnSpy/Hex/Operations/ByteHexSearchService.cs b/dnSpy/dnSpy/Hex/Operations/ByteHexSearchService.cs index 32a703ae08..2bea734399 100644 --- a/dnSpy/dnSpy/Hex/Operations/ByteHexSearchService.cs +++ b/dnSpy/dnSpy/Hex/Operations/ByteHexSearchService.cs @@ -378,7 +378,7 @@ IEnumerable FindAllCore(SearchState state, HexBufferSpan searchRa if ((options & HexFindOptions.Wrap) != 0) { var upperBounds = HexPosition.Min(searchRange.Span.End, startingPosition.Position + pattern.LongLength - 1); - if ((options & HexFindOptions.NoOverlaps) != 0 && !(firstBlockResult is null) && upperBounds > firstBlockResult.Value.Start) + if ((options & HexFindOptions.NoOverlaps) != 0 && firstBlockResult is not null && upperBounds > firstBlockResult.Value.Start) upperBounds = firstBlockResult.Value.Start; foreach (var span in GetValidSpans(startingPosition.Buffer, searchRange.Start, upperBounds)) { cancellationToken.ThrowIfCancellationRequested(); @@ -476,7 +476,7 @@ IEnumerable FindAllCoreReverse(SearchState state, HexBufferSpan s HexPosition.Zero; if (lowerBounds < searchRange.Span.Start) lowerBounds = searchRange.Span.Start; - if ((options & HexFindOptions.NoOverlaps) != 0 && !(firstBlockResult is null) && lowerBounds < firstBlockResult.Value.End) + if ((options & HexFindOptions.NoOverlaps) != 0 && firstBlockResult is not null && lowerBounds < firstBlockResult.Value.End) lowerBounds = firstBlockResult.Value.End; foreach (var span in GetValidSpansReverse(startingPosition.Buffer, searchRange.End - 1, lowerBounds)) { cancellationToken.ThrowIfCancellationRequested(); diff --git a/dnSpy/dnSpy/Hex/Operations/HexEditorOperationsImpl.cs b/dnSpy/dnSpy/Hex/Operations/HexEditorOperationsImpl.cs index 095c4e0581..18ca9be8b8 100644 --- a/dnSpy/dnSpy/Hex/Operations/HexEditorOperationsImpl.cs +++ b/dnSpy/dnSpy/Hex/Operations/HexEditorOperationsImpl.cs @@ -510,7 +510,7 @@ bool InsertTextAscii(HexCellPosition cellPosition, string text) { return true; var encoding = Options.TryGetEncoding(); - Debug2.Assert(!(encoding is null)); + Debug2.Assert(encoding is not null); if (encoding is null) return false; @@ -630,7 +630,7 @@ bool CopyToClipboard(string text, string? htmlText, bool isFullLineData, bool is dataObj.SetData(VS_COPY_FULL_LINE_DATA_FORMAT, true); if (isBoxData) dataObj.SetData(VS_COPY_BOX_DATA_FORMAT, true); - if (!(htmlText is null)) + if (htmlText is not null) dataObj.SetData(DataFormats.Html, htmlText); Clipboard.SetDataObject(dataObj); return true; @@ -783,7 +783,7 @@ bool CopyValue() { var pos = ActiveCaretBufferPosition; var line = BufferLines.GetLineFromPosition(pos); var cell = line.ValueCells.GetCell(pos); - Debug2.Assert(!(cell is null)); + Debug2.Assert(cell is not null); if (cell is null) return false; var cellText = line.Text.Substring(cell.TextSpan.Start, cell.TextSpan.Length); @@ -800,10 +800,10 @@ bool CopyValue() { bool CopyFileOffset() { var pos = ActiveCaretBufferPosition.Position; var peHeaders = TryGetPeHeaders(pos); - if (!(peHeaders is null)) + if (peHeaders is not null) return CopyHexValue(peHeaders.BufferPositionToFilePosition(pos)); var file = TryGetFile(pos); - if (!(file is null)) + if (file is not null) return CopyHexValue((pos - file.Span.Start).ToUInt64()); return CopyHexValue(pos.ToUInt64()); } @@ -830,10 +830,10 @@ public override bool CanPaste { get { switch (Caret.Position.Position.ActiveColumn) { case HexColumnType.Values: - return !(ClipboardUtils.GetData(canBeEmpty: false) is null); + return ClipboardUtils.GetData(canBeEmpty: false) is not null; case HexColumnType.Ascii: - return !(ClipboardUtils.GetText(canBeEmpty: false) is null); + return ClipboardUtils.GetText(canBeEmpty: false) is not null; case HexColumnType.Offset: default: @@ -1009,15 +1009,15 @@ void ScrollAndMoveCaretIfNecessary(VSTE.ScrollDirection scrollDirection) { public override void ScrollColumnLeft() { var wpfHexView = HexView as WpfHexView; - Debug2.Assert(!(wpfHexView is null)); - if (!(wpfHexView is null)) + Debug2.Assert(wpfHexView is not null); + if (wpfHexView is not null) wpfHexView.ViewScroller.ScrollViewportHorizontallyByPixels(-wpfHexView.FormattedLineSource.ColumnWidth); } public override void ScrollColumnRight() { var wpfHexView = HexView as WpfHexView; - Debug2.Assert(!(wpfHexView is null)); - if (!(wpfHexView is null)) + Debug2.Assert(wpfHexView is not null); + if (wpfHexView is not null) wpfHexView.ViewScroller.ScrollViewportHorizontallyByPixels(wpfHexView.FormattedLineSource.ColumnWidth); } @@ -1038,7 +1038,7 @@ public override void ScrollLineCenter() { if (!Roles.Contains(PredefinedHexViewRoles.Zoomable)) return null; var wpfHexView = HexView as WpfHexView; - Debug2.Assert(!(wpfHexView is null)); + Debug2.Assert(wpfHexView is not null); return wpfHexView; } @@ -1157,7 +1157,7 @@ public override void SelectAllBytesBlock() { if (span is null) return; var overlap = BufferLines.BufferSpan.Span.Overlap(span.Value); - Debug2.Assert(!(overlap is null)); + Debug2.Assert(overlap is not null); if (overlap is null) return; if (!overlap.Value.Contains(currPos)) @@ -1234,7 +1234,7 @@ public override void GoToCodeOrStructure() { public override void FollowFieldValueReference() { var span = HexFileStructureInfoService.GetFieldReferenceSpan(ActiveCaretBufferPosition); - if (!(span is null)) { + if (span is not null) { var point = new HexBufferPoint(Buffer, span.Value.Start); if (BufferLines.IsValidPosition(point)) { ViewScroller.EnsureSpanVisible(new HexBufferSpan(Buffer, new HexSpan(span.Value.Start, 0)), HexSpanSelectionFlags.Selection, VSTE.EnsureSpanVisibleOptions.ShowStart); diff --git a/dnSpy/dnSpy/Hex/Operations/HexSearchServiceImpl.cs b/dnSpy/dnSpy/Hex/Operations/HexSearchServiceImpl.cs index d637dba9cb..9eb7598bec 100644 --- a/dnSpy/dnSpy/Hex/Operations/HexSearchServiceImpl.cs +++ b/dnSpy/dnSpy/Hex/Operations/HexSearchServiceImpl.cs @@ -78,7 +78,7 @@ static class Cache { public static byte[] GetBuffer() => Interlocked.Exchange(ref weakBuffer, null)?.Target as byte[] ?? new byte[BUFFER_LENGTH]; public static void ReturnBuffer(ref byte[]? buffer) { var tmp = buffer; - if (!(tmp is null)) { + if (tmp is not null) { buffer = null; weakBuffer = new WeakReference(tmp); } diff --git a/dnSpy/dnSpy/Hex/Operations/StringHexSearchService.cs b/dnSpy/dnSpy/Hex/Operations/StringHexSearchService.cs index 68a482f577..e41ee85329 100644 --- a/dnSpy/dnSpy/Hex/Operations/StringHexSearchService.cs +++ b/dnSpy/dnSpy/Hex/Operations/StringHexSearchService.cs @@ -306,7 +306,7 @@ IEnumerable FindAllCore(SearchState state, HexBufferSpan searchRa if ((options & HexFindOptions.Wrap) != 0) { var upperBounds = HexPosition.Min(searchRange.Span.End, startingPosition.Position + lowerBytes.LongLength - 1); - if ((options & HexFindOptions.NoOverlaps) != 0 && !(firstBlockResult is null) && upperBounds > firstBlockResult.Value.Start) + if ((options & HexFindOptions.NoOverlaps) != 0 && firstBlockResult is not null && upperBounds > firstBlockResult.Value.Start) upperBounds = firstBlockResult.Value.Start; foreach (var span in GetValidSpans(startingPosition.Buffer, searchRange.Start, upperBounds)) { cancellationToken.ThrowIfCancellationRequested(); @@ -406,7 +406,7 @@ IEnumerable FindAllCoreReverse(SearchState state, HexBufferSpan s HexPosition.Zero; if (lowerBounds < searchRange.Span.Start) lowerBounds = searchRange.Span.Start; - if ((options & HexFindOptions.NoOverlaps) != 0 && !(firstBlockResult is null) && lowerBounds < firstBlockResult.Value.End) + if ((options & HexFindOptions.NoOverlaps) != 0 && firstBlockResult is not null && lowerBounds < firstBlockResult.Value.End) lowerBounds = firstBlockResult.Value.End; foreach (var span in GetValidSpansReverse(startingPosition.Buffer, searchRange.End - 1, lowerBounds)) { cancellationToken.ThrowIfCancellationRequested(); diff --git a/dnSpy/dnSpy/Hex/Settings/GeneralAppSettingsPageBase.cs b/dnSpy/dnSpy/Hex/Settings/GeneralAppSettingsPageBase.cs index 872387b625..7ff7804621 100644 --- a/dnSpy/dnSpy/Hex/Settings/GeneralAppSettingsPageBase.cs +++ b/dnSpy/dnSpy/Hex/Settings/GeneralAppSettingsPageBase.cs @@ -170,7 +170,7 @@ public override void OnApply() { options.GroupSizeInBytes = GroupSizeInBytesVM.Value; var encodingInfo = EncodingInfo; - if (!(encodingInfo is null)) + if (encodingInfo is not null) options.EncodingCodePage = encodingInfo.CodePage; } } diff --git a/dnSpy/dnSpy/Hex/Tagging/HexTaggerFactory.cs b/dnSpy/dnSpy/Hex/Tagging/HexTaggerFactory.cs index 600d852297..2699d2ec6b 100644 --- a/dnSpy/dnSpy/Hex/Tagging/HexTaggerFactory.cs +++ b/dnSpy/dnSpy/Hex/Tagging/HexTaggerFactory.cs @@ -44,11 +44,11 @@ public IEnumerable> Create(HexView hexView, HexBuffer buffer) w var type = typeof(T); foreach (var info in hexViewTaggerProviders) { - if (!(info.Metadata.TextViewRoles is null) && !hexView.Roles.ContainsAny(info.Metadata.TextViewRoles)) + if (info.Metadata.TextViewRoles is not null && !hexView.Roles.ContainsAny(info.Metadata.TextViewRoles)) continue; if (CanCreateTagger(type, info.Metadata.TagTypes)) { var tagger = info.Value.CreateTagger(hexView, buffer); - if (!(tagger is null)) + if (tagger is not null) yield return tagger; } } @@ -59,7 +59,7 @@ public IEnumerable> Create(HexBuffer buffer) where T : HexTag { foreach (var info in hexBufferTaggerProviders) { if (CanCreateTagger(type, info.Metadata.TagTypes)) { var tagger = info.Value.CreateTagger(buffer); - if (!(tagger is null)) + if (tagger is not null) yield return tagger; } } diff --git a/dnSpy/dnSpy/Hex/Tagging/TagAggregator.cs b/dnSpy/dnSpy/Hex/Tagging/TagAggregator.cs index 1c4c908289..ed468fc551 100644 --- a/dnSpy/dnSpy/Hex/Tagging/TagAggregator.cs +++ b/dnSpy/dnSpy/Hex/Tagging/TagAggregator.cs @@ -59,7 +59,7 @@ public override IEnumerable> GetAllTags(HexTaggerContext cont public override IEnumerable> GetAllTags(HexTaggerContext context, CancellationToken cancellationToken) => owner.GetAllTags(context, cancellationToken); - public bool IsBatchedTagsChangedHooked => !(BatchedTagsChanged is null); + public bool IsBatchedTagsChangedHooked => BatchedTagsChanged is not null; public void RaiseTagsChanged(object? sender, HexTagsChangedEventArgs e) => TagsChanged?.Invoke(sender, e); public void RaiseBatchedTagsChanged(object? sender, HexBatchedTagsChangedEventArgs e) => BatchedTagsChanged?.Invoke(sender, e); protected override void DisposeCore() => owner.Dispose(); @@ -124,7 +124,7 @@ IEnumerable> GetAllTags(HexTaggerContext context, Cancellatio var spans = new NormalizedHexBufferSpanCollection(span); var textSpan = context.LineSpan; foreach (var tagger in taggers) { - var tags = !(cancellationToken is null) ? tagger.GetTags(spans, cancellationToken.Value) : tagger.GetTags(spans); + var tags = cancellationToken is not null ? tagger.GetTags(spans, cancellationToken.Value) : tagger.GetTags(spans); foreach (var tagSpan in tags) { var intersection = span.Intersection(tagSpan.Span); if (intersection is null) @@ -132,15 +132,15 @@ IEnumerable> GetAllTags(HexTaggerContext context, Cancellatio foreach (var info in context.Line.GetSpans(intersection.Value, tagSpan.Flags)) { var vs = textSpan.Intersection(info.TextSpan); - if (!(vs is null)) + if (vs is not null) yield return new HexTextTagSpan(vs.Value, tagSpan.Tag); } } - var textTags = !(cancellationToken is null) ? tagger.GetTags(context, cancellationToken.Value) : tagger.GetTags(context); + var textTags = cancellationToken is not null ? tagger.GetTags(context, cancellationToken.Value) : tagger.GetTags(context); foreach (var tagSpan in textTags) { var intersection = textSpan.Intersection(tagSpan.Span); - if (!(intersection is null)) + if (intersection is not null) yield return new HexTextTagSpan(intersection.Value, tagSpan.Tag); } } diff --git a/dnSpy/dnSpy/Images/DefaultImageSourceInfoProvider.cs b/dnSpy/dnSpy/Images/DefaultImageSourceInfoProvider.cs index 7b1fc12245..4e09e0f0a3 100644 --- a/dnSpy/dnSpy/Images/DefaultImageSourceInfoProvider.cs +++ b/dnSpy/dnSpy/Images/DefaultImageSourceInfoProvider.cs @@ -37,14 +37,14 @@ sealed class DefaultImageSourceInfoProvider : IImageSourceInfoProvider { public ImageSourceInfo[]? GetImageSourceInfos(string name) { if (nameToInfosDict is null) InitializeResources(); - Debug2.Assert(!(nameToInfosDict is null)); + Debug2.Assert(nameToInfosDict is not null); if (nameToInfosDict.TryGetValue(name, out var infos)) return infos; return null; } void InitializeResources() { - if (!(nameToInfosDict is null)) + if (nameToInfosDict is not null) return; var dict = new Dictionary>(StringComparer.InvariantCultureIgnoreCase); @@ -56,12 +56,12 @@ void InitializeResources() { options.TryToLoadPdbFromDisk = false; using (var mod = ModuleDefMD.Load(assembly.ManifestModule, options)) { var rsrc = mod.Resources.Find(rsrcName) as EmbeddedResource; - Debug2.Assert(!(rsrc is null)); - if (!(rsrc is null)) { + Debug2.Assert(rsrc is not null); + if (rsrc is not null) { var set = ResourceReader.Read(mod, rsrc.CreateReader()); foreach (var elem in set.ResourceElements) { const string imagesPrefix = "images/"; - if (!(elem.Name is null) && elem.Name.StartsWith(imagesPrefix, StringComparison.OrdinalIgnoreCase)) { + if (elem.Name is not null && elem.Name.StartsWith(imagesPrefix, StringComparison.OrdinalIgnoreCase)) { var imageName = elem.Name.Substring(imagesPrefix.Length); var nameNoExt = RemoveExtension(imageName); string? nameKey = null; @@ -79,7 +79,7 @@ void InitializeResources() { Size = GetImageSize(nameNoExt, out nameKey) ?? new Size(16, 16), }; } - if (!(info is null) && !(nameKey is null)) { + if (info is not null && nameKey is not null) { if (!dict.TryGetValue(nameKey, out var list)) dict.Add(nameKey, list = new List()); list.Add(info.Value); diff --git a/dnSpy/dnSpy/Images/DotNetImageService.cs b/dnSpy/dnSpy/Images/DotNetImageService.cs index 70b5a03759..becc3c088d 100644 --- a/dnSpy/dnSpy/Images/DotNetImageService.cs +++ b/dnSpy/dnSpy/Images/DotNetImageService.cs @@ -177,18 +177,18 @@ public ImageReference GetImageReference(TypeDef type) { } static bool IsModule(TypeDef type) => - !(type is null) && type.DeclaringType is null && type.IsSealed && type.IsDefined(stringMicrosoftVisualBasicCompilerServices, stringStandardModuleAttribute); + type is not null && type.DeclaringType is null && type.IsSealed && type.IsDefined(stringMicrosoftVisualBasicCompilerServices, stringStandardModuleAttribute); static readonly UTF8String stringMicrosoftVisualBasicCompilerServices = new UTF8String("Microsoft.VisualBasic.CompilerServices"); static readonly UTF8String stringStandardModuleAttribute = new UTF8String("StandardModuleAttribute"); static bool IsDelegate(TypeDef type) => - !(type.BaseType is null) && type.BaseType.FullName == "System.MulticastDelegate" && type.BaseType.DefinitionAssembly.IsCorLib(); + type.BaseType is not null && type.BaseType.FullName == "System.MulticastDelegate" && type.BaseType.DefinitionAssembly.IsCorLib(); static bool IsException(TypeDef type) { TypeDef? td = type; if (IsSystemException(td)) return true; - for (int i = 0; i < 1000 && !(td is null); i++) { + for (int i = 0; i < 1000 && td is not null; i++) { if (IsSystemException(td.BaseType)) return true; var bt = td.BaseType; @@ -198,7 +198,7 @@ static bool IsException(TypeDef type) { } static bool IsSystemException(ITypeDefOrRef? type) => - !(type is null) && + type is not null && type.DeclaringType is null && type.Namespace == "System" && type.Name == "Exception" && @@ -261,7 +261,7 @@ public ImageReference GetImageReference(FieldDef field) { } } - static bool IsSystemDecimal(TypeSig ts) => !(ts is null) && ts.DefinitionAssembly.IsCorLib() && ts.FullName == "System.Decimal"; + static bool IsSystemDecimal(TypeSig ts) => ts is not null && ts.DefinitionAssembly.IsCorLib() && ts.FullName == "System.Decimal"; static bool IsDecimalConstant(FieldDef field) => IsSystemDecimal(field.FieldType) && field.CustomAttributes.IsDefined("System.Runtime.CompilerServices.DecimalConstantAttribute"); public ImageReference GetImageReference(MethodDef method) { diff --git a/dnSpy/dnSpy/Images/DsImageConverter.cs b/dnSpy/dnSpy/Images/DsImageConverter.cs index 9e48f852bb..210b1ea4cf 100644 --- a/dnSpy/dnSpy/Images/DsImageConverter.cs +++ b/dnSpy/dnSpy/Images/DsImageConverter.cs @@ -30,7 +30,7 @@ sealed class DsImageConverter : IMultiValueConverter { internal static IImageService? imageService; public object? Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - Debug2.Assert(!(imageService is null)); + Debug2.Assert(imageService is not null); if (values is null) throw new ArgumentNullException(nameof(values)); bool b = values.Length == 7; diff --git a/dnSpy/dnSpy/Images/ImageService.cs b/dnSpy/dnSpy/Images/ImageService.cs index 2fd6d32fcc..2063bdf6c4 100644 --- a/dnSpy/dnSpy/Images/ImageService.cs +++ b/dnSpy/dnSpy/Images/ImageService.cs @@ -132,7 +132,7 @@ void ThemeService_ThemeChangedHighPriority(object? sender, ThemeChangedEventArgs } Size GetDpi(DependencyObject? dpiObject, Size dpi) { - if (!(dpiObject is null)) { + if (dpiObject is not null) { if (Window.GetWindow(dpiObject) is MetroWindow window) return window.WindowDpi; } @@ -167,7 +167,7 @@ Size GetDpi(DependencyObject? dpiObject, Size dpi) { if (internalOptions.PhysicalSize.Width == 0 || internalOptions.PhysicalSize.Height == 0) return null; - if (!(imageReference.Assembly is null)) { + if (imageReference.Assembly is not null) { var name = imageReference.Name; foreach (var provider in GetProviders(imageReference.Assembly)) { var infos = provider.Value.GetImageSourceInfos(name); @@ -202,7 +202,7 @@ Size GetDpi(DependencyObject? dpiObject, Size dpi) { foreach (var info in infoList) { var bitmapSource = TryGetImage(info.Uri, internalOptions); - if (!(bitmapSource is null)) + if (bitmapSource is not null) return bitmapSource; } @@ -222,7 +222,7 @@ Size GetDpi(DependencyObject? dpiObject, Size dpi) { BitmapSource? image; if (imageCache.TryGetValue(key, out var weakImage)) { image = weakImage.Target as BitmapSource; - if (!(image is null)) + if (image is not null) return image; } @@ -230,7 +230,7 @@ Size GetDpi(DependencyObject? dpiObject, Size dpi) { if (image is null) return null; - if (!(options.BackgroundColor is null)) + if (options.BackgroundColor is not null) image = ThemedImageCreator.CreateThemedBitmapSource(image, options.BackgroundColor.Value, isHighContrast); imageCache[key] = new WeakReference(image); return image; diff --git a/dnSpy/dnSpy/Language/Intellisense/CompletionCollectionVM.cs b/dnSpy/dnSpy/Language/Intellisense/CompletionCollectionVM.cs index 3b63f65054..983de348ef 100644 --- a/dnSpy/dnSpy/Language/Intellisense/CompletionCollectionVM.cs +++ b/dnSpy/dnSpy/Language/Intellisense/CompletionCollectionVM.cs @@ -46,7 +46,7 @@ public object? this[int index] { public CompletionCollectionVM(IList completionList) { this.completionList = completionList ?? throw new ArgumentNullException(nameof(completionList)); completionListNotifyCollectionChanged = completionList as INotifyCollectionChanged; - if (!(completionListNotifyCollectionChanged is null)) + if (completionListNotifyCollectionChanged is not null) completionListNotifyCollectionChanged.CollectionChanged += CompletionList_CollectionChanged; list = new List(completionList.Count); ReinitializeList(); @@ -56,11 +56,11 @@ void CompletionList_CollectionChanged(object? sender, NotifyCollectionChangedEve int i; switch (e.Action) { case NotifyCollectionChangedAction.Add: - Debug2.Assert(!(e.NewItems is null)); + Debug2.Assert(e.NewItems is not null); i = e.NewStartingIndex; var newList = new List(); foreach (Completion? c in e.NewItems) { - Debug2.Assert(!(c is null)); + Debug2.Assert(c is not null); var vm = GetOrCreateVM(c); newList.Add(vm); list.Insert(i++, vm); @@ -69,12 +69,12 @@ void CompletionList_CollectionChanged(object? sender, NotifyCollectionChangedEve break; case NotifyCollectionChangedAction.Remove: - Debug2.Assert(!(e.OldItems is null)); + Debug2.Assert(e.OldItems is not null); var oldList = new List(); foreach (Completion? c in e.OldItems) { - Debug2.Assert(!(c is null)); + Debug2.Assert(c is not null); var vm = CompletionVM.TryGet(c); - if (!(vm is null)) + if (vm is not null) oldList.Add(vm); Debug.Assert(list[e.OldStartingIndex].Completion == vm?.Completion); list.RemoveAt(e.OldStartingIndex); @@ -118,7 +118,7 @@ void ReinitializeList() { public void Remove(object? value) => throw new NotSupportedException(); public void RemoveAt(int index) => throw new NotSupportedException(); public void Dispose() { - if (!(completionListNotifyCollectionChanged is null)) + if (completionListNotifyCollectionChanged is not null) completionListNotifyCollectionChanged.CollectionChanged -= CompletionList_CollectionChanged; list.Clear(); } diff --git a/dnSpy/dnSpy/Language/Intellisense/CompletionPresenter.cs b/dnSpy/dnSpy/Language/Intellisense/CompletionPresenter.cs index 8ca89546a0..6b9a55e10c 100644 --- a/dnSpy/dnSpy/Language/Intellisense/CompletionPresenter.cs +++ b/dnSpy/dnSpy/Language/Intellisense/CompletionPresenter.cs @@ -103,8 +103,8 @@ public CompletionPresenter(ICompletionSession session, ICompletionTextElementPro session.TextView.LostAggregateFocus += TextView_LostAggregateFocus; session.TextView.TextBuffer.ChangedLowPriority += TextBuffer_ChangedLowPriority; wpfTextView = session.TextView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); - if (!(wpfTextView is null)) + Debug2.Assert(wpfTextView is not null); + if (wpfTextView is not null) wpfTextView.VisualElement.PreviewKeyDown += VisualElement_PreviewKeyDown; session.TextView.LayoutChanged += TextView_LayoutChanged; control.completionsListBox.SelectionChanged += CompletionsListBox_SelectionChanged; @@ -139,7 +139,7 @@ void CompletionsListBox_MouseDoubleClick(object? sender, MouseButtonEventArgs e) } void TextView_LayoutChanged(object? sender, TextViewLayoutChangedEventArgs e) { - if (!(wpfTextView is null) && oldZoomLevel != wpfTextView.ZoomLevel) { + if (wpfTextView is not null && oldZoomLevel != wpfTextView.ZoomLevel) { oldZoomLevel = wpfTextView.ZoomLevel; HideToolTip(); } @@ -211,7 +211,7 @@ void ShowToolTip() { if (!contentType.IsOfAnyType(provider.Metadata.ContentTypes)) continue; var elem = provider.Value.GetUIElement(completionVM.Completion, session, UIElementType.Tooltip); - if (!(elem is null)) + if (elem is not null) return elem; } @@ -274,9 +274,9 @@ void InitializeLoaded() { if (item is null && control.completionsListBox.Items.Count > 0) item = control.completionsListBox.Items[0]; var scrollViewer = WpfUtils.TryGetScrollViewer(control.completionsListBox); - if (!(item is null) && !(scrollViewer is null)) { + if (item is not null && scrollViewer is not null) { var lbItem = control.completionsListBox.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem; - Debug2.Assert(!(lbItem is null)); + Debug2.Assert(lbItem is not null); lbItem.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); var itemHeight = lbItem.DesiredSize.Height; double maxHeight = itemHeight * 9; @@ -286,7 +286,7 @@ void InitializeLoaded() { control.completionsListBox.MaxHeight = maxHeight; } - if (!(scrollViewer is null)) { + if (scrollViewer is not null) { if (scrollViewer.ViewportHeight != 0) UpdateSelectedItem(); else { @@ -384,7 +384,7 @@ void CompletionsListBox_SelectionChanged(object? sender, SelectionChangedEventAr if (completionSet is null) return; var newCompletion = e.AddedItems[0] as CompletionVM; - Debug2.Assert(!(newCompletion is null)); + Debug2.Assert(newCompletion is not null); if (newCompletion is null) return; if (completionSet.SelectionStatus.Completion == newCompletion.Completion) @@ -491,9 +491,9 @@ void CompletionSession_SelectedCompletionSetChanged(object? sender, ValueChanged void UpdateFilterCollection() { var filterCompletionSet = session.SelectedCompletionSet as DsCompletionSet; DisposeFilters(); - if (!(filterCompletionSet is null)) { + if (filterCompletionSet is not null) { var completionSetFilters = filterCompletionSet.Filters; - if (!(completionSetFilters is null)) { + if (completionSetFilters is not null) { foreach (var filter in completionSetFilters) filters.Add(new FilterVM(filter, this, filter.ImageReference)); } @@ -539,7 +539,7 @@ void UpdateSelectedCompletion() { if (completion is null) return null; var vm = CompletionVM.TryGet(completion); - Debug2.Assert(!(vm is null)); + Debug2.Assert(vm is not null); return vm; } @@ -566,12 +566,12 @@ void RegisterCompletionSetEvents(CompletionSet completionSet) { UnregisterCompletionSetEvents(); Debug2.Assert(currentCompletionSet is null); currentCompletionSet = completionSet; - if (!(completionSet is null)) + if (completionSet is not null) completionSet.SelectionStatusChanged += CompletionSet_SelectionStatusChanged; } void UnregisterCompletionSetEvents() { - if (!(currentCompletionSet is null)) { + if (currentCompletionSet is not null) { currentCompletionSet.SelectionStatusChanged -= CompletionSet_SelectionStatusChanged; currentCompletionSet = null; } @@ -596,7 +596,7 @@ void CompletionSession_Dismissed(object? sender, EventArgs e) { control.completionsListBox.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged; control.SizeChanged -= Control_SizeChanged; control.GotKeyboardFocus -= Control_GotKeyboardFocus; - if (!(wpfTextView is null)) + if (wpfTextView is not null) wpfTextView.VisualElement.PreviewKeyDown -= VisualElement_PreviewKeyDown; session.TextView.LayoutChanged -= TextView_LayoutChanged; completionTextElementProvider.Dispose(); @@ -612,7 +612,7 @@ void CompletionSession_Dismissed(object? sender, EventArgs e) { if (string2.IsNullOrEmpty((completion as DsCompletion)?.Suffix)) return null; var elem = CreateFrameworkElement(completion, CompletionClassifierKind.Suffix); - if (!(elem is null)) + if (elem is not null) elem.Margin = new Thickness(5, 0, 2, 0); return elem; } diff --git a/dnSpy/dnSpy/Language/Intellisense/CompletionSession.cs b/dnSpy/dnSpy/Language/Intellisense/CompletionSession.cs index c017a4b82a..8e39e7efc6 100644 --- a/dnSpy/dnSpy/Language/Intellisense/CompletionSession.cs +++ b/dnSpy/dnSpy/Language/Intellisense/CompletionSession.cs @@ -92,7 +92,7 @@ ICompletionSource[] CreateCompletionSources() { if (!TextView.TextDataModel.ContentType.IsOfAnyType(provider.Metadata.ContentTypes)) continue; var source = provider.Value.TryCreateCompletionSource(textBuffer); - if (!(source is null)) + if (source is not null) list.Add(source); } return list.ToArray(); @@ -160,7 +160,7 @@ public void Commit() { customCommit.Commit(); else { var insertionText = completion.InsertionText; - if (!(insertionText is null)) { + if (insertionText is not null) { var replaceSpan = completionSet.ApplicableTo; var buffer = replaceSpan.TextBuffer; var span = replaceSpan.GetSpan(buffer.CurrentSnapshot); @@ -180,7 +180,7 @@ public void Dismiss() { completionSessionCommandTargetFilter?.Close(); completionSessionCommandTargetFilter = null; Dismissed?.Invoke(this, EventArgs.Empty); - if (!(completionSources is null)) { + if (completionSources is not null) { foreach (var source in completionSources) source.Dispose(); completionSources = null; @@ -207,7 +207,7 @@ public bool Match() { if (selectedCompletionSet is null) throw new InvalidOperationException(); selectedCompletionSet.SelectBestMatch(); - return !(selectedCompletionSet.SelectionStatus.Completion is null); + return selectedCompletionSet.SelectionStatus.Completion is not null; } public ITrackingPoint? GetTriggerPoint(ITextBuffer textBuffer) { diff --git a/dnSpy/dnSpy/Language/Intellisense/CompletionSessionCommandTargetFilter.cs b/dnSpy/dnSpy/Language/Intellisense/CompletionSessionCommandTargetFilter.cs index 205e0854f9..f76189e110 100644 --- a/dnSpy/dnSpy/Language/Intellisense/CompletionSessionCommandTargetFilter.cs +++ b/dnSpy/dnSpy/Language/Intellisense/CompletionSessionCommandTargetFilter.cs @@ -33,7 +33,7 @@ sealed class CompletionSessionCommandTargetFilter : ICommandTargetFilter { public CompletionSessionCommandTargetFilter(ICompletionSession completionSession) { this.completionSession = completionSession ?? throw new ArgumentNullException(nameof(completionSession)); dsWpfTextView = completionSession.TextView as IDsWpfTextView; - Debug2.Assert(!(dsWpfTextView is null)); + Debug2.Assert(dsWpfTextView is not null); dsWpfTextView?.CommandTarget.AddFilter(this, CommandTargetFilterOrder.IntellisenseDefaultStatmentCompletion); completionSession.TextView.Caret.PositionChanged += Caret_PositionChanged; diff --git a/dnSpy/dnSpy/Language/Intellisense/CompletionVM.cs b/dnSpy/dnSpy/Language/Intellisense/CompletionVM.cs index 2f46947de3..5e1e3d449c 100644 --- a/dnSpy/dnSpy/Language/Intellisense/CompletionVM.cs +++ b/dnSpy/dnSpy/Language/Intellisense/CompletionVM.cs @@ -99,7 +99,7 @@ IEnumerable CreateAttributeIcons() { var list = new List(); foreach (var icon in icons) { var imageUIObject = CreateImageUIObject(icon); - if (!(imageUIObject is null)) + if (imageUIObject is not null) list.Add(new CompletionIconVM(imageUIObject)); } return list; diff --git a/dnSpy/dnSpy/Language/Intellisense/CurrentLineSpaceReservationService.cs b/dnSpy/dnSpy/Language/Intellisense/CurrentLineSpaceReservationService.cs index 277e3732ab..7a7cc849f9 100644 --- a/dnSpy/dnSpy/Language/Intellisense/CurrentLineSpaceReservationService.cs +++ b/dnSpy/dnSpy/Language/Intellisense/CurrentLineSpaceReservationService.cs @@ -42,7 +42,7 @@ public void SessionCreated(IIntellisenseSession session) { if (!CurrentLineSpaceReservationAgent.IsSupportedSession(session)) return; var wpfTextView = session.TextView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); + Debug2.Assert(wpfTextView is not null); if (wpfTextView is null) return; var currentLineAgent = session.TextView.Properties.GetOrCreateSingletonProperty(typeof(CurrentLineSpaceReservationAgent), () => new CurrentLineSpaceReservationAgent(wpfTextView)); @@ -72,7 +72,7 @@ int ActiveSessions { if ((oldValue != 0) == (activeSessions != 0)) return; if (activeSessions == 0) { - Debug2.Assert(!(spaceReservationManager is null)); + Debug2.Assert(spaceReservationManager is not null); wpfTextView.Caret.PositionChanged -= Caret_PositionChanged; spaceReservationManager.RemoveAgent(this); } diff --git a/dnSpy/dnSpy/Language/Intellisense/IntellisensePresenterFactoryService.cs b/dnSpy/dnSpy/Language/Intellisense/IntellisensePresenterFactoryService.cs index 89d00d722f..5cbcbd9a0f 100644 --- a/dnSpy/dnSpy/Language/Intellisense/IntellisensePresenterFactoryService.cs +++ b/dnSpy/dnSpy/Language/Intellisense/IntellisensePresenterFactoryService.cs @@ -41,13 +41,13 @@ sealed class IntellisensePresenterFactoryService : IIntellisensePresenterFactory public IIntellisensePresenter? TryCreateIntellisensePresenter(IIntellisenseSession session) { if (session is null) throw new ArgumentNullException(nameof(session)); - var contentTypes = session.TextView.BufferGraph.GetTextBuffers(a => !(session.GetTriggerPoint(a) is null)).Select(a => a.ContentType).ToArray(); + var contentTypes = session.TextView.BufferGraph.GetTextBuffers(a => session.GetTriggerPoint(a) is not null).Select(a => a.ContentType).ToArray(); foreach (var lz in intellisensePresenterProviders) { foreach (var contentType in contentTypes) { if (!contentType.IsOfAnyType(lz.Metadata.ContentTypes)) continue; var presenter = lz.Value.TryCreateIntellisensePresenter(session); - if (!(presenter is null)) + if (presenter is not null) return presenter; } } diff --git a/dnSpy/dnSpy/Language/Intellisense/IntellisenseSessionStack.CommandTargetFilter.cs b/dnSpy/dnSpy/Language/Intellisense/IntellisenseSessionStack.CommandTargetFilter.cs index 2bb0939ca5..6ad5231352 100644 --- a/dnSpy/dnSpy/Language/Intellisense/IntellisenseSessionStack.CommandTargetFilter.cs +++ b/dnSpy/dnSpy/Language/Intellisense/IntellisenseSessionStack.CommandTargetFilter.cs @@ -33,7 +33,7 @@ sealed class CommandTargetFilter : ICommandTargetFilter { public CommandTargetFilter(IntellisenseSessionStack owner) { this.owner = owner; wpfTextView = owner.wpfTextView as IDsWpfTextView; - Debug2.Assert(!(wpfTextView is null)); + Debug2.Assert(wpfTextView is not null); } public void HookKeyboard() { @@ -57,7 +57,7 @@ public void UnhookKeyboard() { public CommandTargetStatus CanExecute(Guid group, int cmdId) { if (group == CommandConstants.TextEditorGroup) { - if (!(TryGetIntellisenseKeyboardCommand((TextEditorIds)cmdId) is null)) + if (TryGetIntellisenseKeyboardCommand((TextEditorIds)cmdId) is not null) return CommandTargetStatus.Handled; } return CommandTargetStatus.NotHandled; @@ -71,7 +71,7 @@ public CommandTargetStatus Execute(Guid group, int cmdId, object? args) { public CommandTargetStatus Execute(Guid group, int cmdId, object? args, ref object? result) { if (group == CommandConstants.TextEditorGroup) { var command = TryGetIntellisenseKeyboardCommand((TextEditorIds)cmdId); - if (!(command is null) && owner.ExecuteKeyboardCommand(command.Value)) + if (command is not null && owner.ExecuteKeyboardCommand(command.Value)) return CommandTargetStatus.Handled; } return CommandTargetStatus.NotHandled; diff --git a/dnSpy/dnSpy/Language/Intellisense/IntellisenseSessionStack.cs b/dnSpy/dnSpy/Language/Intellisense/IntellisenseSessionStack.cs index 911d78ee31..cc539a3ffc 100644 --- a/dnSpy/dnSpy/Language/Intellisense/IntellisenseSessionStack.cs +++ b/dnSpy/dnSpy/Language/Intellisense/IntellisenseSessionStack.cs @@ -48,7 +48,7 @@ sealed class SessionState { public IPopupIntellisensePresenter? PopupIntellisensePresenter { get; set; } public SessionState(IIntellisenseSession session) => Session = session; public void SetSpaceReservationManager(ISpaceReservationManager manager) { - if (!(SpaceReservationManager is null)) + if (SpaceReservationManager is not null) throw new InvalidOperationException(); SpaceReservationManager = manager ?? throw new ArgumentNullException(nameof(manager)); } @@ -216,7 +216,7 @@ SessionState GetSessionState(IIntellisenseSession session) { void PresenterUpdated(IIntellisenseSession session) { var sessionState = GetSessionState(session); - if (!(sessionState.SpaceReservationAgent is null)) + if (sessionState.SpaceReservationAgent is not null) sessionState.SpaceReservationManager!.RemoveAgent(sessionState.SpaceReservationAgent); Debug2.Assert(sessionState.SpaceReservationAgent is null); @@ -224,7 +224,7 @@ void PresenterUpdated(IIntellisenseSession session) { if (presenter is IPopupIntellisensePresenter popupPresenter) { if (sessionState.SpaceReservationManager is null) { sessionState.SetSpaceReservationManager(wpfTextView.GetSpaceReservationManager(popupPresenter.SpaceReservationManagerName)); - Debug2.Assert(!(sessionState.SpaceReservationManager is null)); + Debug2.Assert(sessionState.SpaceReservationManager is not null); sessionState.SpaceReservationManager.AgentChanged += SpaceReservationManager_AgentChanged; } UnregisterPopupIntellisensePresenterEvents(sessionState.PopupIntellisensePresenter); @@ -233,7 +233,7 @@ void PresenterUpdated(IIntellisenseSession session) { var presentationSpan = popupPresenter.PresentationSpan; var surfaceElement = popupPresenter.SurfaceElement; - if (!(presentationSpan is null) && !(surfaceElement is null)) { + if (presentationSpan is not null && surfaceElement is not null) { sessionState.SpaceReservationAgent = sessionState.SpaceReservationManager.CreatePopupAgent(presentationSpan, popupPresenter.PopupStyles, surfaceElement); sessionState.SpaceReservationManager.AddAgent(sessionState.SpaceReservationAgent); } @@ -247,7 +247,7 @@ void PresenterUpdated(IIntellisenseSession session) { } void RegisterPopupIntellisensePresenterEvents(IPopupIntellisensePresenter? popupPresenter) { - if (!(popupPresenter is null)) { + if (popupPresenter is not null) { popupPresenter.PopupStylesChanged += PopupIntellisensePresenter_PopupStylesChanged; popupPresenter.PresentationSpanChanged += PopupIntellisensePresenter_PresentationSpanChanged; popupPresenter.SurfaceElementChanged += PopupIntellisensePresenter_SurfaceElementChanged; @@ -255,7 +255,7 @@ void RegisterPopupIntellisensePresenterEvents(IPopupIntellisensePresenter? popup } void UnregisterPopupIntellisensePresenterEvents(IPopupIntellisensePresenter? popupPresenter) { - if (!(popupPresenter is null)) { + if (popupPresenter is not null) { popupPresenter.PopupStylesChanged -= PopupIntellisensePresenter_PopupStylesChanged; popupPresenter.PresentationSpanChanged -= PopupIntellisensePresenter_PresentationSpanChanged; popupPresenter.SurfaceElementChanged -= PopupIntellisensePresenter_SurfaceElementChanged; @@ -277,7 +277,7 @@ void PopupIntellisensePresenter_PropertyChanged(IPopupIntellisensePresenter popu return; } var sessionState = TryGetSessionState(popupPresenter); - Debug2.Assert(!(sessionState is null)); + Debug2.Assert(sessionState is not null); if (sessionState is null) return; if (propertyName == nameof(popupPresenter.PresentationSpan) || propertyName == nameof(popupPresenter.PopupStyles)) { @@ -295,7 +295,7 @@ void SpaceReservationManager_AgentChanged(object? sender, SpaceReservationAgentC if (wpfTextView.IsClosed) return; var sessionState = TryGetSessionState(e.OldAgent); - if (!(sessionState is null)) { + if (sessionState is not null) { sessionState.SpaceReservationAgent = null; // Its popup was hidden, so dismiss the session sessionState.Session.Dismiss(); @@ -304,7 +304,7 @@ void SpaceReservationManager_AgentChanged(object? sender, SpaceReservationAgentC void Session_Dismissed(object? sender, EventArgs e) { var session = sender as IIntellisenseSession; - Debug2.Assert(!(session is null)); + Debug2.Assert(session is not null); if (session is null) return; int index = sessions.IndexOf(session); @@ -321,9 +321,9 @@ void RemoveSessionAt(int index) { session.Dismissed -= Session_Dismissed; session.PresenterChanged -= Session_PresenterChanged; var sessionState = GetSessionState(session); - if (!(sessionState.SpaceReservationAgent is null)) + if (sessionState.SpaceReservationAgent is not null) sessionState.SpaceReservationManager!.RemoveAgent(sessionState.SpaceReservationAgent); - if (!(sessionState.SpaceReservationManager is null)) + if (sessionState.SpaceReservationManager is not null) sessionState.SpaceReservationManager.AgentChanged -= SpaceReservationManager_AgentChanged; UnregisterPopupIntellisensePresenterEvents(sessionState.PopupIntellisensePresenter); sessionStates.Remove(sessionState); diff --git a/dnSpy/dnSpy/Language/Intellisense/QuickInfoPresenter.cs b/dnSpy/dnSpy/Language/Intellisense/QuickInfoPresenter.cs index aabd63d9a7..897fb07950 100644 --- a/dnSpy/dnSpy/Language/Intellisense/QuickInfoPresenter.cs +++ b/dnSpy/dnSpy/Language/Intellisense/QuickInfoPresenter.cs @@ -34,7 +34,7 @@ sealed class QuickInfoPresenter : QuickInfoPresenterBase, ICustomIntellisensePre public QuickInfoPresenter(IQuickInfoSession session) : base(session) { wpfTextView = session.TextView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); + Debug2.Assert(wpfTextView is not null); popup = new Popup { PlacementTarget = wpfTextView?.VisualElement, Placement = PlacementMode.Relative, @@ -63,12 +63,12 @@ bool RenderCore() { return false; var point = session.GetTriggerPoint(session.TextView.TextSnapshot); - Debug2.Assert(!(point is null)); + Debug2.Assert(point is not null); if (point is null) return false; var line = session.TextView.TextViewLines.GetTextViewLineContainingBufferPosition(point.Value); - Debug2.Assert(!(line is null) && line.VisibilityState != VisibilityState.Unattached); + Debug2.Assert(line is not null && line.VisibilityState != VisibilityState.Unattached); if (line is null || line.VisibilityState == VisibilityState.Unattached) return false; @@ -103,7 +103,7 @@ void DismissIfNeeded(MouseEventArgs e) { } bool ShouldDismiss(MouseEventArgs e) { - Debug2.Assert(!(wpfTextView is null)); + Debug2.Assert(wpfTextView is not null); var mousePos = GetMousePoint(e.MouseDevice); if (mousePos is null) return true; @@ -147,7 +147,7 @@ void ClosePopup() { protected override void OnSessionDismissed() { ClosePopup(); - if (!(wpfTextView is null)) { + if (wpfTextView is not null) { wpfTextView.VisualElement.MouseLeave -= VisualElement_MouseLeave; wpfTextView.VisualElement.MouseMove -= VisualElement_MouseMove; popup.RemoveHandler(UIElement.MouseLeaveEvent, new MouseEventHandler(Popup_MouseLeave)); diff --git a/dnSpy/dnSpy/Language/Intellisense/QuickInfoSession.cs b/dnSpy/dnSpy/Language/Intellisense/QuickInfoSession.cs index c001193960..e181e7d14b 100644 --- a/dnSpy/dnSpy/Language/Intellisense/QuickInfoSession.cs +++ b/dnSpy/dnSpy/Language/Intellisense/QuickInfoSession.cs @@ -81,7 +81,7 @@ IQuickInfoSource[] CreateQuickInfoSources() { if (!TextView.TextDataModel.ContentType.IsOfAnyType(provider.Metadata.ContentTypes)) continue; var source = provider.Value.TryCreateQuickInfoSource(textBuffer); - if (!(source is null)) { + if (source is not null) { if (list is null) list = new List(); list.Add(source); @@ -91,7 +91,7 @@ IQuickInfoSource[] CreateQuickInfoSources() { } void DisposeQuickInfoSources() { - if (!(quickInfoSources is null)) { + if (quickInfoSources is not null) { foreach (var source in quickInfoSources) source.Dispose(); quickInfoSources = null; diff --git a/dnSpy/dnSpy/Language/Intellisense/SignatureHelpCurrentParameterTagger.cs b/dnSpy/dnSpy/Language/Intellisense/SignatureHelpCurrentParameterTagger.cs index 46f941258e..2333f26cb0 100644 --- a/dnSpy/dnSpy/Language/Intellisense/SignatureHelpCurrentParameterTagger.cs +++ b/dnSpy/dnSpy/Language/Intellisense/SignatureHelpCurrentParameterTagger.cs @@ -105,7 +105,7 @@ public SignatureHelpCurrentParameterTaggerEx(ITextBuffer buffer, ClassificationT public IEnumerable> GetTags(NormalizedSnapshotSpanCollection spans) { var context = buffer.TryGetSignatureHelpClassifierContext(); - Debug2.Assert(!(context is null)); + Debug2.Assert(context is not null); if (context is null || context.Session.IsDismissed) yield break; ClassificationTag tag; diff --git a/dnSpy/dnSpy/Language/Intellisense/SignatureHelpPresenter.cs b/dnSpy/dnSpy/Language/Intellisense/SignatureHelpPresenter.cs index 856ec64f2b..b84f1dc41a 100644 --- a/dnSpy/dnSpy/Language/Intellisense/SignatureHelpPresenter.cs +++ b/dnSpy/dnSpy/Language/Intellisense/SignatureHelpPresenter.cs @@ -61,7 +61,7 @@ event EventHandler>? IPopupIntellisensePresen public bool HasParameter { get { var parameter = session.SelectedSignature?.CurrentParameter; - return !(parameter is null) && + return parameter is not null && !string.IsNullOrEmpty(parameter.Documentation) && !string.IsNullOrEmpty(parameter.Name); } @@ -118,7 +118,7 @@ public SignatureHelpPresenter(ISignatureHelpSession session, ITextBufferFactoryS this.classifierAggregatorService = classifierAggregatorService ?? throw new ArgumentNullException(nameof(classifierAggregatorService)); this.classificationFormatMap = classificationFormatMap ?? throw new ArgumentNullException(nameof(classificationFormatMap)); defaultExtendedContentType = contentTypeRegistryService.GetContentType(DefaultExtendedContentTypeName); - Debug2.Assert(!(defaultExtendedContentType is null)); + Debug2.Assert(defaultExtendedContentType is not null); classificationFormatMap.ClassificationFormatMappingChanged += ClassificationFormatMap_ClassificationFormatMappingChanged; session.Dismissed += Session_Dismissed; session.SelectedSignatureChanged += Session_SelectedSignatureChanged; @@ -238,7 +238,7 @@ void Signatures_CollectionChanged(object? sender, NotifyCollectionChangedEventAr var doc = signature?.Documentation; if (string2.IsNullOrEmpty(doc)) return null; - Debug2.Assert(!(signature is null)); + Debug2.Assert(signature is not null); return CreateUIObject(doc, GetExtendedClassifierContentType(), new SignatureDocumentationSignatureHelpClassifierContext(session, signature)); } @@ -263,8 +263,8 @@ void Signatures_CollectionChanged(object? sender, NotifyCollectionChangedEventAr signatureTextBuffer.Replace(new Span(0, signatureTextBuffer.CurrentSnapshot.Length), text); var oldContentType = signatureTextBuffer.ContentType; var atSpan = signature.ApplicableToSpan; - Debug2.Assert(!(atSpan is null)); - if (!(atSpan is null)) { + Debug2.Assert(atSpan is not null); + if (atSpan is not null) { var span = atSpan.GetStartPoint(atSpan.TextBuffer.CurrentSnapshot); signatureTextBuffer.ChangeContentType(GetSigHelpContentType(span.Snapshot.ContentType), null); } diff --git a/dnSpy/dnSpy/Language/Intellisense/SignatureHelpSession.cs b/dnSpy/dnSpy/Language/Intellisense/SignatureHelpSession.cs index 47573d706f..49b7f4adbb 100644 --- a/dnSpy/dnSpy/Language/Intellisense/SignatureHelpSession.cs +++ b/dnSpy/dnSpy/Language/Intellisense/SignatureHelpSession.cs @@ -90,7 +90,7 @@ void Caret_PositionChanged(object? sender, CaretPositionChangedEventArgs e) { sigsToRemove.Add(i); } } - if (!(sigsToRemove is null)) { + if (sigsToRemove is not null) { for (int i = sigsToRemove.Count - 1; i >= 0; i--) signatures.RemoveAt(sigsToRemove[i]); } @@ -125,7 +125,7 @@ ISignatureHelpSource[] CreateSignatureHelpSources() { if (!TextView.TextDataModel.ContentType.IsOfAnyType(provider.Metadata.ContentTypes)) continue; var source = provider.Value.TryCreateSignatureHelpSource(textBuffer); - if (!(source is null)) + if (source is not null) list.Add(source); } return list.ToArray(); @@ -171,7 +171,7 @@ public void Recalculate() { } void DisposeSignatureHelpSources() { - if (!(signatureHelpSources is null)) { + if (signatureHelpSources is not null) { foreach (var source in signatureHelpSources) source.Dispose(); signatureHelpSources = null; @@ -201,7 +201,7 @@ public bool Match() { foreach (var source in signatureHelpSources) { var signature = source.GetBestMatch(this); - if (!(signature is null)) { + if (signature is not null) { SelectedSignature = signature; return true; } diff --git a/dnSpy/dnSpy/Language/Intellisense/WpfUtils.cs b/dnSpy/dnSpy/Language/Intellisense/WpfUtils.cs index 9e1232d0f1..afb19f69fa 100644 --- a/dnSpy/dnSpy/Language/Intellisense/WpfUtils.cs +++ b/dnSpy/dnSpy/Language/Intellisense/WpfUtils.cs @@ -37,7 +37,7 @@ public static void ScrollSelectedItemIntoView(ListBox lb, bool center) { if (!center) return; var scrollViewer = TryGetScrollViewer(lb); - if (!(scrollViewer is null)) { + if (scrollViewer is not null) { int index = lb.Items.IndexOf(item); int itemsPerPage = (int)Math.Max(1, Math.Floor(scrollViewer.ViewportHeight)); scrollViewer.ScrollToVerticalOffset(Math.Max(0, index - itemsPerPage / 2)); @@ -52,7 +52,7 @@ public static void ScrollSelectedItemIntoView(ListBox lb, bool center) { return res; var res2 = FindVisualChild(child); - if (!(res2 is null)) + if (res2 is not null) return res2; } diff --git a/dnSpy/dnSpy/MainApp/App.xaml.cs b/dnSpy/dnSpy/MainApp/App.xaml.cs index f5e4486949..214480bf3f 100644 --- a/dnSpy/dnSpy/MainApp/App.xaml.cs +++ b/dnSpy/dnSpy/MainApp/App.xaml.cs @@ -159,7 +159,7 @@ static string GetCachedCompositionConfigurationFilename() { } IExportProviderFactory? TryCreateExportProviderFactoryCachedCore(Resolver resolver, out long resourceManagerTokensOffset) { - Debug2.Assert(!(mefAssemblies is null)); + Debug2.Assert(mefAssemblies is not null); resourceManagerTokensOffset = -1; var filename = GetCachedCompositionConfigurationFilename(); if (!File.Exists(filename)) @@ -213,7 +213,7 @@ IExportProviderFactory CreateExportProviderFactorySlow(Resolver resolver) { bool writingCachedMefFile; async Task SaveMefStateAsync(CompositionConfiguration config) { - Debug2.Assert(!(mefAssemblies is null)); + Debug2.Assert(mefAssemblies is not null); string filename = GetCachedCompositionConfigurationFilename(); bool fileCreated = false; bool deleteFile = true; @@ -253,7 +253,7 @@ void OnTokensUpdated() { } void UpdateResourceManagerTokens() { - Debug2.Assert(!(mefAssemblies is null)); + Debug2.Assert(mefAssemblies is not null); var tokensOffset = resourceManagerTokensOffset; if (tokensOffset < 0) return; @@ -475,12 +475,12 @@ unsafe IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bo } void MainWindow_SourceInitialized(object? sender, EventArgs e) { - Debug2.Assert(!(appWindow is null)); + Debug2.Assert(appWindow is not null); appWindow.MainWindow.SourceInitialized -= MainWindow_SourceInitialized; var hwndSource = PresentationSource.FromVisual(appWindow.MainWindow) as HwndSource; - Debug2.Assert(!(hwndSource is null)); - if (!(hwndSource is null)) + Debug2.Assert(hwndSource is not null); + if (hwndSource is not null) hwndSource.AddHook(WndProc); } @@ -489,7 +489,7 @@ void App_Exit(object? sender, ExitEventArgs e) { dsLoaderService?.Save(); try { var settingsService = exportProvider?.GetExportedValue(); - if (!(settingsService is null)) + if (settingsService is not null) new XmlSettingsWriter(settingsService).Write(); } catch { @@ -508,12 +508,12 @@ void UIFixes() { void FixEditorContextMenuStyle() { var module = typeof(ContextMenu).Module; var type = module.GetType("System.Windows.Documents.TextEditorContextMenu+EditorContextMenu", false, false); - Debug2.Assert(!(type is null)); + Debug2.Assert(type is not null); if (type is null) return; const string styleKey = "EditorContextMenuStyle"; var style = Resources[styleKey]; - Debug2.Assert(!(style is null)); + Debug2.Assert(style is not null); if (style is null) return; Resources.Remove(styleKey); @@ -571,16 +571,16 @@ void DsLoaderService_OnAppLoaded(object? sender, EventArgs e) { static void ShowElapsedTime(Stopwatch sw) => MsgBox.Instance.Show($"{sw.ElapsedMilliseconds} ms, {sw.ElapsedTicks} ticks"); void HandleAppArgs(IAppCommandLineArgs appArgs) { - Debug2.Assert(!(exportProvider is null)); - Debug2.Assert(!(appWindow is null)); + Debug2.Assert(exportProvider is not null); + Debug2.Assert(appWindow is not null); if (appArgs.Activate && appWindow.MainWindow.WindowState == WindowState.Minimized) WindowUtils.SetState(appWindow.MainWindow, WindowState.Normal); var decompiler = GetDecompiler(appArgs.Language); - if (!(decompiler is null)) + if (decompiler is not null) exportProvider.GetExportedValue().Decompiler = decompiler; - if (!(appArgs.FullScreen is null)) + if (appArgs.FullScreen is not null) appWindow.MainWindow.IsFullScreen = appArgs.FullScreen.Value; if (appArgs.NewTab) @@ -601,20 +601,20 @@ void HandleAppArgs(IAppCommandLineArgs appArgs) { } void HandleAppArgs2(IAppCommandLineArgs appArgs) { - Debug2.Assert(!(exportProvider is null)); + Debug2.Assert(exportProvider is not null); foreach (var handler in exportProvider.GetExports().OrderBy(a => a.Value.Order)) handler.Value.OnNewArgs(appArgs); } IDecompiler? GetDecompiler(string language) { - Debug2.Assert(!(exportProvider is null)); + Debug2.Assert(exportProvider is not null); if (string.IsNullOrEmpty(language)) return null; var decompilerService = exportProvider.GetExportedValue(); if (Guid.TryParse(language, out var guid)) { var lang = decompilerService.Find(guid); - if (!(lang is null)) + if (lang is not null) return lang; } diff --git a/dnSpy/dnSpy/MainApp/AppCommandLineArgsHandler.cs b/dnSpy/dnSpy/MainApp/AppCommandLineArgsHandler.cs index 460e41fad2..2c51e81a05 100644 --- a/dnSpy/dnSpy/MainApp/AppCommandLineArgsHandler.cs +++ b/dnSpy/dnSpy/MainApp/AppCommandLineArgsHandler.cs @@ -46,7 +46,7 @@ public void OnNewArgs(IAppCommandLineArgs args) { toolWindowService.Close(info.Guid); foreach (var info in GetToolWindowInfos(args.ShowToolWindow)) { var content = toolWindowService.Show(info.Guid, info.Location); - Debug2.Assert(!(content is null)); + Debug2.Assert(content is not null); if (content is null) continue; if (info.Location is null) diff --git a/dnSpy/dnSpy/MainApp/AppWindow.cs b/dnSpy/dnSpy/MainApp/AppWindow.cs index cfaf007f50..b7135002e9 100644 --- a/dnSpy/dnSpy/MainApp/AppWindow.cs +++ b/dnSpy/dnSpy/MainApp/AppWindow.cs @@ -114,8 +114,8 @@ public void Write() { static string CalculateAssemblyInformationalVersion(Assembly asm) { var attrs = asm.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); var attr = attrs.Length == 0 ? null : attrs[0] as AssemblyInformationalVersionAttribute; - Debug2.Assert(!(attr is null)); - if (!(attr is null)) + Debug2.Assert(attr is not null); + if (attr is not null) return attr.InformationalVersion; return asm.GetName().Version!.ToString(); } @@ -180,7 +180,7 @@ void MainWindow_Closing(object? sender, CancelEventArgs e) { void MainWindow_GotKeyboardFocus(object? sender, KeyboardFocusChangedEventArgs e) { if (e.NewFocus == MainWindow) { var g = documentTabService.TabGroupService.ActiveTabGroup; - if (!(g is null) && !(g.ActiveTabContent is null)) { + if (g is not null && g.ActiveTabContent is not null) { g.SetFocus(g.ActiveTabContent); e.Handled = true; return; @@ -201,7 +201,7 @@ public event EventHandler MainWindowClosed { readonly WeakEventList mainWindowClosed; public void RefreshToolBar() { - if (!(mainWindow is null)) + if (mainWindow is not null) appToolBar.Initialize(mainWindow); } diff --git a/dnSpy/dnSpy/MainApp/DsLoaderService.cs b/dnSpy/dnSpy/MainApp/DsLoaderService.cs index defe56f14a..ec51772175 100644 --- a/dnSpy/dnSpy/MainApp/DsLoaderService.cs +++ b/dnSpy/dnSpy/MainApp/DsLoaderService.cs @@ -56,12 +56,12 @@ sealed class DsLoaderService : IDsLoaderService { } public void Initialize(IDsLoaderContentProvider content, Window window, IAppCommandLineArgs args) { - Debug2.Assert(!(windowLoader is null)); + Debug2.Assert(windowLoader is not null); windowLoader.Initialize(content, window, args); } internal void LoadAllCodeFinished() { - Debug2.Assert(!(windowLoader is null)); + Debug2.Assert(windowLoader is not null); windowLoader = null; OnAppLoaded?.Invoke(this, EventArgs.Empty); } diff --git a/dnSpy/dnSpy/MainApp/MainWindowControl.cs b/dnSpy/dnSpy/MainApp/MainWindowControl.cs index 9175cc201a..9e11906a54 100644 --- a/dnSpy/dnSpy/MainApp/MainWindowControl.cs +++ b/dnSpy/dnSpy/MainApp/MainWindowControl.cs @@ -80,19 +80,19 @@ static bool IsValid(AppToolWindowLocation value) => value == AppToolWindowLocation.Bottom; public void Write(ISettingsSection section) { - Debug2.Assert(!(HorizontalContentState is null) && !(VerticalContentState is null)); - if (!(HorizontalContentState is null)) + Debug2.Assert(HorizontalContentState is not null && VerticalContentState is not null); + if (HorizontalContentState is not null) StackedContentStateSerializer.Serialize(section.GetOrCreateSection(HORIZONTALCONTENT_SECT), HorizontalContentState); - if (!(VerticalContentState is null)) + if (VerticalContentState is not null) StackedContentStateSerializer.Serialize(section.GetOrCreateSection(VERTICALCONTENT_SECT), VerticalContentState); - Debug2.Assert(!(LeftState is null) && !(RightState is null) && !(TopState is null) && !(BottomState is null)); - if (!(LeftState is null)) + Debug2.Assert(LeftState is not null && RightState is not null && TopState is not null && BottomState is not null); + if (LeftState is not null) ToolWindowUIState.Serialize(section.CreateSection(TOOLWINDOWUI_SECT), LeftState); - if (!(RightState is null)) + if (RightState is not null) ToolWindowUIState.Serialize(section.CreateSection(TOOLWINDOWUI_SECT), RightState); - if (!(TopState is null)) + if (TopState is not null) ToolWindowUIState.Serialize(section.CreateSection(TOOLWINDOWUI_SECT), TopState); - if (!(BottomState is null)) + if (BottomState is not null) ToolWindowUIState.Serialize(section.CreateSection(TOOLWINDOWUI_SECT), BottomState); foreach (var kv in SavedLocations) { var sect = section.CreateSection(LOCATION_SECT); @@ -192,8 +192,8 @@ public static void Serialize(ISettingsSection section, ToolWindowUIState state) section.Attribute(ISHORIZONTAL_ATTR, state.IsHorizontal); foreach (var content in state.Groups) ToolWindowGroupState.Serialize(section.CreateSection(GROUP_SECT), content); - Debug2.Assert(!(state.StackedContentState is null)); - if (!(state.StackedContentState is null)) + Debug2.Assert(state.StackedContentState is not null); + if (state.StackedContentState is not null) StackedContentStateSerializer.Serialize(section.GetOrCreateSection(STACKEDCONTENTSTATE_SECTION), state.StackedContentState); } } @@ -330,7 +330,7 @@ public void Initialize(IStackedContentChild mainChild, MainWindowControlState st foreach (var kv in state.SavedLocations) savedLocations[kv.Key] = kv.Value; - if (!(state.LeftState is null) && !(state.RightState is null) && !(state.TopState is null) && !(state.BottomState is null)) { + if (state.LeftState is not null && state.RightState is not null && state.TopState is not null && state.BottomState is not null) { state.LeftState.Restore(this, toolWindowUIs[AppToolWindowLocation.Left]); state.RightState.Restore(this, toolWindowUIs[AppToolWindowLocation.Right]); state.TopState.Restore(this, toolWindowUIs[AppToolWindowLocation.Top]); @@ -339,7 +339,7 @@ public void Initialize(IStackedContentChild mainChild, MainWindowControlState st else RestoreDefault(); - if (!(state.HorizontalContentState is null) && !(state.VerticalContentState is null)) { + if (state.HorizontalContentState is not null && state.VerticalContentState is not null) { horizontalContent.State = state.HorizontalContentState; verticalContent.State = state.VerticalContentState; } @@ -422,7 +422,7 @@ void Show(ToolWindowContent content, AppToolWindowLocation location, bool active if (content is null) throw new ArgumentNullException(nameof(content)); var t = GetToolWindowGroup(content); - if (!(t is null)) { + if (t is not null) { if (active) t.Value.group.ActiveTabContent = content; if (focus) @@ -457,7 +457,7 @@ internal bool TryAdd(ToolWindowUI ui, IToolWindowGroup g, Guid guid) { var content = Create(guid); if (content is null) return false; - if (!(GetToolWindowGroup(content) is null)) + if (GetToolWindowGroup(content) is not null) return false; g.Add(content); @@ -475,8 +475,8 @@ internal void Show(ToolWindowUI ui) { ui.IsAdded = true; } - public bool IsShown(ToolWindowContent content) => !(GetToolWindowGroup(content) is null); - public bool IsShown(Guid guid) => !(GetToolWindowGroup(guid) is null); + public bool IsShown(ToolWindowContent content) => GetToolWindowGroup(content) is not null; + public bool IsShown(Guid guid) => GetToolWindowGroup(guid) is not null; void Hide(ToolWindowUI ui) { Debug.Assert(!ui.ToolWindowGroupService.TabGroups.Any()); @@ -504,7 +504,7 @@ void SaveLength(ToolWindowUI ui) { ToolWindowContent? Show(Guid guid, AppToolWindowLocation location, bool active, bool focus) { var content = Create(guid); - Debug2.Assert(!(content is null)); + Debug2.Assert(content is not null); if (content is null) return null; Show(content, location, active, focus); @@ -514,7 +514,7 @@ void SaveLength(ToolWindowUI ui) { ToolWindowContent? Create(Guid guid) { foreach (var provider in mainToolWindowContentProviders) { var content = provider.Value.GetOrCreate(guid); - if (!(content is null)) + if (content is not null) return content; } return null; @@ -559,7 +559,7 @@ public void Close(ToolWindowContent content) { if (content is null) throw new ArgumentNullException(nameof(content)); var t = GetToolWindowGroup(content); - Debug2.Assert(!(t is null)); + Debug2.Assert(t is not null); if (t is null) throw new InvalidOperationException(); t.Value.group.Close(content); @@ -596,7 +596,7 @@ public void Move(ToolWindowContent? content, AppToolWindowLocation location) { location = Convert(location); if (t is null || t.Value.ui.Location == location) return; - Debug2.Assert(!(content is null)); + Debug2.Assert(content is not null); var g = GetOrCreateGroup(location); t.Value.group.MoveTo(g, content); @@ -623,13 +623,13 @@ public void Move(IToolWindowGroup group, AppToolWindowLocation location) { return; var activeContent = t.Value.group.ActiveTabContent; - Debug2.Assert(!(activeContent is null)); + Debug2.Assert(activeContent is not null); foreach (var c in t.Value.group.TabContents.ToArray()) Move(c, location); - if (!(activeContent is null)) { + if (activeContent is not null) { var t2 = GetToolWindowGroup(activeContent); - Debug2.Assert(!(t2 is null)); - if (!(t2 is null)) { + Debug2.Assert(t2 is not null); + if (t2 is not null) { t2.Value.group.ActiveTabContent = activeContent; } } diff --git a/dnSpy/dnSpy/MainApp/MessageBoxService.cs b/dnSpy/dnSpy/MainApp/MessageBoxService.cs index aaf145f611..391d8a87a5 100644 --- a/dnSpy/dnSpy/MainApp/MessageBoxService.cs +++ b/dnSpy/dnSpy/MainApp/MessageBoxService.cs @@ -99,7 +99,7 @@ public MsgBoxButton Show(string message, MsgBoxButton buttons, Window? ownerWind public void Show(Exception exception, string? msg, Window? ownerWindow) { string msgToShow; - if (!(exception is null)) { + if (exception is not null) { msgToShow = $"{msg ?? dnSpy_Resources.ExceptionMessage}\n\n{exception.ToString()}"; const int MAX_LEN = 2048; if (msgToShow.Length > MAX_LEN) diff --git a/dnSpy/dnSpy/MainApp/ResourceManagerTokenCacheImpl.cs b/dnSpy/dnSpy/MainApp/ResourceManagerTokenCacheImpl.cs index a7a2a5f5d4..edd18dff02 100644 --- a/dnSpy/dnSpy/MainApp/ResourceManagerTokenCacheImpl.cs +++ b/dnSpy/dnSpy/MainApp/ResourceManagerTokenCacheImpl.cs @@ -47,8 +47,8 @@ public override void SetResourceManagerGetMethodMetadataToken(Assembly assembly, } public void SetTokens(Assembly[] assemblies, int[] tokens) { - Debug2.Assert(!(assemblies is null)); - Debug2.Assert(!(tokens is null)); + Debug2.Assert(assemblies is not null); + Debug2.Assert(tokens is not null); Debug.Assert(assemblies.Length == tokens.Length); lock (lockObj) { for (int i = 0; i < assemblies.Length; i++) { diff --git a/dnSpy/dnSpy/MainApp/SavedWindowState.cs b/dnSpy/dnSpy/MainApp/SavedWindowState.cs index 2f17ede5b7..3b67f6fd36 100644 --- a/dnSpy/dnSpy/MainApp/SavedWindowState.cs +++ b/dnSpy/dnSpy/MainApp/SavedWindowState.cs @@ -35,8 +35,8 @@ public SavedWindowState() { public SavedWindowState(MetroWindow window) { Bounds = window.RestoreBounds; var source = PresentationSource.FromVisual(window); - Debug2.Assert(!(source is null)); - if (!(source is null)) { + Debug2.Assert(source is not null); + if (source is not null) { var t = Bounds; t = Rect.Transform(Bounds, source.CompositionTarget.TransformToDevice); Bounds = new Rect(t.TopLeft, Bounds.Size); diff --git a/dnSpy/dnSpy/MainApp/Settings/FontAppSettingsPage.cs b/dnSpy/dnSpy/MainApp/Settings/FontAppSettingsPage.cs index d50eea1b55..30e1ee6649 100644 --- a/dnSpy/dnSpy/MainApp/Settings/FontAppSettingsPage.cs +++ b/dnSpy/dnSpy/MainApp/Settings/FontAppSettingsPage.cs @@ -211,7 +211,7 @@ public FontFamilyVM(FontFamily ff) { public override bool Equals(object? obj) { var other = obj as FontFamilyVM; - return !(other is null) && + return other is not null && FontFamily.Equals(other.FontFamily); } diff --git a/dnSpy/dnSpy/MainApp/Settings/GeneralAppSettingsPage.cs b/dnSpy/dnSpy/MainApp/Settings/GeneralAppSettingsPage.cs index c970727164..2f898b3ee6 100644 --- a/dnSpy/dnSpy/MainApp/Settings/GeneralAppSettingsPage.cs +++ b/dnSpy/dnSpy/MainApp/Settings/GeneralAppSettingsPage.cs @@ -169,7 +169,7 @@ public GeneralAppSettingsPage(IThemeServiceImpl themeService, IWindowsExplorerIn if (!ThemesVM.Any(a => a.Theme == themeService.Theme)) ThemesVM.Add(new ThemeVM(themeService.Theme)); SelectedThemeVM = ThemesVM.FirstOrDefault(a => a.Theme == themeService.Theme); - Debug2.Assert(!(SelectedThemeVM is null)); + Debug2.Assert(SelectedThemeVM is not null); WindowsExplorerIntegration = windowsExplorerIntegrationService.WindowsExplorerIntegration; AllowMoreThanOneInstance = appSettings.AllowMoreThanOneInstance; @@ -183,7 +183,7 @@ public GeneralAppSettingsPage(IThemeServiceImpl themeService, IWindowsExplorerIn public override void OnApply() => throw new InvalidOperationException(); public void OnApply(IAppRefreshSettings appRefreshSettings) { - if (!(SelectedThemeVM is null)) + if (SelectedThemeVM is not null) themeService.Theme = SelectedThemeVM.Theme; windowsExplorerIntegrationService.WindowsExplorerIntegration = WindowsExplorerIntegration; appSettings.AllowMoreThanOneInstance = AllowMoreThanOneInstance; diff --git a/dnSpy/dnSpy/MainApp/Settings/WindowsExplorerIntegration.cs b/dnSpy/dnSpy/MainApp/Settings/WindowsExplorerIntegration.cs index 2f54392ab4..fa49ab5bb9 100644 --- a/dnSpy/dnSpy/MainApp/Settings/WindowsExplorerIntegration.cs +++ b/dnSpy/dnSpy/MainApp/Settings/WindowsExplorerIntegration.cs @@ -58,7 +58,7 @@ public bool? WindowsExplorerIntegration { continue; using (var key = Registry.CurrentUser.OpenSubKey(@"Software\Classes\" + name + @"\shell\" + EXPLORER_MENU_TEXT)) { - if (!(key is null)) + if (key is not null) count++; } } diff --git a/dnSpy/dnSpy/MainApp/ToolBarCommands.cs b/dnSpy/dnSpy/MainApp/ToolBarCommands.cs index a3c6b96467..881ecdf649 100644 --- a/dnSpy/dnSpy/MainApp/ToolBarCommands.cs +++ b/dnSpy/dnSpy/MainApp/ToolBarCommands.cs @@ -103,7 +103,7 @@ sealed class FullScreenToolbarCommand : ToolBarButtonBase, IToolBarToggleButton AppWindow? appWindow = null; public Binding GetBinding(IToolBarItemContext context) { - Debug2.Assert(!(appWindow is null) && !(appWindow.MainWindow is null)); + Debug2.Assert(appWindow is not null && appWindow.MainWindow is not null); return new Binding(nameof(appWindow.MainWindow.IsFullScreen)) { Source = appWindow.MainWindow, }; @@ -114,7 +114,7 @@ public override void Execute(IToolBarItemContext context) { bool initd = false; public override bool IsVisible(IToolBarItemContext context) { - Debug2.Assert(!(appWindow is null) && !(appWindow.MainWindow is null)); + Debug2.Assert(appWindow is not null && appWindow.MainWindow is not null); if (!initd) { appWindow.MainWindow.IsFullScreenChanged += (s, e) => appWindow.RefreshToolBar(); initd = true; diff --git a/dnSpy/dnSpy/Menus/ContextMenuProvider.cs b/dnSpy/dnSpy/Menus/ContextMenuProvider.cs index c14113b118..3c26f7f94a 100644 --- a/dnSpy/dnSpy/Menus/ContextMenuProvider.cs +++ b/dnSpy/dnSpy/Menus/ContextMenuProvider.cs @@ -49,7 +49,7 @@ bool IsIgnored(object? sender, ContextMenuEventArgs e) { return false; var o = e.OriginalSource as DependencyObject; - while (!(o is null)) { + while (o is not null) { if (o == element) return false; diff --git a/dnSpy/dnSpy/Menus/MenuItemContext.cs b/dnSpy/dnSpy/Menus/MenuItemContext.cs index 8ba78646ca..1f707c8cf9 100644 --- a/dnSpy/dnSpy/Menus/MenuItemContext.cs +++ b/dnSpy/dnSpy/Menus/MenuItemContext.cs @@ -36,17 +36,17 @@ public MenuItemContext(Guid menuGuid, bool openedFromKeyboard, GuidObject creato OpenedFromKeyboard = openedFromKeyboard; this.guidObjects = new List(); this.guidObjects.Add(creatorObject); - if (!(guidObjects is null)) + if (guidObjects is not null) this.guidObjects.AddRange(guidObjects); state = new Dictionary(); } public T? GetOrCreateState(object key, Func createState) where T : class { - Debug2.Assert(!(key is null)); + Debug2.Assert(key is not null); T? value; if (state.TryGetValue(key, out var o)) { value = o as T; - Debug2.Assert(o is null || !(value is null)); + Debug2.Assert(o is null || value is not null); return value; } value = createState(); diff --git a/dnSpy/dnSpy/Menus/MenuService.cs b/dnSpy/dnSpy/Menus/MenuService.cs index 5701343eeb..e649610fa8 100644 --- a/dnSpy/dnSpy/Menus/MenuService.cs +++ b/dnSpy/dnSpy/Menus/MenuService.cs @@ -90,13 +90,13 @@ public IContextMenuProvider InitializeContextMenu(FrameworkElement elem, string InitializeContextMenu(elem, new Guid(guid), provider, initCtxMenu, ctxMenuGuid is null ? (Guid?)null : new Guid(ctxMenuGuid)); void InitializeMenuItemObjects() { - if (!(guidToGroups is null)) + if (guidToGroups is not null) return; InitializeMenus(); - Debug2.Assert(!(guidToMenu is null)); + Debug2.Assert(guidToMenu is not null); InitializeMenuItems(); - Debug2.Assert(!(guidToGroups is null)); + Debug2.Assert(guidToGroups is not null); } void InitializeMenus() { @@ -152,7 +152,7 @@ void InitializeMenuItems() { continue; var guidString = item.Metadata.Guid; - if (!(guidString is null)) { + if (guidString is not null) { b = Guid.TryParse(guidString, out var guid); Debug.Assert(b, $"MenuItem: Couldn't parse Guid property: '{guidString}'"); if (!b) @@ -202,7 +202,7 @@ internal static bool ParseGroup(string s, out double order, out string name) { WeakReference prevEventArgs = new WeakReference(null); internal bool? ShowContextMenu(object evArgs, FrameworkElement ctxMenuElem, Guid topLevelMenuGuid, Guid ownerMenuGuid, GuidObject creatorObject, IGuidObjectsProvider? provider, IContextMenuInitializer? initCtxMenu, bool openedFromKeyboard) { InitializeMenuItemObjects(); - Debug2.Assert(!(guidToGroups is null)); + Debug2.Assert(guidToGroups is not null); // There could be nested context menu handler calls, eg. first text editor followed by // the TabControl. We don't wan't the TabControl to disable the text editor's ctx menu. @@ -214,7 +214,7 @@ internal static bool ParseGroup(string s, out double order, out string name) { bool b = guidToGroups.TryGetValue(ownerMenuGuid, out var groups); if (!b) return false; - Debug2.Assert(!(groups is null)); + Debug2.Assert(groups is not null); var menu = new ContextMenu(); BindBackgroundBrush(menu, isCtxMenu: true); @@ -237,7 +237,7 @@ internal static bool ParseGroup(string s, out double order, out string name) { ctx.Dispose(); ctxMenuElem.ContextMenu = new ContextMenu(); }; - if (!(initCtxMenu is null)) + if (initCtxMenu is not null) initCtxMenu.Initialize(ctx, menu); ctxMenuElem.ContextMenu = menu; prevEventArgs.Target = evArgs; @@ -284,7 +284,7 @@ List CreateMenuItems(MenuItemContext ctx, List groups, } MenuItem Create(IMenuItem item, IMenuItemMetadata metadata, MenuItemContext ctx, IInputElement? commandTarget, MenuItem? menuItem, bool isCtxMenu) { - Debug2.Assert(!(guidToGroups is null)); + Debug2.Assert(guidToGroups is not null); if (menuItem is null) menuItem = new MenuItem(); menuItem.CommandTarget = commandTarget; @@ -303,7 +303,7 @@ MenuItem Create(IMenuItem item, IMenuItemMetadata metadata, MenuItemContext ctx, var cmdHolder = item as ICommandHolder; bool lastIsEnabledCallValue = false; - if (!(iconImgRef is null)) { + if (iconImgRef is not null) { if (cmdHolder is null) lastIsEnabledCallValue = item.IsEnabled(ctx); else { @@ -313,7 +313,7 @@ MenuItem Create(IMenuItem item, IMenuItemMetadata metadata, MenuItemContext ctx, Add16x16Image(menuItem, iconImgRef.Value, lastIsEnabledCallValue); } - if (!(metadata.Guid is null)) { + if (metadata.Guid is not null) { var itemGuid = Guid.Parse(metadata.Guid); if (guidToGroups.ContainsKey(itemGuid)) { menuItem.Items.Add(new MenuItem()); @@ -339,7 +339,7 @@ MenuItem Create(IMenuItem item, IMenuItemMetadata metadata, MenuItemContext ctx, iconImgRef = null; }; - menuItem.Command = !(cmdHolder is null) ? cmdHolder.Command : new RelayCommand(a => { + menuItem.Command = cmdHolder is not null ? cmdHolder.Command : new RelayCommand(a => { Debug.Assert(!ctx.IsDisposed); if (ctx?.IsDisposed == false) { item.Execute(ctx); @@ -349,7 +349,7 @@ MenuItem Create(IMenuItem item, IMenuItemMetadata metadata, MenuItemContext ctx, if (ctx?.IsDisposed != false) return false; bool b = item.IsEnabled(ctx); - if (lastIsEnabledCallValue != b && !(iconImgRef is null)) + if (lastIsEnabledCallValue != b && iconImgRef is not null) Add16x16Image(menuItem, iconImgRef.Value, lastIsEnabledCallValue = b); return b; }); @@ -366,7 +366,7 @@ static void Add16x16Image(MenuItem menuItem, ImageReference imageReference, bool void Reinitialize(MenuItem menuItem) { // To trigger this condition: Open the menu, then hold down LEFT or RIGHT for a few secs - if (menuItem.Items.Count != 1 || !(menuItem.Items[0] is MenuItem first) || !(first.Header is null)) { + if (menuItem.Items.Count != 1 || !(menuItem.Items[0] is MenuItem first) || first.Header is not null) { menuItem.Items.Clear(); menuItem.Items.Add(new MenuItem()); } @@ -374,12 +374,12 @@ void Reinitialize(MenuItem menuItem) { void InitializeSubMenu(MenuItem menuItem, MenuItemContext ctx, Guid ownerMenuGuid, IInputElement? commandTarget, bool isCtxMenu) { Reinitialize(menuItem); - Debug2.Assert(!(guidToGroups is null)); + Debug2.Assert(guidToGroups is not null); bool b = guidToGroups.TryGetValue(ownerMenuGuid, out var groups); Debug.Assert(b); if (b) { - Debug2.Assert(!(groups is null)); + Debug2.Assert(groups is not null); BindBackgroundBrush(menuItem, isCtxMenu); var firstMenuItem = menuItem.Items.Count == 1 ? menuItem.Items[0] as MenuItem : null; var allItems = CreateMenuItems(ctx, groups, commandTarget, firstMenuItem, isCtxMenu); @@ -392,13 +392,13 @@ void InitializeSubMenu(MenuItem menuItem, MenuItemContext ctx, Guid ownerMenuGui MenuItemContext? InitializeMainSubMenu(MenuItem menuItem, MenuMD md, IInputElement? commandTarget) { Reinitialize(menuItem); - Debug2.Assert(!(guidToGroups is null)); + Debug2.Assert(guidToGroups is not null); var guid = new Guid(md.Metadata.Guid!); bool b = guidToGroups.TryGetValue(guid, out var groups); Debug.Assert(b); if (b) { - Debug2.Assert(!(groups is null)); + Debug2.Assert(groups is not null); BindBackgroundBrush(menuItem, isCtxMenu: false); var ctx = new MenuItemContext(guid, true, new GuidObject(guid, null), null); var firstMenuItem = menuItem.Items.Count == 1 ? menuItem.Items[0] as MenuItem : null; @@ -415,8 +415,8 @@ void InitializeSubMenu(MenuItem menuItem, MenuItemContext ctx, Guid ownerMenuGui public Menu CreateMenu(Guid menuGuid, IInputElement? commandTarget) { InitializeMenuItemObjects(); - Debug2.Assert(!(guidToGroups is null)); - Debug2.Assert(!(guidToMenu is null)); + Debug2.Assert(guidToGroups is not null); + Debug2.Assert(guidToMenu is not null); var menu = new Menu(); @@ -440,7 +440,7 @@ public Menu CreateMenu(Guid menuGuid, IInputElement? commandTarget) { }; topMenuItem.SubmenuClosed += (s, e) => { if (e.Source == topMenuItem) { - Debug2.Assert(!(ctxTmp is null)); + Debug2.Assert(ctxTmp is not null); ctxTmp?.Dispose(); ctxTmp = null; diff --git a/dnSpy/dnSpy/Metadata/ModuleIdProvider.cs b/dnSpy/dnSpy/Metadata/ModuleIdProvider.cs index a2fe6cd79e..1741ffaa98 100644 --- a/dnSpy/dnSpy/Metadata/ModuleIdProvider.cs +++ b/dnSpy/dnSpy/Metadata/ModuleIdProvider.cs @@ -56,7 +56,7 @@ StrongBox CreateCore(ModuleDef module) { var list = new List(moduleIdFactoryProviders.Length); foreach (var provider in moduleIdFactoryProviders) { var factory = provider.Value.Create(); - if (!(factory is null)) + if (factory is not null) list.Add(factory); } factories = list.ToArray(); @@ -64,7 +64,7 @@ StrongBox CreateCore(ModuleDef module) { foreach (var factory in factories) { var id = factory.Create(module); - if (!(id is null)) + if (id is not null) return new StrongBox(id.Value); } diff --git a/dnSpy/dnSpy/Output/NotPresentOutputWriter.cs b/dnSpy/dnSpy/Output/NotPresentOutputWriter.cs index a468e76f3c..bddbaf68bd 100644 --- a/dnSpy/dnSpy/Output/NotPresentOutputWriter.cs +++ b/dnSpy/dnSpy/Output/NotPresentOutputWriter.cs @@ -31,7 +31,7 @@ sealed class NotPresentOutputWriter : IOutputTextPane { IOutputTextPane TextPane { get { - if (!(textPane is null)) + if (textPane is not null) return textPane; return (textPane = outputService.Find(guid)) ?? NullOutputTextPane.Instance; } diff --git a/dnSpy/dnSpy/Output/OutputContent.cs b/dnSpy/dnSpy/Output/OutputContent.cs index 538425e88d..439bd29833 100644 --- a/dnSpy/dnSpy/Output/OutputContent.cs +++ b/dnSpy/dnSpy/Output/OutputContent.cs @@ -110,7 +110,7 @@ void OutputControl_PreviewKeyDown(object? sender, KeyEventArgs e) { void SelectLog(int tmpIndex) { var vm = OutputService.SelectLog(tmpIndex); - Debug2.Assert(!(vm is null)); + Debug2.Assert(vm is not null); if (vm is null) return; vm.FocusedElement?.Focus(); diff --git a/dnSpy/dnSpy/Output/OutputService.cs b/dnSpy/dnSpy/Output/OutputService.cs index f65aa2fd1d..c7de049253 100644 --- a/dnSpy/dnSpy/Output/OutputService.cs +++ b/dnSpy/dnSpy/Output/OutputService.cs @@ -94,7 +94,7 @@ public bool ShowTimestamps { public object? TextEditorUIObject => SelectedOutputBufferVM?.TextEditorUIObject; public IInputElement? FocusedElement => SelectedOutputBufferVM?.FocusedElement; - public bool HasOutputWindows => !(SelectedOutputBufferVM is null); + public bool HasOutputWindows => SelectedOutputBufferVM is not null; public double ZoomLevel => SelectedOutputBufferVM?.ZoomLevel ?? 100; public OutputBufferVM? SelectedOutputBufferVM { @@ -153,9 +153,9 @@ void OutputBuffers_CollectionChanged(object? sender, NotifyCollectionChangedEven if (SelectedOutputBufferVM is null) SelectedOutputBufferVM = OutputBuffers.FirstOrDefault(); - if (!(e.NewItems is null)) { + if (e.NewItems is not null) { foreach (OutputBufferVM? vm in e.NewItems) { - Debug2.Assert(!(vm is null)); + Debug2.Assert(vm is not null); if (vm.Guid == prevSelectedGuid && prevSelectedGuid != Guid.Empty) { SelectedOutputBufferVM = vm; prevSelectedGuid = Guid.Empty; @@ -177,7 +177,7 @@ IOutputTextPane Create(Guid guid, string name, object? contentTypeObj) { var vm = OutputBuffers.FirstOrDefault(a => a.Guid == guid); Debug2.Assert(vm is null || vm.Name == name); - if (!(vm is null)) + if (vm is not null) return vm; var logEditorOptions = new LogEditorOptions { @@ -222,15 +222,15 @@ int GetSortedInsertIndex(OutputBufferVM vm) { public void Select(Guid guid) { var vm = OutputBuffers.FirstOrDefault(a => a.Guid == guid); - Debug2.Assert(!(vm is null)); - if (!(vm is null)) + Debug2.Assert(vm is not null); + if (vm is not null) SelectedOutputBufferVM = vm; } public bool CanCopy => SelectedOutputBufferVM?.CanCopy == true; public void Copy() => SelectedOutputBufferVM?.Copy(); - public bool CanClearAll => !(SelectedOutputBufferVM is null); + public bool CanClearAll => SelectedOutputBufferVM is not null; public void ClearAll() { if (!CanClearAll) @@ -238,12 +238,12 @@ public void ClearAll() { SelectedOutputBufferVM?.Clear(); } - public bool CanSaveText => !(SelectedOutputBufferVM is null); + public bool CanSaveText => SelectedOutputBufferVM is not null; public void SaveText() { if (!CanSaveText) return; - Debug2.Assert(!(SelectedOutputBufferVM is null)); + Debug2.Assert(SelectedOutputBufferVM is not null); var vm = SelectedOutputBufferVM; var filename = pickSaveFilename.GetFilename(GetFilename(vm), "txt", TEXTFILES_FILTER); if (filename is null) diff --git a/dnSpy/dnSpy/Scripting/ServiceLocator.cs b/dnSpy/dnSpy/Scripting/ServiceLocator.cs index 8ffbb21e1c..1ac3696a90 100644 --- a/dnSpy/dnSpy/Scripting/ServiceLocator.cs +++ b/dnSpy/dnSpy/Scripting/ServiceLocator.cs @@ -32,16 +32,16 @@ sealed class ServiceLocator : IServiceLocator { Dispatcher? dispatcher; public T Resolve() where T : class { - Debug2.Assert(!(exportProvider is null)); - Debug2.Assert(!(dispatcher is null)); + Debug2.Assert(exportProvider is not null); + Debug2.Assert(dispatcher is not null); if (exportProvider is null) throw new InvalidOperationException(); return dispatcher.UI(() => exportProvider.GetExportedValue()); } public T? TryResolve() where T : class { - Debug2.Assert(!(exportProvider is null)); - Debug2.Assert(!(dispatcher is null)); + Debug2.Assert(exportProvider is not null); + Debug2.Assert(dispatcher is not null); if (exportProvider is null) throw new InvalidOperationException(); return dispatcher.UI(() => { @@ -55,7 +55,7 @@ public T Resolve() where T : class { public void SetExportProvider(Dispatcher dispatcher, ExportProvider exportProvider) { this.dispatcher = dispatcher; - if (!(this.exportProvider is null)) + if (this.exportProvider is not null) throw new InvalidOperationException(); this.exportProvider = exportProvider ?? throw new ArgumentNullException(nameof(exportProvider)); } diff --git a/dnSpy/dnSpy/Search/AppCommandLineArgsHandler.cs b/dnSpy/dnSpy/Search/AppCommandLineArgsHandler.cs index 22079745be..2a0525de61 100644 --- a/dnSpy/dnSpy/Search/AppCommandLineArgsHandler.cs +++ b/dnSpy/dnSpy/Search/AppCommandLineArgsHandler.cs @@ -43,17 +43,17 @@ public void OnNewArgs(IAppCommandLineArgs args) { var loc = GetSearchLocation(args.SearchIn); var typ = GetSearchType(args.SearchFor); - if (!(loc is null)) { + if (loc is not null) { show = true; searchService.Value.SearchLocation = loc.Value; } - if (!(typ is null)) { + if (typ is not null) { show = true; searchService.Value.SearchType = typ.Value; } - if (!(args.SearchText is null)) { + if (args.SearchText is not null) { show = true; searchService.Value.SearchText = args.SearchText; } diff --git a/dnSpy/dnSpy/Search/Commands.cs b/dnSpy/dnSpy/Search/Commands.cs index bbc5a63ece..28e1b00916 100644 --- a/dnSpy/dnSpy/Search/Commands.cs +++ b/dnSpy/dnSpy/Search/Commands.cs @@ -89,7 +89,7 @@ public override void Execute(IMenuItemContext context) { searchService.Value.FollowResult(res, newTab); } - public override bool IsVisible(IMenuItemContext context) => !(GetReference(context) is null); + public override bool IsVisible(IMenuItemContext context) => GetReference(context) is not null; ISearchResult? GetReference(IMenuItemContext context) { if (context.CreatorObject.Guid != new Guid(MenuConstants.GUIDOBJ_SEARCH_GUID)) diff --git a/dnSpy/dnSpy/Search/DocumentSearcher.cs b/dnSpy/dnSpy/Search/DocumentSearcher.cs index c001ac09af..ed0bbd099f 100644 --- a/dnSpy/dnSpy/Search/DocumentSearcher.cs +++ b/dnSpy/dnSpy/Search/DocumentSearcher.cs @@ -154,7 +154,7 @@ void SearchCompleted() { disposed = true; cancellationTokenSource.Cancel(); cancellationTokenSource.Dispose(); - Debug2.Assert(!(OnSearchCompleted is null)); + Debug2.Assert(OnSearchCompleted is not null); OnSearchCompleted?.Invoke(this, EventArgs.Empty); } bool disposed; @@ -195,7 +195,7 @@ void EmptySearchResultsQueue() { if (cancellationTokenSource.IsCancellationRequested) return; - Debug2.Assert(!(OnNewSearchResults is null)); + Debug2.Assert(OnNewSearchResults is not null); OnNewSearchResults?.Invoke(this, new SearchResultEventArgs(results)); } } diff --git a/dnSpy/dnSpy/Search/FilterSearcher.cs b/dnSpy/dnSpy/Search/FilterSearcher.cs index c688e47891..6e370bc7aa 100644 --- a/dnSpy/dnSpy/Search/FilterSearcher.cs +++ b/dnSpy/dnSpy/Search/FilterSearcher.cs @@ -86,7 +86,7 @@ void CheckCustomAttributes(IDsDocument file, IHasCustomAttribute hca, object? pa bool CheckCA(IDsDocument file, IHasCustomAttribute hca, object? parent, CAArgument o) { var value = o.Value; var u = value as UTF8String; - if (!(u is null)) + if (u is not null) value = u.String; if (!IsMatch(null, value)) return false; @@ -131,7 +131,7 @@ void SearchAssemblyInternal(AssemblyDocumentNode asmNode) { if (asmNode is null) return; var asm = asmNode.Document.AssemblyDef; - Debug2.Assert(!(asm is null)); + Debug2.Assert(asm is not null); if (asm is null) return; var res = options.Filter.GetResult(asm); @@ -186,7 +186,7 @@ void SearchModule(IDsDocument module) { NameObject = mod, ObjectImageReference = options.DotNetImageService.GetImageReference(mod), LocationObject = mod.Assembly, - LocationImageReference = !(mod.Assembly is null) ? options.DotNetImageService.GetImageReference(mod.Assembly.ManifestModule) : new ImageReference(), + LocationImageReference = mod.Assembly is not null ? options.DotNetImageService.GetImageReference(mod.Assembly.ManifestModule) : new ImageReference(), Document = module, }); } @@ -260,7 +260,7 @@ void SearchResources(IDsDocument module) { return; modNode.TreeNode.EnsureChildrenLoaded(); var resFolder = modNode.TreeNode.Children.FirstOrDefault(a => a.Data is ResourcesFolderNode); - if (!(resFolder is null)) { + if (resFolder is not null) { resFolder.EnsureChildrenLoaded(); resNodes.AddRange(resFolder.DataChildren.OfType()); } @@ -625,7 +625,7 @@ void SearchBody(IDsDocument ownerModule, TypeDef type, MethodDef method) { case Code.Ldstr: operand = instr.Operand; break; default: operand = null; break; } - if (!(operand is null) && IsMatch(null, operand)) { + if (operand is not null && IsMatch(null, operand)) { options.OnMatch(new SearchResult { Context = options.Context, Object = method, diff --git a/dnSpy/dnSpy/Search/FrameworkFileUtils.cs b/dnSpy/dnSpy/Search/FrameworkFileUtils.cs index 7385385bd3..9dc6b2b9a6 100644 --- a/dnSpy/dnSpy/Search/FrameworkFileUtils.cs +++ b/dnSpy/dnSpy/Search/FrameworkFileUtils.cs @@ -460,7 +460,7 @@ public static bool IsFrameworkAssembly(string filename, string? assemblySimpleNa if (Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(filename))) is string baseDir && Directory.Exists(Path.Combine(baseDir, "Microsoft.NETCore.App"))) return true; - if (!(assemblySimpleName is null)) { + if (assemblySimpleName is not null) { if (frameworkAssemblyNames.Contains(assemblySimpleName)) return true; foreach (var prefix in frameworkAssemblyNamePrefixes) { diff --git a/dnSpy/dnSpy/Search/SearchControlVM.cs b/dnSpy/dnSpy/Search/SearchControlVM.cs index 278161c7f6..60b315cec5 100644 --- a/dnSpy/dnSpy/Search/SearchControlVM.cs +++ b/dnSpy/dnSpy/Search/SearchControlVM.cs @@ -117,7 +117,7 @@ public IDecompiler Decompiler { set { if (decompiler != value) { decompiler = value; - if (!(fileSearcher is null)) + if (fileSearcher is not null) fileSearcher.Decompiler = decompiler; } } @@ -229,7 +229,7 @@ bool CanSearchFile(DsDocumentNode node) => IEnumerable GetAllFilesToSearch() => documentTreeView.TreeView.Root.DataChildren.OfType().Where(a => CanSearchFile(a)); IEnumerable GetSelectedFilesToSearch() => - documentTreeView.TreeView.TopLevelSelection.Select(a => a.GetDocumentNode()).Where(a => !(a is null) && CanSearchFile(a)).Distinct()!; + documentTreeView.TreeView.TopLevelSelection.Select(a => a.GetDocumentNode()).Where(a => a is not null && CanSearchFile(a)).Distinct()!; IEnumerable GetAllFilesInSameDirToSearch() { var dirsEnum = GetSelectedFilesToSearch().Where(a => File.Exists(a.Document.Filename)).Select(a => Path.GetDirectoryName(a.Document.Filename)); @@ -238,9 +238,9 @@ IEnumerable GetAllFilesInSameDirToSearch() { } IEnumerable GetSelectedTypeToSearch() { - foreach (var node in documentTreeView.TreeView.TopLevelSelection.Select(a => a.GetAncestorOrSelf()).Where(a => !(a is null)).Distinct()) { + foreach (var node in documentTreeView.TreeView.TopLevelSelection.Select(a => a.GetAncestorOrSelf()).Where(a => a is not null).Distinct()) { var fileNode = node.GetDocumentNode(); - Debug2.Assert(!(fileNode is null)); + Debug2.Assert(fileNode is not null); if (fileNode is null) continue; yield return new SearchTypeInfo(fileNode.Document, node!.TypeDef); @@ -250,7 +250,7 @@ IEnumerable GetSelectedTypeToSearch() { void FileSearcher_OnSearchCompleted(object? sender, EventArgs e) { if (sender is null || sender != fileSearcher || searchCompleted) return; - Debug2.Assert(!(fileSearcher is null)); + Debug2.Assert(fileSearcher is not null); searchCompleted = true; SearchResults.Remove(fileSearcher.SearchingResult!); TooManyResults = fileSearcher.TooManyResults; @@ -292,7 +292,7 @@ public void Clear() { void CancelSearch() { TooManyResults = false; delayedSearch.Cancel(); - if (!(fileSearcher is null)) { + if (fileSearcher is not null) { fileSearcher.Cancel(); fileSearcher = null; } @@ -310,7 +310,7 @@ void SearchSettings_PropertyChanged(object? sender, PropertyChangedEventArgs e) Restart(); break; case nameof(SearchSettings.SyntaxHighlight): - if (!(fileSearcher is null)) + if (fileSearcher is not null) fileSearcher.SyntaxHighlight = SearchSettings.SyntaxHighlight; break; case nameof(SearchSettings.MatchWholeWords): diff --git a/dnSpy/dnSpy/Search/SearchResult.cs b/dnSpy/dnSpy/Search/SearchResult.cs index d8105e2273..5ea9b914eb 100644 --- a/dnSpy/dnSpy/Search/SearchResult.cs +++ b/dnSpy/dnSpy/Search/SearchResult.cs @@ -78,7 +78,7 @@ public string? ToolTip { return module.Location; if (!string.IsNullOrWhiteSpace(module.Name)) return module.Name; - if (!(module.Assembly is null) && !string.IsNullOrWhiteSpace(module.Assembly.Name)) + if (module.Assembly is not null && !string.IsNullOrWhiteSpace(module.Assembly.Name)) return module.Assembly.Name; return null; } @@ -118,7 +118,7 @@ void CreateUI(ITextColorWriter output, object? o, bool includeNamespace) { } if (o is TypeDef td) { - Debug2.Assert(!(Context.Decompiler is null)); + Debug2.Assert(Context.Decompiler is not null); Context.Decompiler.WriteType(output, td, includeNamespace); return; } diff --git a/dnSpy/dnSpy/Search/SearchService.cs b/dnSpy/dnSpy/Search/SearchService.cs index dbe5033013..7048a136fe 100644 --- a/dnSpy/dnSpy/Search/SearchService.cs +++ b/dnSpy/dnSpy/Search/SearchService.cs @@ -100,7 +100,7 @@ public IEnumerable GetGuidObjects(GuidObjectsProviderArgs args) { if (listBox.SelectedItem is ISearchResult searchResult) { yield return new GuidObject(MenuConstants.GUIDOBJ_SEARCHRESULT_GUID, searchResult); var @ref = searchResult.Reference; - if (!(@ref is null)) + if (@ref is not null) yield return new GuidObject(MenuConstants.GUIDOBJ_CODE_REFERENCE_GUID, new TextReference(@ref)); } } diff --git a/dnSpy/dnSpy/Settings/AppearanceCategory/TextAppearanceCategory.cs b/dnSpy/dnSpy/Settings/AppearanceCategory/TextAppearanceCategory.cs index 9fcc1c25da..e77a948d65 100644 --- a/dnSpy/dnSpy/Settings/AppearanceCategory/TextAppearanceCategory.cs +++ b/dnSpy/dnSpy/Settings/AppearanceCategory/TextAppearanceCategory.cs @@ -61,7 +61,7 @@ void UpdateActive() { var newActive = ThemeFontSettings.Active; if (activeFontSettings == newActive) return; - if (!(activeFontSettings is null)) + if (activeFontSettings is not null) activeFontSettings.PropertyChanged -= ActiveFontSettings_PropertyChanged; activeFontSettings = newActive; activeFontSettings.PropertyChanged += ActiveFontSettings_PropertyChanged; @@ -89,7 +89,7 @@ public ResourceDictionary CreateResourceDictionary(ITheme theme) { } ResourceDictionary CreateResourceDictionaryCore(ITheme theme) { - Debug2.Assert(!(activeFontSettings is null)); + Debug2.Assert(activeFontSettings is not null); var res = new ResourceDictionary(); var tc = theme.GetColor(def.ColorType); diff --git a/dnSpy/dnSpy/Settings/Dialog/AppSettingsPageVM.cs b/dnSpy/dnSpy/Settings/Dialog/AppSettingsPageVM.cs index 884ec1966d..43c2be8f84 100644 --- a/dnSpy/dnSpy/Settings/Dialog/AppSettingsPageVM.cs +++ b/dnSpy/dnSpy/Settings/Dialog/AppSettingsPageVM.cs @@ -77,7 +77,7 @@ public AppSettingsPageVM(AppSettingsPage page, PageContext context) { PageAndUIObject? GetOrCreatePageAndUIObject() { var uiObj = context.PageUIObjectLoader.GetUIObject(Page); - if (!(uiObj is null)) + if (uiObj is not null) return createdPageAndUIObject ??= new PageAndUIObject(this, CreateUIObject(uiObj)); // Try to pick a visible child @@ -144,7 +144,7 @@ static IEnumerable GetStrings(DependencyObject obj) { if (obj is null) yield break; var objString = TryGetString(obj); - if (!(objString is null)) + if (objString is not null) yield return objString; foreach (var childObj in LogicalTreeHelper.GetChildren(obj)) { var child = childObj as DependencyObject; @@ -159,17 +159,17 @@ static IEnumerable GetStrings(DependencyObject obj) { string? s; s = (obj as GroupBox)?.Header as string; - if (!(s is null)) + if (s is not null) return s; // Label, CheckBox, Button, TextControl and others s = (obj as ContentControl)?.Content as string; - if (!(s is null)) + if (s is not null) return s; Debug.Assert(!(obj is TextBlock), $"Use {nameof(TextControl)} instead so the text can be highlighted"); s = (obj as TextBlock)?.Text; - if (!(s is null)) + if (s is not null) return s; return null; diff --git a/dnSpy/dnSpy/Settings/Dialog/AppSettingsService.cs b/dnSpy/dnSpy/Settings/Dialog/AppSettingsService.cs index 8153391b67..37a68af503 100644 --- a/dnSpy/dnSpy/Settings/Dialog/AppSettingsService.cs +++ b/dnSpy/dnSpy/Settings/Dialog/AppSettingsService.cs @@ -69,8 +69,8 @@ sealed class AppSettingsService : IAppSettingsService { public void Show(Guid guid, Window? owner) => Show2(guid, owner); void Show2(Guid? guid, Window? owner) { - if (!(showAppSettings is null)) { - if (!(guid is null)) + if (showAppSettings is not null) { + if (guid is not null) showAppSettings.Select(guid.Value); return; } diff --git a/dnSpy/dnSpy/Settings/Dialog/SettingsAppCommandLineArgsHandler.cs b/dnSpy/dnSpy/Settings/Dialog/SettingsAppCommandLineArgsHandler.cs index 7c7479595b..50fb3a2181 100644 --- a/dnSpy/dnSpy/Settings/Dialog/SettingsAppCommandLineArgsHandler.cs +++ b/dnSpy/dnSpy/Settings/Dialog/SettingsAppCommandLineArgsHandler.cs @@ -40,7 +40,7 @@ public void OnNewArgs(IAppCommandLineArgs args) { Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { var guidString = args.GetArgumentValue(ARG_NAME); var guid = TryParse(guidString); - if (!(guid is null)) + if (guid is not null) appSettingsService.Value.Show(guid.Value); else appSettingsService.Value.Show(); diff --git a/dnSpy/dnSpy/Settings/Dialog/ShowAppSettingsDialog.cs b/dnSpy/dnSpy/Settings/Dialog/ShowAppSettingsDialog.cs index 5a5486c048..251ea87921 100644 --- a/dnSpy/dnSpy/Settings/Dialog/ShowAppSettingsDialog.cs +++ b/dnSpy/dnSpy/Settings/Dialog/ShowAppSettingsDialog.cs @@ -89,7 +89,7 @@ public ShowAppSettingsDialog(IClassificationFormatMap classificationFormatMap, I } object? IPageUIObjectLoader.GetUIObject(AppSettingsPage page) { - Debug2.Assert(!(appSettingsDlg is null)); + Debug2.Assert(appSettingsDlg is not null); var oldCursor = appSettingsDlg.Cursor; try { appSettingsDlg.Cursor = Cursors.Wait; @@ -101,7 +101,7 @@ public ShowAppSettingsDialog(IClassificationFormatMap classificationFormatMap, I } public void Select(Guid value) { - Debug2.Assert(!(allPages is null)); + Debug2.Assert(allPages is not null); var page = allPages.FirstOrDefault(a => a.Page.Guid == value); if (page?.Parent is null) return; @@ -128,13 +128,13 @@ public void Show(Guid? guid, Window ownerWindow) { appSettingsDlg.Owner = ownerWindow ?? throw new ArgumentNullException(nameof(ownerWindow)); AppSettingsPageVM? selectedItem = null; - if (!(guid is null)) + if (guid is not null) selectedItem = allPages.FirstOrDefault(a => a.Page.Guid == guid.Value); if (selectedItem is null) selectedItem = rootVM.Children.FirstOrDefault(); - if (guid is null && !(selectedItem is null)) + if (guid is null && selectedItem is not null) selectedItem = selectedItem.VisiblePage; - if (!(selectedItem is null)) + if (selectedItem is not null) pageContext.TreeView.SelectItems(new[] { selectedItem }); bool saveSettings = appSettingsDlg.ShowDialog() == true; @@ -164,7 +164,7 @@ public void Show(Guid? guid, Window ownerWindow) { } void InitializeKeyboardBindings() { - Debug2.Assert(!(appSettingsDlg is null)); + Debug2.Assert(appSettingsDlg is not null); var cmd = new RelayCommand(a => { appSettingsDlg.searchTextBox.Focus(); appSettingsDlg.searchTextBox.SelectAll(); @@ -174,9 +174,9 @@ void InitializeKeyboardBindings() { } void FilterTreeView(string searchText) { - Debug2.Assert(!(allPages is null)); - Debug2.Assert(!(rootVM is null)); - Debug2.Assert(!(appSettingsDlg is null)); + Debug2.Assert(allPages is not null); + Debug2.Assert(rootVM is not null); + Debug2.Assert(appSettingsDlg is not null); if (string.IsNullOrWhiteSpace(searchText)) searchText = string.Empty; if (searchText == string.Empty) { @@ -201,7 +201,7 @@ void FilterTreeView(string searchText) { RefreshAllNodes(); if (pageContext.TreeView.SelectedItem is null) { var first = rootVM.Children.FirstOrDefault(a => !a.TreeNode.IsHidden); - if (!(first is null)) { + if (first is not null) { pageContext.TreeView.SelectItems(new[] { first }); // The treeview steals the focus. It uses prio Loaded. appSettingsDlg.searchTextBox.Focus(); @@ -214,8 +214,8 @@ void FilterTreeView(string searchText) { bool isFiltering; void RefreshAllNodes() { - Debug2.Assert(!(allPages is null)); - Debug2.Assert(!(appSettingsDlg is null)); + Debug2.Assert(allPages is not null); + Debug2.Assert(appSettingsDlg is not null); foreach (var page in allPages) page.ClearUICache(); foreach (var page in allPages) @@ -236,12 +236,12 @@ void FilterChildren(AppSettingsPageVM page, SearchMatcher matcher) { } bool IsVisible(AppSettingsPageVM page, SearchMatcher matcher) { - Debug2.Assert(!(appSettingsDlg is null)); + Debug2.Assert(appSettingsDlg is not null); pageStringsList.Clear(); pageTitlesList.Clear(); var p = page; // Don't include the root - while (!(p.Parent is null)) { + while (p.Parent is not null) { pageTitlesList.Add(p.Page.Title); p = p.Parent; } @@ -257,7 +257,7 @@ bool IsVisible(AppSettingsPageVM page, SearchMatcher matcher) { object IContentConverter.Convert(object content, object ownerControl) { var result = TryConvert(content, ownerControl); - if (!(result is null)) + if (result is not null) return result; if (ownerControl is TextControl textControl) { @@ -406,7 +406,7 @@ AppSettingsPageVM[] CreateSettingsPages() { foreach (var lz in appSettingsPageProviders) { foreach (var page in lz.Value.Create()) { - Debug2.Assert(!(page is null)); + Debug2.Assert(page is not null); if (page is null) continue; var vm = new AppSettingsPageVM(page, pageContext); @@ -445,12 +445,12 @@ public override void OnApply() { } static AppSettingsPageVM? TryCreate(object obj, IAppSettingsPageContainerMetadata md, PageContext context) { Guid? guid = md.Guid is null ? null : TryParseGuid(md.Guid); - Debug2.Assert(!(guid is null), "Invalid GUID"); + Debug2.Assert(guid is not null, "Invalid GUID"); if (guid is null) return null; Guid? parentGuid = md.ParentGuid is null ? rootGuid : TryParseGuid(md.ParentGuid); - Debug2.Assert(!(parentGuid is null), "Invalid Parent GUID"); + Debug2.Assert(parentGuid is not null, "Invalid Parent GUID"); if (parentGuid is null) return null; diff --git a/dnSpy/dnSpy/Settings/Fonts/ThemeFontSettingsSerializer.cs b/dnSpy/dnSpy/Settings/Fonts/ThemeFontSettingsSerializer.cs index 2d6c8e2e3e..bfe63093b9 100644 --- a/dnSpy/dnSpy/Settings/Fonts/ThemeFontSettingsSerializer.cs +++ b/dnSpy/dnSpy/Settings/Fonts/ThemeFontSettingsSerializer.cs @@ -70,7 +70,7 @@ public override ThemeFontSettingsData[] Deserialize() { var name = tfsSection.Attribute(ThemeFontSettingsAttrName); if (name is null) continue; - if (!(TryGetThemeFontSettingsSection(name) is null)) { + if (TryGetThemeFontSettingsSection(name) is not null) { rootSection.RemoveSection(tfsSection); continue; } @@ -83,7 +83,7 @@ public override void Remove(string name) { if (name is null) throw new ArgumentNullException(nameof(name)); var section = TryGetThemeFontSettingsSection(name); - if (!(section is null)) + if (section is not null) rootSection.RemoveSection(section); } @@ -93,7 +93,7 @@ ThemeFontSettingsData DeserializeThemeFontSettingsData(ISettingsSection tfsSecti var themeGuid = fontSection.Attribute(FontSettingsAttrThemeGuid); var fontFamily = fontSection.Attribute(FontSettingsAttrFontFamily); var fontSize = fontSection.Attribute(FontSettingsAttrFontSize); - if (themeGuid is null || string.IsNullOrWhiteSpace(fontFamily) || fontSize is null || !(TryGetThemeFontSettingsSection(name, themeGuid.Value) is null)) { + if (themeGuid is null || string.IsNullOrWhiteSpace(fontFamily) || fontSize is null || TryGetThemeFontSettingsSection(name, themeGuid.Value) is not null) { tfsSection.RemoveSection(fontSection); continue; } @@ -124,7 +124,7 @@ public override void Serialize(FontSettings fontSettings) { ISettingsSection GetThemeFontSettingsSection(string name) { var section = TryGetThemeFontSettingsSection(name); - if (!(section is null)) + if (section is not null) return section; section = rootSection.CreateSection(ThemeFontSettingsSection); section.Attribute(ThemeFontSettingsAttrName, name); @@ -135,7 +135,7 @@ ISettingsSection GetThemeFontSettingsSection(string name) { ISettingsSection GetThemeFontSettingsSection(string name, Guid themeGuid) { var tfsSection = GetThemeFontSettingsSection(name); var section = TryGetThemeFontSettingsSection(name, themeGuid); - if (!(section is null)) + if (section is not null) return section; section = tfsSection.CreateSection(FontSettingsSection); section.Attribute(FontSettingsAttrThemeGuid, themeGuid); diff --git a/dnSpy/dnSpy/Settings/SectionAttributes.cs b/dnSpy/dnSpy/Settings/SectionAttributes.cs index 82715ca07f..0b53136c6f 100644 --- a/dnSpy/dnSpy/Settings/SectionAttributes.cs +++ b/dnSpy/dnSpy/Settings/SectionAttributes.cs @@ -41,7 +41,7 @@ public SectionAttributes() { } public T Attribute(string name) { - Debug2.Assert(!(name is null)); + Debug2.Assert(name is not null); if (name is null) throw new ArgumentNullException(nameof(name)); @@ -63,7 +63,7 @@ public T Attribute(string name) { } public void Attribute(string name, T value) { - Debug2.Assert(!(name is null)); + Debug2.Assert(name is not null); if (name is null) throw new ArgumentNullException(nameof(name)); @@ -74,7 +74,7 @@ public void Attribute(string name, T value) { } public void RemoveAttribute(string name) { - Debug2.Assert(!(name is null)); + Debug2.Assert(name is not null); if (name is null) throw new ArgumentNullException(nameof(name)); diff --git a/dnSpy/dnSpy/Settings/SettingsSectionProvider.cs b/dnSpy/dnSpy/Settings/SettingsSectionProvider.cs index 449d8aa9d7..992babf716 100644 --- a/dnSpy/dnSpy/Settings/SettingsSectionProvider.cs +++ b/dnSpy/dnSpy/Settings/SettingsSectionProvider.cs @@ -41,7 +41,7 @@ public ISettingsSection[] Sections { } public ISettingsSection CreateSection(string name) { - Debug2.Assert(!(name is null)); + Debug2.Assert(name is not null); if (name is null) throw new ArgumentNullException(nameof(name)); @@ -52,14 +52,14 @@ public ISettingsSection CreateSection(string name) { } public ISettingsSection GetOrCreateSection(string name) { - Debug2.Assert(!(name is null)); + Debug2.Assert(name is not null); if (name is null) throw new ArgumentNullException(nameof(name)); ISettingsSection? section; lock (lockObj) { section = sections.FirstOrDefault(a => StringComparer.Ordinal.Equals(name, a.Name)); - if (!(section is null)) + if (section is not null) return section; sections.Add(section = new SettingsSection(name)); } @@ -67,7 +67,7 @@ public ISettingsSection GetOrCreateSection(string name) { } public void RemoveSection(string name) { - Debug2.Assert(!(name is null)); + Debug2.Assert(name is not null); if (name is null) throw new ArgumentNullException(nameof(name)); @@ -80,7 +80,7 @@ public void RemoveSection(string name) { } public void RemoveSection(ISettingsSection section) { - Debug2.Assert(!(section is null)); + Debug2.Assert(section is not null); if (section is null) throw new ArgumentNullException(nameof(section)); diff --git a/dnSpy/dnSpy/Settings/SettingsService.cs b/dnSpy/dnSpy/Settings/SettingsService.cs index d7c6055a73..ffdc91b0c7 100644 --- a/dnSpy/dnSpy/Settings/SettingsService.cs +++ b/dnSpy/dnSpy/Settings/SettingsService.cs @@ -67,7 +67,7 @@ public void RemoveSection(Guid guid) { } public void RemoveSection(ISettingsSection section) { - Debug2.Assert(!(section is null)); + Debug2.Assert(section is not null); if (section is null) throw new ArgumentNullException(nameof(section)); diff --git a/dnSpy/dnSpy/Settings/XmlSettingsWriter.cs b/dnSpy/dnSpy/Settings/XmlSettingsWriter.cs index d68fd66ba7..d2d7dc67bd 100644 --- a/dnSpy/dnSpy/Settings/XmlSettingsWriter.cs +++ b/dnSpy/dnSpy/Settings/XmlSettingsWriter.cs @@ -58,7 +58,7 @@ XElement Write(ISettingsSection section, int recursionCounter) { xmlSect.SetAttributeValue(XmlSettingsConstants.SECTION_ATTRIBUTE_NAME, XmlUtils.EscapeAttributeValue(section.Name)); foreach (var attr in section.Attributes.OrderBy(a => a.key.ToUpperInvariant())) { var n = XmlUtils.FilterAttributeName(attr.key); - Debug2.Assert(!(n is null), "Invalid character(s) in section attribute name. Only valid XML attribute names can be used."); + Debug2.Assert(n is not null, "Invalid character(s) in section attribute name. Only valid XML attribute names can be used."); if (n is null) continue; bool b = n == XmlSettingsConstants.SECTION_ATTRIBUTE_NAME; diff --git a/dnSpy/dnSpy/Tabs/TabElementZoomer.cs b/dnSpy/dnSpy/Tabs/TabElementZoomer.cs index 0176bb1ff7..a7c3f5e9cc 100644 --- a/dnSpy/dnSpy/Tabs/TabElementZoomer.cs +++ b/dnSpy/dnSpy/Tabs/TabElementZoomer.cs @@ -58,7 +58,7 @@ void ResetBindings() { public void InstallZoom(IUIObjectProvider provider, FrameworkElement? elem) { var zoomable = (provider as IZoomableProvider)?.Zoomable ?? provider as IZoomable; - if (!(zoomable is null)) + if (zoomable is not null) InstallScaleCore(provider, zoomable); else InstallScaleCore(provider, elem); @@ -89,7 +89,7 @@ void UninstallScale() { uiObjectProvider = null; if (zoomElement is null) return; - if (!(metroWindow is null)) + if (metroWindow is not null) metroWindow.WindowDpiChanged -= MetroWindow_WindowDpiChanged; zoomElement.Loaded -= ZoomElement_Loaded; zoomElement.PreviewMouseWheel -= ZoomElement_PreviewMouseWheel; @@ -142,29 +142,29 @@ void SetZoomValue(double value, bool force) { currentZoomValue = newZoomValue; - if (!(zoomElement is null)) + if (zoomElement is not null) AddScaleTransform(); } void AddScaleTransform() { - Debug2.Assert(!(zoomElement is null)); + Debug2.Assert(zoomElement is not null); var mwin = GetWindow(); - if (!(mwin is null)) { + if (mwin is not null) { mwin.SetScaleTransform(zoomElement, currentZoomValue); DsImage.SetZoom(zoomElement, currentZoomValue); } } MetroWindow? GetWindow() { - Debug2.Assert(!(zoomElement is null)); - if (!(metroWindow is null)) + Debug2.Assert(zoomElement is not null); + if (metroWindow is not null) return metroWindow; if (zoomElement is null) return null; var win = Window.GetWindow(zoomElement); metroWindow = win as MetroWindow; - if (!(metroWindow is null)) { + if (metroWindow is not null) { metroWindow.WindowDpiChanged += MetroWindow_WindowDpiChanged; return metroWindow; } @@ -178,14 +178,14 @@ void AddScaleTransform() { } void MetroWindow_WindowDpiChanged(object? sender, EventArgs e) { - Debug2.Assert(!(sender is null) && sender == metroWindow); + Debug2.Assert(sender is not null && sender == metroWindow); ((MetroWindow)sender).SetScaleTransform(zoomElement, currentZoomValue); } void ZoomElement_Loaded(object? sender, RoutedEventArgs e) { var fe = (FrameworkElement)sender!; fe.Loaded -= ZoomElement_Loaded; - if (!(zoomElement is null)) + if (zoomElement is not null) AddScaleTransform(); } diff --git a/dnSpy/dnSpy/Tabs/TabGroup.cs b/dnSpy/dnSpy/Tabs/TabGroup.cs index 4da857afa6..00ff312d29 100644 --- a/dnSpy/dnSpy/Tabs/TabGroup.cs +++ b/dnSpy/dnSpy/Tabs/TabGroup.cs @@ -127,7 +127,7 @@ void SetFocus2(ITabContent content) { } void SetFocusNoChecks(IInputElement uiel) { - Debug2.Assert(!(uiel is null) && uiel.Focusable); + Debug2.Assert(uiel is not null && uiel.Focusable); if (uiel is null) return; wpfFocusService.Focus(uiel); @@ -170,7 +170,7 @@ void uiElem_IsVisibleChanged(object? sender, DependencyPropertyChangedEventArgs TabItemImpl? GetTabItemImpl(ITabContent content) { foreach (TabItemImpl? impl in tabControl.Items) { - Debug2.Assert(!(impl is null)); + Debug2.Assert(impl is not null); if (impl.TabContent == content) return impl; } @@ -219,7 +219,7 @@ public TabGroup(TabGroupService tabGroupService, IMenuService menuService, IWpfF tabControl.SetStyle(options.TabControlStyle ?? "FileTabGroupTabControlStyle"); tabControl.SelectionChanged += TabControl_SelectionChanged; tabControl.PreviewKeyDown += TabControl_PreviewKeyDown; - if (!(options.InitializeContextMenu is null)) + if (options.InitializeContextMenu is not null) contextMenuProvider = options.InitializeContextMenu(menuService, this, tabControl); else if (options.TabGroupGuid != Guid.Empty) contextMenuProvider = menuService.InitializeContextMenu(tabControl, options.TabGroupGuid, new GuidObjectsProvider(this)); @@ -288,14 +288,14 @@ void RemoveEvents(TabItemImpl impl) { void tabItem_GotKeyboardFocus(object? sender, KeyboardFocusChangedEventArgs e) { tabGroupService.SetActive(this); var tabItem = GetTabItemImpl(sender); - if (!(tabItem is null)) + if (tabItem is not null) tabItem.IsActive = true; IsActive = true; } void tabItem_LostKeyboardFocus(object? sender, KeyboardFocusChangedEventArgs e) { var tabItem = GetTabItemImpl(sender); - if (!(tabItem is null)) + if (tabItem is not null) tabItem.IsActive = false; IsActive = false; } @@ -480,7 +480,7 @@ public bool MoveToAndSelect(TabGroup dstTabGroup, TabItemImpl? srcTabItem, int i } public bool MoveTo(TabGroup dstTabGroup, TabItemImpl srcTabItem, TabItemImpl insertBeforeThis) { - if (!(insertBeforeThis is null)) { + if (insertBeforeThis is not null) { Debug.Assert(dstTabGroup.tabControl.Items.Contains(insertBeforeThis)); return MoveTo(dstTabGroup, srcTabItem, dstTabGroup.tabControl.Items.IndexOf(insertBeforeThis)); } @@ -595,7 +595,7 @@ void SelectTab(int index) { public void SelectPreviousTab() => SelectTab(tabControl.SelectedIndex - 1); public bool SelectPreviousTabCanExecute => tabControl.Items.Count > 1; public void CloseActiveTab() => RemoveTabItem(ActiveTabItemImpl); - public bool CloseActiveTabCanExecute => !(ActiveTabItemImpl is null); + public bool CloseActiveTabCanExecute => ActiveTabItemImpl is not null; public void CloseAllButActiveTab() { var activeTab = ActiveTabItemImpl; diff --git a/dnSpy/dnSpy/Tabs/TabGroupService.cs b/dnSpy/dnSpy/Tabs/TabGroupService.cs index 4f542f59c5..31f067198b 100644 --- a/dnSpy/dnSpy/Tabs/TabGroupService.cs +++ b/dnSpy/dnSpy/Tabs/TabGroupService.cs @@ -194,7 +194,7 @@ void Move(TabGroup dstTabGroup, TabGroup srcTabGroup, TabItemImpl? srcTabItemImp SetActive(dstTabGroup); } - public bool MoveToNextTabGroupCanExecute => ActiveIndex >= 0 && ActiveIndex + 1 < stackedContent.Count && !(stackedContent[ActiveIndex].ActiveTabItemImpl is null); + public bool MoveToNextTabGroupCanExecute => ActiveIndex >= 0 && ActiveIndex + 1 < stackedContent.Count && stackedContent[ActiveIndex].ActiveTabItemImpl is not null; public void MoveToNextTabGroup() { if (!MoveToNextTabGroupCanExecute) @@ -202,7 +202,7 @@ public void MoveToNextTabGroup() { Move(stackedContent[ActiveIndex + 1], stackedContent[ActiveIndex], stackedContent[ActiveIndex].ActiveTabItemImpl); } - public bool MoveToPreviousTabGroupCanExecute => ActiveIndex > 0 && !(stackedContent[ActiveIndex].ActiveTabItemImpl is null); + public bool MoveToPreviousTabGroupCanExecute => ActiveIndex > 0 && stackedContent[ActiveIndex].ActiveTabItemImpl is not null; public void MoveToPreviousTabGroup() { if (!MoveToPreviousTabGroupCanExecute) diff --git a/dnSpy/dnSpy/Tabs/TabUtils.cs b/dnSpy/dnSpy/Tabs/TabUtils.cs index 062034457a..b893cf59e2 100644 --- a/dnSpy/dnSpy/Tabs/TabUtils.cs +++ b/dnSpy/dnSpy/Tabs/TabUtils.cs @@ -28,7 +28,7 @@ public static void SetStyle(this FrameworkElement elem, object obj) { return; } - if (!(obj is null)) { + if (obj is not null) { elem.SetResourceReference(FrameworkElement.StyleProperty, obj); return; } diff --git a/dnSpy/dnSpy/Text/Adornments/ToolTipProvider.cs b/dnSpy/dnSpy/Text/Adornments/ToolTipProvider.cs index 5b9e8395db..42f71926a9 100644 --- a/dnSpy/dnSpy/Text/Adornments/ToolTipProvider.cs +++ b/dnSpy/dnSpy/Text/Adornments/ToolTipProvider.cs @@ -45,7 +45,7 @@ public ToolTipProvider(IWpfTextView wpfTextView) { } public void ClearToolTip() { - if (!(toolTipAgent is null)) + if (toolTipAgent is not null) spaceReservationManager.RemoveAgent(toolTipAgent); } diff --git a/dnSpy/dnSpy/Text/AvalonEdit/CharRope.cs b/dnSpy/dnSpy/Text/AvalonEdit/CharRope.cs index 42884af1e4..a4ea08f5b6 100644 --- a/dnSpy/dnSpy/Text/AvalonEdit/CharRope.cs +++ b/dnSpy/dnSpy/Text/AvalonEdit/CharRope.cs @@ -85,7 +85,7 @@ internal static RopeNode InitFromString(string text) { } static void FillNode(RopeNode node, string text, int start) { - if (!(node.contents is null)) { + if (node.contents is not null) { text.CopyTo(start, node.contents, 0, node.length); } else { diff --git a/dnSpy/dnSpy/Text/AvalonEdit/DocumentLine.cs b/dnSpy/dnSpy/Text/AvalonEdit/DocumentLine.cs index 85d30b1e7d..693a349b72 100644 --- a/dnSpy/dnSpy/Text/AvalonEdit/DocumentLine.cs +++ b/dnSpy/dnSpy/Text/AvalonEdit/DocumentLine.cs @@ -48,7 +48,7 @@ sealed partial class DocumentLine { internal DocumentLine(TextDocument document) { #if DEBUG - Debug2.Assert(!(document is null)); + Debug2.Assert(document is not null); this.document = document; #endif } @@ -159,7 +159,7 @@ public DocumentLine? NextLine { get { DebugVerifyAccess(); - if (!(right is null)) { + if (right is not null) { return right.LeftMost; } else { @@ -169,7 +169,7 @@ public DocumentLine? NextLine { oldNode = node; node = node.parent; // we are on the way up from the right part, don't output node again - } while (!(node is null) && node.right == oldNode); + } while (node is not null && node.right == oldNode); return node; } } @@ -183,7 +183,7 @@ public DocumentLine? PreviousLine { get { DebugVerifyAccess(); - if (!(left is null)) { + if (left is not null) { return left.RightMost; } else { @@ -193,7 +193,7 @@ public DocumentLine? PreviousLine { oldNode = node; node = node.parent; // we are on the way up from the left part, don't output node again - } while (!(node is null) && node.left == oldNode); + } while (node is not null && node.left == oldNode); return node; } } diff --git a/dnSpy/dnSpy/Text/AvalonEdit/DocumentLineTree.cs b/dnSpy/dnSpy/Text/AvalonEdit/DocumentLineTree.cs index e3c9140aa5..9ab8f3dbad 100644 --- a/dnSpy/dnSpy/Text/AvalonEdit/DocumentLineTree.cs +++ b/dnSpy/dnSpy/Text/AvalonEdit/DocumentLineTree.cs @@ -49,11 +49,11 @@ public DocumentLineTree(TextDocument document) { internal static void UpdateAfterChildrenChange(LineNode node) { int totalCount = 1; int totalLength = node.TotalLength; - if (!(node.left is null)) { + if (node.left is not null) { totalCount += node.left.nodeTotalCount; totalLength += node.left.nodeTotalLength; } - if (!(node.right is null)) { + if (node.right is not null) { totalCount += node.right.nodeTotalCount; totalLength += node.right.nodeTotalLength; } @@ -61,7 +61,7 @@ internal static void UpdateAfterChildrenChange(LineNode node) { || totalLength != node.nodeTotalLength) { node.nodeTotalCount = totalCount; node.nodeTotalLength = totalLength; - if (!(node.parent is null)) + if (node.parent is not null) UpdateAfterChildrenChange(node.parent); } } @@ -112,9 +112,9 @@ LineNode BuildTree(LineNode[] nodes, int start, int end, int subtreeHeight) { LineNode node = nodes[middle]; node.left = BuildTree(nodes, start, middle, subtreeHeight - 1); node.right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1); - if (!(node.left is null)) + if (node.left is not null) node.left.parent = node; - if (!(node.right is null)) + if (node.right is not null) node.right.parent = node; if (subtreeHeight == 1) node.color = RED; @@ -129,11 +129,11 @@ LineNode GetNodeByIndex(int index) { Debug.Assert(index < root.nodeTotalCount); LineNode node = root; while (true) { - if (!(node.left is null) && index < node.left.nodeTotalCount) { + if (node.left is not null && index < node.left.nodeTotalCount) { node = node.left; } else { - if (!(node.left is null)) { + if (node.left is not null) { index -= node.left.nodeTotalCount; } if (index == 0) @@ -145,10 +145,10 @@ LineNode GetNodeByIndex(int index) { } internal static int GetIndexFromNode(LineNode node) { - int index = (!(node.left is null)) ? node.left.nodeTotalCount : 0; - while (!(node.parent is null)) { + int index = (node.left is not null) ? node.left.nodeTotalCount : 0; + while (node.parent is not null) { if (node == node.parent.right) { - if (!(node.parent.left is null)) + if (node.parent.left is not null) index += node.parent.left.nodeTotalCount; index++; } @@ -165,11 +165,11 @@ LineNode GetNodeByOffset(int offset) { } LineNode node = root; while (true) { - if (!(node.left is null) && offset < node.left.nodeTotalLength) { + if (node.left is not null && offset < node.left.nodeTotalLength) { node = node.left; } else { - if (!(node.left is null)) { + if (node.left is not null) { offset -= node.left.nodeTotalLength; } offset -= node.TotalLength; @@ -181,10 +181,10 @@ LineNode GetNodeByOffset(int offset) { } internal static int GetOffsetFromNode(LineNode node) { - int offset = (!(node.left is null)) ? node.left.nodeTotalLength : 0; - while (!(node.parent is null)) { + int offset = (node.left is not null) ? node.left.nodeTotalLength : 0; + while (node.parent is not null) { if (node == node.parent.right) { - if (!(node.parent.left is null)) + if (node.parent.left is not null) offset += node.parent.left.nodeTotalLength; offset += node.parent.TotalLength; } @@ -223,12 +223,12 @@ internal void CheckProperties() { void CheckProperties(LineNode node) { int totalCount = 1; int totalLength = node.TotalLength; - if (!(node.left is null)) { + if (node.left is not null) { CheckProperties(node.left); totalCount += node.left.nodeTotalCount; totalLength += node.left.nodeTotalLength; } - if (!(node.right is null)) { + if (node.right is not null) { CheckProperties(node.right); totalCount += node.right.nodeTotalCount; totalLength += node.right.nodeTotalLength; @@ -280,12 +280,12 @@ static void AppendTreeToString(LineNode node, StringBuilder b, int indent) { b.Append("BLACK "); b.AppendLine(node.ToString()); indent += 2; - if (!(node.left is null)) { + if (node.left is not null) { b.Append(' ', indent); b.Append("L: "); AppendTreeToString(node.left, b, indent); } - if (!(node.right is null)) { + if (node.right is not null) { b.Append(' ', indent); b.Append("R: "); AppendTreeToString(node.right, b, indent); @@ -342,7 +342,7 @@ void InsertAsRight(LineNode parentNode, LineNode newNode) { } void FixTreeOnInsert(LineNode node) { - Debug2.Assert(!(node is null)); + Debug2.Assert(node is not null); Debug.Assert(node.color == RED); Debug2.Assert(node.left is null || node.left.color == BLACK); Debug2.Assert(node.right is null || node.right.color == BLACK); @@ -366,7 +366,7 @@ void FixTreeOnInsert(LineNode node) { // because the root is black, parentNode is not the root -> there is a grandparent node LineNode grandparentNode = parentNode.parent; LineNode uncleNode = Sibling(parentNode); - if (!(uncleNode is null) && uncleNode.color == RED) { + if (uncleNode is not null && uncleNode.color == RED) { parentNode.color = BLACK; uncleNode.color = BLACK; grandparentNode.color = RED; @@ -402,7 +402,7 @@ void FixTreeOnInsert(LineNode node) { } void RemoveNode(LineNode removedNode) { - if (!(removedNode.left is null) && !(removedNode.right is null)) { + if (removedNode.left is not null && removedNode.right is not null) { // replace removedNode with it's in-order successor LineNode leftMost = removedNode.right.LeftMost; @@ -411,15 +411,15 @@ void RemoveNode(LineNode removedNode) { // and overwrite the removedNode with it ReplaceNode(removedNode, leftMost); leftMost.left = removedNode.left; - if (!(leftMost.left is null)) + if (leftMost.left is not null) leftMost.left.parent = leftMost; leftMost.right = removedNode.right; - if (!(leftMost.right is null)) + if (leftMost.right is not null) leftMost.right.parent = leftMost; leftMost.color = removedNode.color; UpdateAfterChildrenChange(leftMost); - if (!(leftMost.parent is null)) + if (leftMost.parent is not null) UpdateAfterChildrenChange(leftMost.parent); return; } @@ -429,10 +429,10 @@ void RemoveNode(LineNode removedNode) { LineNode parentNode = removedNode.parent; LineNode childNode = removedNode.left ?? removedNode.right; ReplaceNode(removedNode, childNode); - if (!(parentNode is null)) + if (parentNode is not null) UpdateAfterChildrenChange(parentNode); if (removedNode.color == BLACK) { - if (!(childNode is null) && childNode.color == RED) { + if (childNode is not null && childNode.color == RED) { childNode.color = BLACK; } else { @@ -500,14 +500,14 @@ void FixTreeOnDelete(LineNode node, LineNode parentNode) { sibling.color = parentNode.color; parentNode.color = BLACK; if (node == parentNode.left) { - if (!(sibling.right is null)) { + if (sibling.right is not null) { Debug.Assert(sibling.right.color == RED); sibling.right.color = BLACK; } RotateLeft(parentNode); } else { - if (!(sibling.left is null)) { + if (sibling.left is not null) { Debug.Assert(sibling.left.color == RED); sibling.left.color = BLACK; } @@ -526,7 +526,7 @@ void ReplaceNode(LineNode replacedNode, LineNode newNode) { else replacedNode.parent.right = newNode; } - if (!(newNode is null)) { + if (newNode is not null) { newNode.parent = replacedNode.parent; } replacedNode.parent = null; @@ -535,14 +535,14 @@ void ReplaceNode(LineNode replacedNode, LineNode newNode) { void RotateLeft(LineNode p) { // let q be p's right child LineNode q = p.right; - Debug2.Assert(!(q is null)); + Debug2.Assert(q is not null); Debug.Assert(q.parent == p); // set q to be the new root ReplaceNode(p, q); // set p's right child to be q's left child p.right = q.left; - if (!(p.right is null)) + if (p.right is not null) p.right.parent = p; // set q's left child to be p q.left = p; @@ -553,14 +553,14 @@ void RotateLeft(LineNode p) { void RotateRight(LineNode p) { // let q be p's left child LineNode q = p.left; - Debug2.Assert(!(q is null)); + Debug2.Assert(q is not null); Debug.Assert(q.parent == p); // set q to be the new root ReplaceNode(p, q); // set p's left child to be q's right child p.left = q.right; - if (!(p.left is null)) + if (p.left is not null) p.left.parent = p; // set q's right child to be p q.right = p; @@ -583,7 +583,7 @@ static LineNode Sibling(LineNode node, LineNode parentNode) { return parentNode.left; } - static bool GetColor(LineNode node) => !(node is null) ? node.color : BLACK; + static bool GetColor(LineNode node) => node is not null ? node.color : BLACK; #endregion #region IList implementation @@ -649,7 +649,7 @@ public IEnumerator GetEnumerator() { IEnumerator Enumerate() { document.VerifyAccess(); DocumentLine line = root.LeftMost; - while (!(line is null)) { + while (line is not null) { yield return line; line = line.NextLine; } diff --git a/dnSpy/dnSpy/Text/AvalonEdit/LineManager.cs b/dnSpy/dnSpy/Text/AvalonEdit/LineManager.cs index 3af5bd5ef9..a037ff1166 100644 --- a/dnSpy/dnSpy/Text/AvalonEdit/LineManager.cs +++ b/dnSpy/dnSpy/Text/AvalonEdit/LineManager.cs @@ -42,7 +42,7 @@ public void Rebuild() { // keep the first document line DocumentLine ls = documentLineTree.GetByNumber(1); // but mark all other lines as deleted, and detach them from the other nodes - for (DocumentLine line = ls.NextLine; !(line is null); line = line.NextLine) { + for (DocumentLine line = ls.NextLine; line is not null; line = line.NextLine) { line.isDeleted = true; line.parent = line.left = line.right = null; } diff --git a/dnSpy/dnSpy/Text/AvalonEdit/LineNode.cs b/dnSpy/dnSpy/Text/AvalonEdit/LineNode.cs index 5dd6aff36a..0e0e96d46e 100644 --- a/dnSpy/dnSpy/Text/AvalonEdit/LineNode.cs +++ b/dnSpy/dnSpy/Text/AvalonEdit/LineNode.cs @@ -61,7 +61,7 @@ internal LineNode InitLineNode() { internal LineNode LeftMost { get { LineNode node = this; - while (!(node.left is null)) + while (node.left is not null) node = node.left; return node; } @@ -70,7 +70,7 @@ internal LineNode LeftMost { internal LineNode RightMost { get { LineNode node = this; - while (!(node.right is null)) + while (node.right is not null) node = node.right; return node; } diff --git a/dnSpy/dnSpy/Text/AvalonEdit/Rope.cs b/dnSpy/dnSpy/Text/AvalonEdit/Rope.cs index d249fd8c1f..44181d07fa 100644 --- a/dnSpy/dnSpy/Text/AvalonEdit/Rope.cs +++ b/dnSpy/dnSpy/Text/AvalonEdit/Rope.cs @@ -58,7 +58,7 @@ public Rope(IEnumerable input) { } else { string text = input as string; - if (!(text is null)) { + if (text is not null) { // if a string is IEnumerable, then T must be char ((Rope)(object)this).root = CharRope.InitFromString(text); } @@ -256,7 +256,7 @@ internal ImmutableStack FindNodeUsingCache(int index) { entry = new RopeCacheEntry(entry.node.GetContentNode(), entry.nodeStartIndex); // entry is now guaranteed NOT to be another function node } - if (!(entry.node.contents is null)) { + if (entry.node.contents is not null) { // this is a node containing actual content, so we're done break; } @@ -276,7 +276,7 @@ internal ImmutableStack FindNodeUsingCache(int index) { } // this method guarantees that it finds a leaf node - Debug2.Assert(!(stack.Peek().node.contents is null)); + Debug2.Assert(stack.Peek().node.contents is not null); return stack; } #endregion @@ -313,7 +313,7 @@ internal static void VerifyArrayWithRange(T[] array, int arrayIndex, int count) /// public override string ToString() { Rope charRope = this as Rope; - if (!(charRope is null)) { + if (charRope is not null) { return charRope.ToString(0, Length); } else { @@ -499,7 +499,7 @@ public T[] ToArray(int startIndex, int count) { static IEnumerator Enumerate(RopeNode node) { Stack> stack = new Stack>(); - while (!(node is null)) { + while (node is not null) { // go to leftmost node, pushing the right parts that we'll have to visit later while (node.contents is null) { if (node.height == 0) { @@ -507,7 +507,7 @@ static IEnumerator Enumerate(RopeNode node) { node = node.GetContentNode(); continue; } - Debug2.Assert(!(node.right is null)); + Debug2.Assert(node.right is not null); stack.Push(node.right); node = node.left; } diff --git a/dnSpy/dnSpy/Text/AvalonEdit/RopeNode.cs b/dnSpy/dnSpy/Text/AvalonEdit/RopeNode.cs index 7577649212..35b299a339 100644 --- a/dnSpy/dnSpy/Text/AvalonEdit/RopeNode.cs +++ b/dnSpy/dnSpy/Text/AvalonEdit/RopeNode.cs @@ -57,12 +57,12 @@ internal void CheckInvariants() { Debug.Assert(isShared); } else { - Debug2.Assert(!(contents is null) && contents.Length == NodeSize); + Debug2.Assert(contents is not null && contents.Length == NodeSize); Debug.Assert(length >= 0 && length <= NodeSize); } } else { - Debug2.Assert(!(left is null) && !(right is null)); + Debug2.Assert(left is not null && right is not null); Debug2.Assert(contents is null); Debug.Assert(length == left.length + right.length); Debug.Assert(height == 1 + Math.Max(left.height, right.height)); @@ -110,9 +110,9 @@ internal RopeNode CloneIfShared() { internal void Publish() { if (!isShared) { - if (!(left is null)) + if (left is not null) left.Publish(); - if (!(right is null)) + if (right is not null) right.Publish(); // it's important that isShared=true is set at the end: // Publish() must not return until the whole subtree is marked as shared, even when @@ -263,7 +263,7 @@ void MergeIfPossible() { } else { // must be a leaf node: function nodes are always marked shared - Debug2.Assert(!(left.contents is null)); + Debug2.Assert(left.contents is not null); // steal buffer from left side contents = left.contents; #if DEBUG @@ -383,7 +383,7 @@ internal static RopeNode Concat(RopeNode left, RopeNode right) { /// Splits this leaf node at offset and returns a new node with the part of the text after offset. /// RopeNode SplitAfter(int offset) { - Debug2.Assert(!isShared && height == 0 && !(contents is null)); + Debug2.Assert(!isShared && height == 0 && contents is not null); RopeNode newPart = new RopeNode(); newPart.contents = new T[NodeSize]; newPart.length = length - offset; @@ -505,12 +505,12 @@ internal RopeNode RemoveRange(int index, int count) { internal virtual void AppendTreeToString(StringBuilder b, int indent) { b.AppendLine(ToString()); indent += 2; - if (!(left is null)) { + if (left is not null) { b.Append(' ', indent); b.Append("L: "); left.AppendTreeToString(b, indent); } - if (!(right is null)) { + if (right is not null) { b.Append(' ', indent); b.Append("R: "); right.AppendTreeToString(b, indent); @@ -518,9 +518,9 @@ internal virtual void AppendTreeToString(StringBuilder b, int indent) { } public override string ToString() { - if (!(contents is null)) { + if (contents is not null) { char[] charContents = contents as char[]; - if (!(charContents is null)) + if (charContents is not null) return "[Leaf length=" + length + ", isShared=" + isShared + ", text=\"" + new string(charContents, 0, length) + "\"]"; else return "[Leaf length=" + length + ", isShared=" + isShared + "\"]"; @@ -552,7 +552,7 @@ sealed class FunctionNode : RopeNode { public FunctionNode(int length, Func> initializer) { Debug.Assert(length > 0); - Debug2.Assert(!(initializer is null)); + Debug2.Assert(initializer is not null); this.length = length; this.initializer = initializer; @@ -597,7 +597,7 @@ internal override void AppendTreeToString(StringBuilder b, int indent) { resultNode = cachedResults; } indent += 2; - if (!(resultNode is null)) { + if (resultNode is not null) { b.Append(' ', indent); b.Append("C: "); resultNode.AppendTreeToString(b, indent); diff --git a/dnSpy/dnSpy/Text/AvalonEdit/TextDocument.cs b/dnSpy/dnSpy/Text/AvalonEdit/TextDocument.cs index d7072f58f1..a85f8229bb 100644 --- a/dnSpy/dnSpy/Text/AvalonEdit/TextDocument.cs +++ b/dnSpy/dnSpy/Text/AvalonEdit/TextDocument.cs @@ -47,7 +47,7 @@ sealed class TextDocument : ITextSource { /// It is possible to change the owner thread using the method. /// public void VerifyAccess() { - if (!(owner is null) && Thread.CurrentThread != owner) + if (owner is not null && Thread.CurrentThread != owner) throw new InvalidOperationException("TextDocument can be accessed only from the thread that owns it."); } @@ -67,7 +67,7 @@ public void SetOwnerThread(Thread newOwner) { // We need to lock here to ensure that in the null owner case, // only one thread succeeds in taking ownership. lock (lockObject) { - if (!(owner is null)) { + if (owner is not null) { VerifyAccess(); } owner = newOwner; @@ -153,7 +153,7 @@ public char[] ToCharArray(int startIndex, int length) { public string Text { get { VerifyAccess(); - string completeText = !(cachedText is null) ? (cachedText.Target as string) : null; + string completeText = cachedText is not null ? (cachedText.Target as string) : null; if (completeText is null) { completeText = rope.ToString(); cachedText = new WeakReference(completeText); diff --git a/dnSpy/dnSpy/Text/CachedColorsListTagger.cs b/dnSpy/dnSpy/Text/CachedColorsListTagger.cs index 1caa1c8df9..2a006b1d7b 100644 --- a/dnSpy/dnSpy/Text/CachedColorsListTagger.cs +++ b/dnSpy/dnSpy/Text/CachedColorsListTagger.cs @@ -78,8 +78,8 @@ internal static CachedColorsListTagger Create(CachedColorsList cachedColorsList) new CachedColorsListTagger(cachedColorsList); public IEnumerable> GetTags(NormalizedSnapshotSpanCollection spans) { - Debug2.Assert(!(ThemeClassificationTypeService is null)); - Debug2.Assert(!(ClassificationTypeRegistryService is null)); + Debug2.Assert(ThemeClassificationTypeService is not null); + Debug2.Assert(ClassificationTypeRegistryService is not null); if (ThemeClassificationTypeService is null || ClassificationTypeRegistryService is null) yield break; if (textClassificationType is null) diff --git a/dnSpy/dnSpy/Text/Classification/CategoryClassificationFormatMap.cs b/dnSpy/dnSpy/Text/Classification/CategoryClassificationFormatMap.cs index bff3b29ded..277d0118a7 100644 --- a/dnSpy/dnSpy/Text/Classification/CategoryClassificationFormatMap.cs +++ b/dnSpy/dnSpy/Text/Classification/CategoryClassificationFormatMap.cs @@ -34,7 +34,7 @@ namespace dnSpy.Text.Classification { sealed class CategoryClassificationFormatMap : IClassificationFormatMap { public TextFormattingRunProperties DefaultTextProperties { get { - Debug2.Assert(!(defaultTextFormattingRunProperties is null)); + Debug2.Assert(defaultTextFormattingRunProperties is not null); return defaultTextFormattingRunProperties; } set { @@ -103,7 +103,7 @@ public CategoryClassificationFormatMap(IThemeService themeService, IEditorFormat var e = editorFormatDefinitionService.ClassificationFormatDefinitions[i]; foreach (var ctString in e.Metadata.ClassificationTypeNames) { var classificationType = classificationTypeRegistryService.GetClassificationType(ctString); - Debug2.Assert(!(classificationType is null)); + Debug2.Assert(classificationType is not null); if (classificationType is null) continue; Debug.Assert(!toEditorFormatDefinition.ContainsKey(classificationType)); @@ -169,7 +169,7 @@ public TextFormattingRunProperties GetExplicitTextProperties(IClassificationType return TextFormattingRunProperties.CreateTextFormattingRunProperties(); if (info.ExplicitTextProperties is null) CreateExplicitTextProperties(info); - Debug2.Assert(!(info.ExplicitTextProperties is null)); + Debug2.Assert(info.ExplicitTextProperties is not null); return info.ExplicitTextProperties; } @@ -177,10 +177,10 @@ public TextFormattingRunProperties GetTextProperties(IClassificationType classif if (classificationType is null) throw new ArgumentNullException(nameof(classificationType)); var info = TryGetClassificationInfo(classificationType, canCreate: true); - Debug2.Assert(!(info is null)); + Debug2.Assert(info is not null); if (info.InheritedTextProperties is null) CreateInheritedTextProperties(info); - Debug2.Assert(!(info.InheritedTextProperties is null)); + Debug2.Assert(info.InheritedTextProperties is not null); return info.InheritedTextProperties; } diff --git a/dnSpy/dnSpy/Text/Classification/ClassificationFontUtils.cs b/dnSpy/dnSpy/Text/Classification/ClassificationFontUtils.cs index cfa82211fe..486e912f4e 100644 --- a/dnSpy/dnSpy/Text/Classification/ClassificationFontUtils.cs +++ b/dnSpy/dnSpy/Text/Classification/ClassificationFontUtils.cs @@ -76,15 +76,15 @@ public static TextFormattingRunProperties Create(ResourceDictionary dict) { var cultureInfo = dict[ClassificationFormatDefinition.CultureInfoId] as CultureInfo; var textRunProps = TextFormattingRunProperties.CreateTextFormattingRunProperties(foreground, background, typeface, size, hintingSize, textDecorations, textEffects, cultureInfo); var isItalic = dict[ClassificationFormatDefinition.IsItalicId] as bool?; - if (!(isItalic is null)) + if (isItalic is not null) textRunProps = textRunProps.SetItalic(isItalic.Value); var isBold = dict[ClassificationFormatDefinition.IsBoldId] as bool?; - if (!(isBold is null)) + if (isBold is not null) textRunProps = textRunProps.SetBold(isBold.Value); double? opacity; - if (foreground is null && !((opacity = dict[ClassificationFormatDefinition.ForegroundOpacityId] as double?) is null)) + if (foreground is null && (opacity = dict[ClassificationFormatDefinition.ForegroundOpacityId] as double?) is not null) textRunProps = textRunProps.SetForegroundOpacity(opacity.Value); - if (background is null && !((opacity = dict[ClassificationFormatDefinition.BackgroundOpacityId] as double?) is null)) + if (background is null && (opacity = dict[ClassificationFormatDefinition.BackgroundOpacityId] as double?) is not null) textRunProps = textRunProps.SetBackgroundOpacity(opacity.Value); return textRunProps; } @@ -93,7 +93,7 @@ public static TextFormattingRunProperties Create(ResourceDictionary dict) { var brush = dict[brushId] as Brush; if (brush is null) { var color = dict[colorId] as Color?; - if (!(color is null)) + if (color is not null) brush = new SolidColorBrush(color.Value); } if (brush is null) @@ -102,7 +102,7 @@ public static TextFormattingRunProperties Create(ResourceDictionary dict) { return brush; var opacity = dict[opacityId] as double? ?? defaultOpacity; - if (!(opacity is null)) { + if (opacity is not null) { brush = brush.Clone(); brush.Opacity = opacity.Value; } diff --git a/dnSpy/dnSpy/Text/Classification/ClassificationTypeRegistryService.cs b/dnSpy/dnSpy/Text/Classification/ClassificationTypeRegistryService.cs index 9602c92f54..cd8df07baa 100644 --- a/dnSpy/dnSpy/Text/Classification/ClassificationTypeRegistryService.cs +++ b/dnSpy/dnSpy/Text/Classification/ClassificationTypeRegistryService.cs @@ -54,7 +54,7 @@ public ClassificationTypeCreator(ClassificationTypeRegistryService owner, IEnume rawClassificationTypes = new Dictionary(); foreach (var md in classificationTypeDefinitions.Select(a => a.Metadata)) { var type = md.Name; - Debug2.Assert(!(type is null)); + Debug2.Assert(type is not null); if (type is null) continue; Debug.Assert(!rawClassificationTypes.ContainsKey(type)); @@ -76,7 +76,7 @@ public ClassificationTypeCreator(ClassificationTypeRegistryService owner, IEnume IClassificationType? TryCreate(string type, int recurse) { var ct = TryGet(type); - if (!(ct is null)) + if (ct is not null) return ct; const int MAX_RECURSE = 1000; @@ -88,7 +88,7 @@ public ClassificationTypeCreator(ClassificationTypeRegistryService owner, IEnume Debug.Assert(b); if (!b) return null; - Debug2.Assert(!(rawCt is null)); + Debug2.Assert(rawCt is not null); b = rawClassificationTypes.Remove(rawCt.Type); Debug.Assert(b); diff --git a/dnSpy/dnSpy/Text/Classification/ClassifierAggregatorBase.cs b/dnSpy/dnSpy/Text/Classification/ClassifierAggregatorBase.cs index 2f834f2115..d04afe2e86 100644 --- a/dnSpy/dnSpy/Text/Classification/ClassifierAggregatorBase.cs +++ b/dnSpy/dnSpy/Text/Classification/ClassifierAggregatorBase.cs @@ -77,11 +77,11 @@ IList GetClassificationSpansCore(SnapshotSpan span, Cancella var list = new List(); var targetSnapshot = span.Snapshot; - var tags = !(cancellationToken is null) ? tagAggregator.GetTags(span, cancellationToken.Value) : tagAggregator.GetTags(span); + var tags = cancellationToken is not null ? tagAggregator.GetTags(span, cancellationToken.Value) : tagAggregator.GetTags(span); foreach (var mspan in tags) { foreach (var s in mspan.Span.GetSpans(textBuffer)) { var overlap = span.Overlap(s.TranslateTo(targetSnapshot, SpanTrackingMode.EdgeExclusive)); - if (!(overlap is null)) + if (overlap is not null) list.Add(new ClassificationSpan(overlap.Value, mspan.Tag.ClassificationType)); } } diff --git a/dnSpy/dnSpy/Text/Classification/ClassifierTaggerProvider.cs b/dnSpy/dnSpy/Text/Classification/ClassifierTaggerProvider.cs index 5f4e5fcd68..9557c87bfd 100644 --- a/dnSpy/dnSpy/Text/Classification/ClassifierTaggerProvider.cs +++ b/dnSpy/dnSpy/Text/Classification/ClassifierTaggerProvider.cs @@ -58,7 +58,7 @@ IEnumerable GetClassifiers(ITextBuffer buffer) { foreach (var ct in info.Metadata.ContentTypes) { if (bufferContentType.IsOfType(ct)) { var classifier = info.Value.GetClassifier(buffer); - if (!(classifier is null)) + if (classifier is not null) yield return classifier; break; } diff --git a/dnSpy/dnSpy/Text/Classification/TextClassifierAggregatorService.cs b/dnSpy/dnSpy/Text/Classification/TextClassifierAggregatorService.cs index 29aba173a5..7ffbbfdacb 100644 --- a/dnSpy/dnSpy/Text/Classification/TextClassifierAggregatorService.cs +++ b/dnSpy/dnSpy/Text/Classification/TextClassifierAggregatorService.cs @@ -45,7 +45,7 @@ public ITextClassifierAggregator Create(IContentType contentType) { if (!contentType.IsOfAnyType(lz.Metadata.ContentTypes)) continue; var classifier = lz.Value.Create(contentType); - if (!(classifier is null)) + if (classifier is not null) list.Add(classifier); } return new TextClassifierAggregator(classificationTypeRegistryService, list); diff --git a/dnSpy/dnSpy/Text/Classification/ThemeClassificationTypeService.cs b/dnSpy/dnSpy/Text/Classification/ThemeClassificationTypeService.cs index b46d69c389..99ab0da97b 100644 --- a/dnSpy/dnSpy/Text/Classification/ThemeClassificationTypeService.cs +++ b/dnSpy/dnSpy/Text/Classification/ThemeClassificationTypeService.cs @@ -351,7 +351,7 @@ sealed class ThemeClassificationTypeService : IThemeClassificationTypeService { classificationTypeRegistryService.GetClassificationType(ThemeClassificationTypeNames.AsmHexBytes), }; foreach (var ct in classificationTypes) { - Debug2.Assert(!(ct is null)); + Debug2.Assert(ct is not null); if (ct is null) throw new InvalidOperationException(); } diff --git a/dnSpy/dnSpy/Text/Classification/ViewClassificationFormatMap.cs b/dnSpy/dnSpy/Text/Classification/ViewClassificationFormatMap.cs index 8ca0d62708..8fc7a2aa07 100644 --- a/dnSpy/dnSpy/Text/Classification/ViewClassificationFormatMap.cs +++ b/dnSpy/dnSpy/Text/Classification/ViewClassificationFormatMap.cs @@ -59,7 +59,7 @@ void UpdateAppearanceMap() { if (categoryMap == newMap) return; - if (!(categoryMap is null)) + if (categoryMap is not null) categoryMap.ClassificationFormatMappingChanged -= CategoryMap_ClassificationFormatMappingChanged; categoryMap = newMap; categoryMap.ClassificationFormatMappingChanged += CategoryMap_ClassificationFormatMappingChanged; @@ -97,7 +97,7 @@ public void SwapPriorities(IClassificationType firstType, IClassificationType se public void EndBatchUpdate() => categoryMap.EndBatchUpdate(); public void Dispose() { - if (!(categoryMap is null)) + if (categoryMap is not null) categoryMap.ClassificationFormatMappingChanged -= CategoryMap_ClassificationFormatMappingChanged; DisposeCore(); } diff --git a/dnSpy/dnSpy/Text/Classification/ViewEditorFormatMap.cs b/dnSpy/dnSpy/Text/Classification/ViewEditorFormatMap.cs index 955396ace2..e8552ea1fd 100644 --- a/dnSpy/dnSpy/Text/Classification/ViewEditorFormatMap.cs +++ b/dnSpy/dnSpy/Text/Classification/ViewEditorFormatMap.cs @@ -57,7 +57,7 @@ void UpdateAppearanceMap() { if (categoryMap == newMap) return; - if (!(categoryMap is null)) + if (categoryMap is not null) categoryMap.FormatMappingChanged -= CategoryMap_FormatMappingChanged; categoryMap = newMap; categoryMap.FormatMappingChanged += CategoryMap_FormatMappingChanged; @@ -86,7 +86,7 @@ public void SetProperties(string key, ResourceDictionary properties) { } public void Dispose() { - if (!(categoryMap is null)) + if (categoryMap is not null) categoryMap.FormatMappingChanged -= CategoryMap_FormatMappingChanged; DisposeCore(); } diff --git a/dnSpy/dnSpy/Text/ContentTypeRegistryService.cs b/dnSpy/dnSpy/Text/ContentTypeRegistryService.cs index e4a6641a66..2811c55827 100644 --- a/dnSpy/dnSpy/Text/ContentTypeRegistryService.cs +++ b/dnSpy/dnSpy/Text/ContentTypeRegistryService.cs @@ -72,14 +72,14 @@ public ContentTypeCreator(ContentTypeRegistryService owner, IEnumerable(StringComparer.OrdinalIgnoreCase); foreach (var md in contentTypeDefinitions.Select(a => a.Metadata)) { var typeName = md.Name; - Debug2.Assert(!(typeName is null)); + Debug2.Assert(typeName is not null); if (typeName is null) continue; Debug.Assert(!rawContentTypes.ContainsKey(typeName)); if (rawContentTypes.ContainsKey(typeName)) continue; var baseTypes = (md.BaseDefinition ?? Array.Empty()).ToArray(); - Debug2.Assert(!(baseTypes is null)); + Debug2.Assert(baseTypes is not null); if (baseTypes is null) continue; var rawCt = new RawContentType(typeName, baseTypes, md.MimeType); @@ -97,7 +97,7 @@ public ContentTypeCreator(ContentTypeRegistryService owner, IEnumerable= 0; i--) { var elem = adornmentLayerElements[i]; - if (!(elem.VisualSpan is null) && visualSpan.OverlapsWith(GetOverlapsWithSpan(elem.VisualSpan.Value))) { + if (elem.VisualSpan is not null && visualSpan.OverlapsWith(GetOverlapsWithSpan(elem.VisualSpan.Value))) { adornmentLayerElements.RemoveAt(i); Children.RemoveAt(i); elem.RemovedCallback?.Invoke(elem.Tag, elem.Adornment); @@ -149,7 +149,7 @@ public void RemoveMatchingAdornments(SnapshotSpan visualSpan, Predicate= 0; i--) { var elem = adornmentLayerElements[i]; - if (!(elem.VisualSpan is null) && visualSpan.OverlapsWith(GetOverlapsWithSpan(elem.VisualSpan.Value)) && match(elem)) { + if (elem.VisualSpan is not null && visualSpan.OverlapsWith(GetOverlapsWithSpan(elem.VisualSpan.Value)) && match(elem)) { adornmentLayerElements.RemoveAt(i); Children.RemoveAt(i); elem.RemovedCallback?.Invoke(elem.Tag, elem.Adornment); @@ -171,8 +171,8 @@ internal void OnLayoutChanged(TextViewLayoutChangedEventArgs e) { elem.OnLayoutChanged(e.NewSnapshot); // All adornments that exist in spans that have been removed or in reformatted lines are always removed. - if (!(elem.VisualSpan is null) && - (!TextView.TextViewLines.IntersectsBufferSpan(elem.VisualSpan.Value) || !(GetLine(e.NewOrReformattedLines, GetOverlapsWithSpan(elem.VisualSpan.Value)) is null))) { + if (elem.VisualSpan is not null && + (!TextView.TextViewLines.IntersectsBufferSpan(elem.VisualSpan.Value) || GetLine(e.NewOrReformattedLines, GetOverlapsWithSpan(elem.VisualSpan.Value)) is not null)) { adornmentLayerElements.RemoveAt(i); Children.RemoveAt(i); elem.RemovedCallback?.Invoke(elem.Tag, elem.Adornment); @@ -189,9 +189,9 @@ internal void OnLayoutChanged(TextViewLayoutChangedEventArgs e) { break; case AdornmentPositioningBehavior.TextRelative: - Debug2.Assert(!(elem.VisualSpan is null)); + Debug2.Assert(elem.VisualSpan is not null); var translatedLine = GetLine(e.TranslatedLines, GetOverlapsWithSpan(elem.VisualSpan.Value)); - if (!(translatedLine is null)) { + if (translatedLine is not null) { // Only y is updated, x is owner controlled SetTop(elem.Adornment, ToDefault(GetTop(elem.Adornment), 0) + translatedLine.DeltaY); } diff --git a/dnSpy/dnSpy/Text/Editor/BlockStructureService.cs b/dnSpy/dnSpy/Text/Editor/BlockStructureService.cs index e1e827211e..c9cff6c391 100644 --- a/dnSpy/dnSpy/Text/Editor/BlockStructureService.cs +++ b/dnSpy/dnSpy/Text/Editor/BlockStructureService.cs @@ -154,7 +154,7 @@ void RefreshLinesAndColorInfos() { } void UpdateColorInfos() { - Debug2.Assert(!(editorFormatMap is null)); + Debug2.Assert(editorFormatMap is not null); var lineKind = wpfTextView.Options.GetBlockStructureLineKind(); foreach (var info in lineColorInfos) { var props = editorFormatMap.GetProperties(info.Type); @@ -177,7 +177,7 @@ void UpdateColorInfos() { newPen = InitializePen(new Pen(scBrush, PEN_THICKNESS), lineKind); newPen.Freeze(); } - else if (!((newPen = props[MarkerFormatDefinition.BorderId] as Pen) is null)) { + else if ((newPen = props[MarkerFormatDefinition.BorderId] as Pen) is not null) { if (newPen.CanFreeze) newPen.Freeze(); } @@ -280,7 +280,7 @@ public int GetHashCode([DisallowNull] BlockStructureData obj) => void AddLineElements(NormalizedSnapshotSpanCollection spans) { if (spans.Count == 0) return; - Debug2.Assert(!(layer is null)); + Debug2.Assert(layer is not null); var list = new List(); var updated = new HashSet(BlockStructureDataComparer.Instance); foreach (var span in spans) { @@ -293,7 +293,7 @@ void AddLineElements(NormalizedSnapshotSpanCollection spans) { updated.Add(info); var lineElement = FindLineElement(info); - if (!(lineElement is null)) { + if (lineElement is not null) { layer.RemoveAdornment(lineElement); Debug.Assert(!lineElements.Contains(lineElement)); } @@ -547,7 +547,7 @@ void RegisterEvents() { void UnregisterEvents() { wpfTextView.LayoutChanged -= WpfTextView_LayoutChanged; - if (!(editorFormatMap is null)) + if (editorFormatMap is not null) editorFormatMap.FormatMappingChanged -= EditorFormatMap_FormatMappingChanged; } diff --git a/dnSpy/dnSpy/Text/Editor/CommonGuidObjectsProvider.cs b/dnSpy/dnSpy/Text/Editor/CommonGuidObjectsProvider.cs index 0f643bab23..eff4fb3ca8 100644 --- a/dnSpy/dnSpy/Text/Editor/CommonGuidObjectsProvider.cs +++ b/dnSpy/dnSpy/Text/Editor/CommonGuidObjectsProvider.cs @@ -37,12 +37,12 @@ public static Func> Create(Func } public IEnumerable GetGuidObjects(GuidObjectsProviderArgs args) { - if (!(createGuidObjects is null)) { + if (createGuidObjects is not null) { foreach (var guidObject in createGuidObjects(args)) yield return guidObject; } - if (!(guidObjectsProvider is null)) { + if (guidObjectsProvider is not null) { foreach (var guidObject in guidObjectsProvider.GetGuidObjects(args)) yield return guidObject; } diff --git a/dnSpy/dnSpy/Text/Editor/CurrentLineHighlighter.cs b/dnSpy/dnSpy/Text/Editor/CurrentLineHighlighter.cs index 3b9939332a..2c8ea83159 100644 --- a/dnSpy/dnSpy/Text/Editor/CurrentLineHighlighter.cs +++ b/dnSpy/dnSpy/Text/Editor/CurrentLineHighlighter.cs @@ -137,7 +137,7 @@ void PositionLineElement() { adornmentLayer?.RemoveAllAdornments(); return; } - Debug2.Assert(!(adornmentLayer is null)); + Debug2.Assert(adornmentLayer is not null); var line = wpfTextView.Caret.ContainingTextViewLine; if (line.IsVisible()) { @@ -235,7 +235,7 @@ public void SetLine(ITextViewLine line, double width) { if (line is null) throw new ArgumentNullException(nameof(line)); var newRect = new Rect(PEN_THICKNESS / 2, PEN_THICKNESS / 2, Math.Max(0, width - PEN_THICKNESS), Math.Max(0, line.TextHeight + WpfTextViewLine.DEFAULT_BOTTOM_SPACE - PEN_THICKNESS)); - if (!(geometry is null) && newRect == geometryRect) + if (geometry is not null && newRect == geometryRect) return; geometryRect = newRect; if (geometryRect.Height == 0 || geometryRect.Width == 0) @@ -250,7 +250,7 @@ public void SetLine(ITextViewLine line, double width) { protected override void OnRender(DrawingContext drawingContext) { base.OnRender(drawingContext); - if (!(geometry is null)) + if (geometry is not null) drawingContext.DrawGeometry(BackgroundBrush, pen, geometry); } } diff --git a/dnSpy/dnSpy/Text/Editor/CustomLineNumberMargin.cs b/dnSpy/dnSpy/Text/Editor/CustomLineNumberMargin.cs index 21c4efc8d9..9048dd1afc 100644 --- a/dnSpy/dnSpy/Text/Editor/CustomLineNumberMargin.cs +++ b/dnSpy/dnSpy/Text/Editor/CustomLineNumberMargin.cs @@ -57,7 +57,7 @@ public CustomLineNumberMarginImpl(IWpfTextViewHost wpfTextViewHost, IClassificat : base(PredefinedDsMarginNames.CustomLineNumber, wpfTextViewHost, classificationFormatMapService, textFormatterProvider) => CustomLineNumberMargin.SetMargin(wpfTextViewHost.TextView, this); void ICustomLineNumberMargin.SetOwner(ICustomLineNumberMarginOwner owner) { - if (!(this.owner is null)) + if (this.owner is not null) throw new InvalidOperationException(); this.owner = owner ?? throw new ArgumentNullException(nameof(owner)); if (Visibility == Visibility.Visible) @@ -85,13 +85,13 @@ sealed class CustomLineNumberState : LineNumberState { } protected override int? GetMaxLineDigitsCore() { - Debug2.Assert(!(owner is null)); + Debug2.Assert(owner is not null); return owner?.GetMaxLineNumberDigits(); } protected override TextFormattingRunProperties GetLineNumberTextFormattingRunProperties(ITextViewLine viewLine, LineNumberState state, int lineNumber) { - Debug2.Assert(!(owner is null)); - Debug2.Assert(!(state is null)); + Debug2.Assert(owner is not null); + Debug2.Assert(state is not null); if (owner is null) throw new InvalidOperationException(); var customState = (CustomLineNumberState)state; diff --git a/dnSpy/dnSpy/Text/Editor/DefaultTextViewCommandTarget.cs b/dnSpy/dnSpy/Text/Editor/DefaultTextViewCommandTarget.cs index 348981ea7b..8459aa38b9 100644 --- a/dnSpy/dnSpy/Text/Editor/DefaultTextViewCommandTarget.cs +++ b/dnSpy/dnSpy/Text/Editor/DefaultTextViewCommandTarget.cs @@ -362,7 +362,7 @@ public CommandTargetStatus Execute(Guid group, int cmdId, object? args, ref obje else if (group == CommandConstants.TextEditorGroup) { switch ((TextEditorIds)cmdId) { case TextEditorIds.BACKSPACE: - if (!(EditorOperations.ProvisionalCompositionSpan is null)) + if (EditorOperations.ProvisionalCompositionSpan is not null) EditorOperations.InsertText(string.Empty); else EditorOperations.Backspace(); diff --git a/dnSpy/dnSpy/Text/Editor/DefaultTextViewMouseProcessor.cs b/dnSpy/dnSpy/Text/Editor/DefaultTextViewMouseProcessor.cs index e8feb46730..bfbf700d01 100644 --- a/dnSpy/dnSpy/Text/Editor/DefaultTextViewMouseProcessor.cs +++ b/dnSpy/dnSpy/Text/Editor/DefaultTextViewMouseProcessor.cs @@ -182,11 +182,11 @@ void GetSelectionOrCaretIfNoSelection(out VirtualSnapshotPoint start, out Virtua public override void OnMouseMove(object? sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { - if (!(mouseLeftDownInfo is null) && !mouseLeftDownInfo.Value.TryAdvanceVersion(wpfTextView.TextSnapshot.Version)) { + if (mouseLeftDownInfo is not null && !mouseLeftDownInfo.Value.TryAdvanceVersion(wpfTextView.TextSnapshot.Version)) { CancelMouseLeftButtonSelection(); return; } - if (!mouseCaptured && !(mouseLeftDownInfo is null)) { + if (!mouseCaptured && mouseLeftDownInfo is not null) { var mouseLoc = GetLocation(e); var dist = mouseLeftDownInfo.Value.Point - mouseLoc.Point; bool movedEnough = Math.Abs(dist.X) >= SystemParameters.MinimumHorizontalDragDistance || @@ -199,7 +199,7 @@ public override void OnMouseMove(object? sender, MouseEventArgs e) { } else if (mouseCaptured) { e.Handled = true; - Debug2.Assert(!(mouseLeftDownInfo is null)); + Debug2.Assert(mouseLeftDownInfo is not null); if (mouseLeftDownInfo is null) StopScrolling(); else if (mouseLeftDownInfo.Value.Clicks == 2 || mouseLeftDownInfo.Value.Clicks == 3) { @@ -260,7 +260,7 @@ void UpdateScrolling(MouseEventArgs e) { return; } - if (!(dispatcherTimer is null)) { + if (dispatcherTimer is not null) { // It resets the timer if we write a new value, even if it's identical to the original value if (dispatcherTimer.Interval != interval) dispatcherTimer.Interval = interval; diff --git a/dnSpy/dnSpy/Text/Editor/DsScrollBar.cs b/dnSpy/dnSpy/Text/Editor/DsScrollBar.cs index 3bb3a0c1d9..1f5a02aac5 100644 --- a/dnSpy/dnSpy/Text/Editor/DsScrollBar.cs +++ b/dnSpy/dnSpy/Text/Editor/DsScrollBar.cs @@ -53,7 +53,7 @@ protected override void OnContextMenuOpening(ContextMenuEventArgs e) { ClearValue(ContextMenuProperty); base.OnContextMenuOpening(e); var ctxMenu = ContextMenu; - if (!(ctxMenu is null)) { + if (ctxMenu is not null) { if (IsEnabled) { ctxMenu.PlacementTarget = this; ctxMenu.IsOpen = true; diff --git a/dnSpy/dnSpy/Text/Editor/EditorOptions.cs b/dnSpy/dnSpy/Text/Editor/EditorOptions.cs index 64fdaf5ad7..da7b70fb97 100644 --- a/dnSpy/dnSpy/Text/Editor/EditorOptions.cs +++ b/dnSpy/dnSpy/Text/Editor/EditorOptions.cs @@ -67,7 +67,7 @@ public EditorOptions(EditorOptionsFactoryService service, EditorOptions? parent, } void UpdateOptions(EditorOptions? oldParent) { - if (!(oldParent is null)) { + if (oldParent is not null) { for (int i = 0; i < oldParent.weakChildren.Count; i++) { if (oldParent.weakChildren[i].Target == this) { oldParent.weakChildren.RemoveAt(i); @@ -75,10 +75,10 @@ void UpdateOptions(EditorOptions? oldParent) { } } } - if (!(parent is null)) + if (parent is not null) parent.weakChildren.Add(new WeakReference(this)); - if (!(parent is null) || !(oldParent is null)) { + if (parent is not null || oldParent is not null) { foreach (var o in SupportedOptions) { if (dict.ContainsKey(o.Name)) continue; @@ -91,10 +91,10 @@ void UpdateOptions(EditorOptions? oldParent) { } bool TryGetValue(string optionId, out object? value) { - if (!(scope is null) && !service.GetOption(optionId).IsApplicableToScope(scope)) + if (scope is not null && !service.GetOption(optionId).IsApplicableToScope(scope)) throw new InvalidOperationException(); EditorOptions? p = this; - while (!(p is null)) { + while (p is not null) { if (p.dict.TryGetValue(optionId, out value)) return true; p = p.parent; @@ -127,7 +127,7 @@ void OnChanged(string optionId) { public bool IsOptionDefined(string optionId, bool localScopeOnly) { if (optionId is null) throw new ArgumentNullException(nameof(optionId)); - if (!(parent is null) && localScopeOnly) + if (parent is not null && localScopeOnly) return dict.ContainsKey(optionId); var def = service.GetOption(optionId); return scope is null || def.IsApplicableToScope(scope); @@ -159,7 +159,7 @@ public void SetOptionValue(string optionId, object? value) { if (optionId is null) throw new ArgumentNullException(nameof(optionId)); var def = service.GetOption(optionId); - if (!(scope is null) && !def.IsApplicableToScope(scope)) + if (scope is not null && !def.IsApplicableToScope(scope)) throw new InvalidOperationException(); if (!def.IsValid(ref value)) throw new ArgumentException(); diff --git a/dnSpy/dnSpy/Text/Editor/GlyphMargin.cs b/dnSpy/dnSpy/Text/Editor/GlyphMargin.cs index dfb5a65866..62bed3bf29 100644 --- a/dnSpy/dnSpy/Text/Editor/GlyphMargin.cs +++ b/dnSpy/dnSpy/Text/Editor/GlyphMargin.cs @@ -192,7 +192,7 @@ IMouseProcessor[] CreateMouseProcessors() { } void InitializeGlyphFactories(IContentType? beforeContentType, IContentType afterContentType) { - Debug2.Assert(!(iconCanvas is null)); + Debug2.Assert(iconCanvas is not null); var oldFactories = new Dictionary(); foreach (var info in glyphFactories.Values) oldFactories[info.FactoryProvider] = info.Factory; @@ -205,7 +205,7 @@ void InitializeGlyphFactories(IContentType? beforeContentType, IContentType afte continue; IGlyphFactory? glyphFactory = null; foreach (var type in lazy.Metadata.TagTypes) { - Debug2.Assert(!(type is null)); + Debug2.Assert(type is not null); if (type is null) break; Debug.Assert(!glyphFactories.ContainsKey(type)); @@ -238,13 +238,13 @@ void InitializeGlyphFactories(IContentType? beforeContentType, IContentType afte foreach (var c in childCanvases) iconCanvas.Children.Add(c); - if (!(beforeContentType is null)) + if (beforeContentType is not null) RefreshEverything(); } } void Initialize() { - if (!(mouseProcessorCollection is null)) + if (mouseProcessorCollection is not null) return; iconCanvas = new Canvas { Background = Brushes.Transparent }; Children.Add(iconCanvas); @@ -289,7 +289,7 @@ void TextView_LayoutChanged(object? sender, TextViewLayoutChangedEventArgs e) { } void OnNewLayout(IList newOrReformattedLines, IList translatedLines) { - Debug2.Assert(!(lineInfos is null)); + Debug2.Assert(lineInfos is not null); var newInfos = new Dictionary(); foreach (var line in newOrReformattedLines) @@ -324,7 +324,7 @@ void OnNewLayout(IList newOrReformattedLines, IList newInfos, ITextViewLine line) { var wpfLine = line as IWpfTextViewLine; - Debug2.Assert(!(wpfLine is null)); + Debug2.Assert(wpfLine is not null); if (wpfLine is null) return; var info = new LineInfo(line, CreateIconInfos(wpfLine)); @@ -334,11 +334,11 @@ void AddLine(Dictionary newInfos, ITextViewLine line) { } List CreateIconInfos(IWpfTextViewLine line) { - Debug2.Assert(!(tagAggregator is null)); + Debug2.Assert(tagAggregator is not null); var icons = new List(); foreach (var mappingSpan in tagAggregator.GetTags(line.ExtentAsMappingSpan)) { var tag = mappingSpan.Tag; - Debug2.Assert(!(tag is null)); + Debug2.Assert(tag is not null); if (tag is null) continue; // Fails if someone forgot to Export(typeof(IGlyphFactoryProvider)) with the correct tag types @@ -395,7 +395,7 @@ void Update(SnapshotSpan span, ref HashSet? checkedLines) { } void Update(IWpfTextViewLine line) { - Debug2.Assert(!(lineInfos is null)); + Debug2.Assert(lineInfos is not null); Debug.Assert(line.VisibilityState != VisibilityState.Unattached); if (!lineInfos.TryGetValue(line.IdentityTag, out var info)) return; @@ -437,9 +437,9 @@ void RegisterEvents() { void UnregisterEvents() { hasRegisteredEvents = false; - if (!(editorFormatMap is null)) + if (editorFormatMap is not null) editorFormatMap.FormatMappingChanged -= EditorFormatMap_FormatMappingChanged; - if (!(tagAggregator is null)) + if (tagAggregator is not null) tagAggregator.BatchedTagsChanged -= TagAggregator_BatchedTagsChanged; wpfTextViewHost.TextView.LayoutChanged -= TextView_LayoutChanged; } diff --git a/dnSpy/dnSpy/Text/Editor/GlyphTextMarkerService.cs b/dnSpy/dnSpy/Text/Editor/GlyphTextMarkerService.cs index e6989c9746..b16a58304e 100644 --- a/dnSpy/dnSpy/Text/Editor/GlyphTextMarkerService.cs +++ b/dnSpy/dnSpy/Text/Editor/GlyphTextMarkerService.cs @@ -205,7 +205,7 @@ public void SetDotNetSpanMap(ITextView textView, IDotNetSpanMap? map) { if (textView is null) throw new ArgumentNullException(nameof(textView)); var service = GlyphTextViewMarkerService.TryGet(textView); - Debug2.Assert(!(service is null)); + Debug2.Assert(service is not null); service?.SetDotNetSpanMap(map); } } diff --git a/dnSpy/dnSpy/Text/Editor/GlyphTextMarkerServiceMouseProcessor.cs b/dnSpy/dnSpy/Text/Editor/GlyphTextMarkerServiceMouseProcessor.cs index 6444be6ac9..f44c0d6b24 100644 --- a/dnSpy/dnSpy/Text/Editor/GlyphTextMarkerServiceMouseProcessor.cs +++ b/dnSpy/dnSpy/Text/Editor/GlyphTextMarkerServiceMouseProcessor.cs @@ -86,10 +86,10 @@ public GlyphTextMarkerServiceMouseProcessor(IGlyphTextMarkerServiceImpl glyphTex var list = new List(); foreach (var lazy in glyphTextMarkerServiceImpl.GlyphTextMarkerMouseProcessorProviders) { - if (!(lazy.Metadata.TextViewRoles is null) && !wpfTextViewHost.TextView.Roles.ContainsAny(lazy.Metadata.TextViewRoles)) + if (lazy.Metadata.TextViewRoles is not null && !wpfTextViewHost.TextView.Roles.ContainsAny(lazy.Metadata.TextViewRoles)) continue; var mouseProcessor = lazy.Value.GetAssociatedMouseProcessor(wpfTextViewHost, margin); - if (!(mouseProcessor is null)) + if (mouseProcessor is not null) list.Add(mouseProcessor); } glyphTextMarkerMouseProcessors = list.ToArray(); @@ -108,7 +108,7 @@ public GlyphTextMarkerServiceMouseProcessor(IGlyphTextMarkerServiceImpl glyphTex return null; var line = wpfTextViewHost.TextView.TextViewLines.GetTextViewLineContainingYCoordinate(point.Y + wpfTextViewHost.TextView.ViewportTop); var wpfLine = line as IWpfTextViewLine; - Debug2.Assert((!(line is null)) == (!(wpfLine is null))); + Debug2.Assert((line is not null) == (wpfLine is not null)); if (wpfLine is null || !wpfLine.IsVisible()) return null; return wpfLine; @@ -429,7 +429,7 @@ void ClosePopup() { } void CloseToolTip(bool clearLine = true) { - if (!(toolTip is null)) + if (toolTip is not null) toolTip.IsOpen = false; toolTip = null; toolTipMarker = null; @@ -452,7 +452,7 @@ void ToolTipDispatcherTimer_Tick(object? sender, EventArgs e) { return; } CloseToolTip(false); - Debug2.Assert(!(toolTipLine is null)); + Debug2.Assert(toolTipLine is not null); UpdateToolTipContent(toolTipLine); UpdatePopupContent(toolTipLine); @@ -464,7 +464,7 @@ void UpdateToolTipContent(IWpfTextViewLine line) { if (glyphTextMarkerHandlerContext is null) glyphTextMarkerHandlerContext = new GlyphTextMarkerHandlerContext(wpfTextViewHost, margin, line, this); var toolTipInfo = marker.Handler.GetToolTipContent(glyphTextMarkerHandlerContext, marker); - if (!(toolTipInfo is null)) { + if (toolTipInfo is not null) { Debug2.Assert(toolTip is null); toolTipMarker = marker; toolTip = new ToolTip(); @@ -500,7 +500,7 @@ void UpdatePopupContent(IWpfTextViewLine line) { if (glyphTextMarkerHandlerContext is null) glyphTextMarkerHandlerContext = new GlyphTextMarkerHandlerContext(wpfTextViewHost, margin, line, this); var popupContent = marker.Handler.GetPopupContent(glyphTextMarkerHandlerContext, marker); - if (!(popupContent is null)) { + if (popupContent is not null) { AddPopupContent(line, marker, popupContent); return; } @@ -527,7 +527,7 @@ void AddPopupContent(IWpfTextViewLine line, IGlyphTextMarker marker, FrameworkEl } void TextView_LayoutChanged(object? sender, TextViewLayoutChangedEventArgs e) { - bool refresh = !(toolTipLine is null) || popup.IsOpen; + bool refresh = toolTipLine is not null || popup.IsOpen; if (popup.IsOpen) { if (e.OldSnapshot != e.NewSnapshot) ClosePopup(); diff --git a/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerClassificationTagger.cs b/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerClassificationTagger.cs index 2a041fc98b..74bf94fc7e 100644 --- a/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerClassificationTagger.cs +++ b/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerClassificationTagger.cs @@ -42,7 +42,7 @@ sealed class GlyphTextViewMarkerClassificationTaggerProvider : IViewTaggerProvid public ITagger? CreateTagger(ITextView textView, ITextBuffer buffer) where T : ITag { var wpfTextView = textView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); + Debug2.Assert(wpfTextView is not null); if (wpfTextView is null) return null; if (textView.TextBuffer != buffer) diff --git a/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerGlyphTagger.cs b/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerGlyphTagger.cs index a55cdfe865..9df2b0db6e 100644 --- a/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerGlyphTagger.cs +++ b/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerGlyphTagger.cs @@ -44,7 +44,7 @@ sealed class GlyphTextViewMarkerGlyphTaggerProvider : IViewTaggerProvider { public ITagger? CreateTagger(ITextView textView, ITextBuffer buffer) where T : ITag { var wpfTextView = textView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); + Debug2.Assert(wpfTextView is not null); if (wpfTextView is null) return null; if (textView.TextBuffer != buffer) diff --git a/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerGlyphTextMarkerTagger.cs b/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerGlyphTextMarkerTagger.cs index cf2f5701e8..2f94174bab 100644 --- a/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerGlyphTextMarkerTagger.cs +++ b/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerGlyphTextMarkerTagger.cs @@ -42,7 +42,7 @@ sealed class GlyphTextViewMarkerGlyphTextMarkerTaggerProvider : IViewTaggerProvi public ITagger? CreateTagger(ITextView textView, ITextBuffer buffer) where T : ITag { var wpfTextView = textView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); + Debug2.Assert(wpfTextView is not null); if (wpfTextView is null) return null; if (textView.TextBuffer != buffer) diff --git a/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerService.cs b/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerService.cs index 8f37dd9f2f..8d1a34ec62 100644 --- a/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerService.cs +++ b/dnSpy/dnSpy/Text/Editor/GlyphTextViewMarkerService.cs @@ -94,25 +94,25 @@ public MarkerAndSpanCollection(GlyphTextViewMarkerService owner) { public void UpdateSpans(IDotNetSpanMap? map) { inDocMarkers.Clear(); SelectedMarkersInDocumentCount = 0; - if (!(map is null)) { + if (map is not null) { var allMarkers = this.allMarkers; for (int i = 0; i < allMarkers.Count; i++) { Span? span; switch (allMarkers[i]) { case IGlyphTextMethodMarkerImpl methodMarker: span = map.ToSpan(methodMarker.Method.Module, methodMarker.Method.Token, methodMarker.ILOffset); - if (!(span is null)) { + if (span is not null) { inDocMarkers.Add(methodMarker, span.Value); - if (!(methodMarker.SelectedMarkerTypeName is null)) + if (methodMarker.SelectedMarkerTypeName is not null) SelectedMarkersInDocumentCount++; } break; case IGlyphTextDotNetTokenMarkerImpl tokenMarker: span = map.ToSpan(tokenMarker.Module, tokenMarker.Token); - if (!(span is null)) { + if (span is not null) { inDocMarkers.Add(tokenMarker, span.Value); - if (!(tokenMarker.SelectedMarkerTypeName is null)) + if (tokenMarker.SelectedMarkerTypeName is not null) SelectedMarkersInDocumentCount++; } break; @@ -135,9 +135,9 @@ public IEnumerable GetMarkerAndSpans(ITextSnapshot snapshot, Span public void Add(IGlyphTextMarkerImpl marker, Span? span) { allMarkers.Add(marker); - if (!(span is null)) { + if (span is not null) { inDocMarkers.Add(marker, span.Value); - if (!(marker.SelectedMarkerTypeName is null)) + if (marker.SelectedMarkerTypeName is not null) SelectedMarkersInDocumentCount++; } } @@ -147,7 +147,7 @@ public bool Remove(IGlyphTextMarkerImpl marker) { if (allMarkers[i] == marker) { allMarkers.RemoveAt(i); if (inDocMarkers.Remove(marker)) { - if (!(marker.SelectedMarkerTypeName is null)) + if (marker.SelectedMarkerTypeName is not null) SelectedMarkersInDocumentCount--; } return true; @@ -163,7 +163,7 @@ public bool Remove(HashSet markers) { if (markers.Contains(marker)) { allMarkers.RemoveAt(i); if (inDocMarkers.Remove(marker)) { - if (!(marker.SelectedMarkerTypeName is null)) + if (marker.SelectedMarkerTypeName is not null) SelectedMarkersInDocumentCount--; } removed++; @@ -244,14 +244,14 @@ void Caret_PositionChanged(object? sender, CaretPositionChangedEventArgs e) { Debug.Assert(markerAndSpanCollection.SelectedMarkersInDocumentCount > 0); var oldMarkers = GetMarkers(e.OldPosition.VirtualBufferPosition); var newMarkers = GetMarkers(e.NewPosition.VirtualBufferPosition); - if (!(oldMarkers is null)) { + if (oldMarkers is not null) { foreach (var marker in oldMarkers) { if (ExistsIn(newMarkers, marker)) continue; Refresh(marker); } } - if (!(newMarkers is null)) { + if (newMarkers is not null) { foreach (var marker in newMarkers) { if (ExistsIn(oldMarkers, marker)) continue; @@ -299,7 +299,7 @@ void Initialize() { bool glyphTextMarkerTagAggregatorWasNull; internal void AddGlyphTextMarkerListener(IGlyphTextMarkerListener listener) { - if (!(glyphTextMarkerListener is null)) + if (glyphTextMarkerListener is not null) throw new InvalidOperationException("Only one instance is supported"); glyphTextMarkerListener = listener ?? throw new ArgumentNullException(nameof(listener)); } @@ -374,7 +374,7 @@ void EditorFormatMap_FormatMappingChanged(object? sender, FormatItemsEventArgs e var hash = new HashSet(StringComparer.Ordinal); foreach (var elem in markerElements) { hash.Add(elem.Type); - if (!(elem.SelectedType is null)) + if (elem.SelectedType is not null) hash.Add(elem.SelectedType); } foreach (var s in e.ChangedItems) { @@ -405,14 +405,14 @@ void GlyphTextMarkerTagAggregator_BatchedTagsChanged(object? sender, BatchedTags foreach (var mappingSpan in e.Spans) { foreach (var span in mappingSpan.GetSpans(TextView.TextSnapshot)) { var intersection = TextView.TextViewLines.FormattedSpan.Intersection(span); - if (!(intersection is null)) { + if (intersection is not null) { if (intersectionSpans is null) intersectionSpans = new List(); intersectionSpans.Add(intersection.Value); } } } - if (!(intersectionSpans is null)) + if (intersectionSpans is not null) UpdateRange(new NormalizedSnapshotSpanCollection(intersectionSpans)); } @@ -425,7 +425,7 @@ void RemoveMarkerElements(NormalizedSnapshotSpanCollection spans) { } void AddMarkerElements(NormalizedSnapshotSpanCollection spans) { - Debug2.Assert(!(glyphTextMarkerTagAggregator is null)); + Debug2.Assert(glyphTextMarkerTagAggregator is not null); if (glyphTextMarkerTagAggregator is null) { glyphTextMarkerTagAggregatorWasNull = true; return; @@ -512,7 +512,7 @@ void RemoveAllMarkerElements() { newPen = new Pen(scBrush, PEN_THICKNESS); newPen.Freeze(); } - else if (!((newPen = props[MarkerFormatDefinition.BorderId] as Pen) is null)) { + else if ((newPen = props[MarkerFormatDefinition.BorderId] as Pen) is not null) { if (newPen.CanFreeze) newPen.Freeze(); } @@ -521,14 +521,14 @@ void RemoveAllMarkerElements() { } MarkerElement? TryCreateMarkerElement(SnapshotSpan span, IGlyphTextMarkerTag tag) { - Debug2.Assert(!(tag.MarkerTypeName is null)); + Debug2.Assert(tag.MarkerTypeName is not null); var geo = TextView.TextViewLines.GetMarkerGeometry(span); if (geo is null) return null; var type = tag.MarkerTypeName ?? string.Empty; var selectedType = tag.SelectedMarkerTypeName; - var propName = (!(selectedType is null) && IsSelected(span) ? selectedType : type) ?? type; + var propName = (selectedType is not null && IsSelected(span) ? selectedType : type) ?? type; var props = editorFormatMap.GetProperties(propName); var markerElement = new MarkerElement(span, propName, type, selectedType, tag.ZIndex, geo); markerElement.BackgroundBrush = GetBackgroundBrush(props); @@ -606,11 +606,11 @@ void Refresh(IGlyphTextMarkerImpl marker) { void Refresh(IGlyphTextMarker marker, SnapshotSpan span) { bool visible = TextView.TextViewLines.FormattedSpan.IntersectsWith(span); - if (visible && !(marker.GlyphImageReference is null)) + if (visible && marker.GlyphImageReference is not null) glyphTextViewMarkerGlyphTagTagger.RaiseTagsChanged(span); - if (!(marker.ClassificationType is null)) + if (marker.ClassificationType is not null) glyphTextViewMarkerClassificationTagTagger.RaiseTagsChanged(span); - if (visible && !(marker.MarkerTypeName is null)) + if (visible && marker.MarkerTypeName is not null) glyphTextViewMarkerGlyphTextMarkerTagTagger.RaiseTagsChanged(span); } @@ -766,7 +766,7 @@ IEnumerable GetMarkers(NormalizedSnapshotSpanCollection spans, bo public IEnumerable> GetClassificationTags(NormalizedSnapshotSpanCollection spans) { foreach (var info in GetMarkers(spans, startOfSpanOnly: false)) { var ct = info.Marker.ClassificationType; - if (!(ct is null)) + if (ct is not null) yield return new TagSpan(info.Span, new ClassificationTag(ct)); } } @@ -774,7 +774,7 @@ public IEnumerable> GetClassificationTags(Normalize public IEnumerable> GetGlyphTextMarkerGlyphTags(NormalizedSnapshotSpanCollection spans) { foreach (var info in GetMarkers(spans, startOfSpanOnly: true)) { var imgRef = info.Marker.GlyphImageReference; - if (!(imgRef is null)) + if (imgRef is not null) yield return new TagSpan(info.Span, new GlyphTextMarkerGlyphTag(imgRef.Value, info.Marker.ZIndex)); } } @@ -782,7 +782,7 @@ public IEnumerable> GetGlyphTextMarkerGlyphTag public IEnumerable> GetGlyphTextMarkerTags(NormalizedSnapshotSpanCollection spans) { foreach (var info in GetMarkers(spans, startOfSpanOnly: false)) { var markerTypeName = info.Marker.MarkerTypeName; - if (!(markerTypeName is null)) + if (markerTypeName is not null) yield return new TagSpan(info.Span, new GlyphTextMarkerTag(markerTypeName, info.Marker.SelectedMarkerTypeName, info.Marker.ZIndex)); } } @@ -798,7 +798,7 @@ internal IGlyphTextMarkerImpl[] GetSortedGlyphTextMarkers(IWpfTextViewLine line) markers.Add(info.Marker); } } - if (!(markers is null)) { + if (markers is not null) { if (markers.Count == 1) return new[] { markers[0] }; return markers.OrderByDescending(a => a.ZIndex).ToArray(); @@ -829,7 +829,7 @@ internal SnapshotSpan GetSpan(IGlyphTextMarker marker) { return null; var line = TextView.TextViewLines.GetTextViewLineContainingBufferPosition(span.Value.Start); var wpfLine = line as IWpfTextViewLine; - Debug2.Assert((!(line is null)) == (!(wpfLine is null))); + Debug2.Assert((line is not null) == (wpfLine is not null)); if (wpfLine is null || !wpfLine.IsVisible()) return null; return wpfLine; @@ -845,8 +845,8 @@ void WpfTextView_Closed(object? sender, EventArgs e) { glyphTextMarkerServiceImpl.MarkersRemoved -= GlyphTextMarkerServiceImpl_MarkersRemoved; glyphTextMarkerServiceImpl.GetGlyphTextMarkerAndSpan -= GlyphTextMarkerServiceImpl_GetGlyphTextMarkerAndSpan; editorFormatMap.FormatMappingChanged -= EditorFormatMap_FormatMappingChanged; - Debug2.Assert(!(glyphTextMarkerTagAggregator is null)); - if (!(glyphTextMarkerTagAggregator is null)) { + Debug2.Assert(glyphTextMarkerTagAggregator is not null); + if (glyphTextMarkerTagAggregator is not null) { glyphTextMarkerTagAggregator.BatchedTagsChanged -= GlyphTextMarkerTagAggregator_BatchedTagsChanged; glyphTextMarkerTagAggregator.Dispose(); } diff --git a/dnSpy/dnSpy/Text/Editor/GoToCommand.cs b/dnSpy/dnSpy/Text/Editor/GoToCommand.cs index 552fff207f..dd7cda0896 100644 --- a/dnSpy/dnSpy/Text/Editor/GoToCommand.cs +++ b/dnSpy/dnSpy/Text/Editor/GoToCommand.cs @@ -102,7 +102,7 @@ bool GetLineColumn(out int chosenLine, out int? chosenColumn) { var viewLine = textView.Caret.ContainingTextViewLine; var snapshotLine = viewLine.Start.GetContainingLine(); var wpfTextView = textView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); + Debug2.Assert(wpfTextView is not null); var ownerWindow = wpfTextView is null ? null : Window.GetWindow(wpfTextView.VisualElement); int maxLines = snapshotLine.Snapshot.LineCount; @@ -128,14 +128,14 @@ string TryGetRowCol(string s, int currentLine, int maxLines, out int? line, out column = null; bool columnError = false; Match match; - if (!((match = goToLineRegex1.Match(s)) is null) && match.Groups.Count == 4) { + if ((match = goToLineRegex1.Match(s)) is not null && match.Groups.Count == 4) { TryParseOneBasedToZeroBased(match.Groups[1].Value, out line); - if (!(line is null) && line.Value >= maxLines) + if (line is not null && line.Value >= maxLines) line = null; if (match.Groups[3].Value != string.Empty) columnError = !TryParseOneBasedToZeroBased(match.Groups[3].Value, out column); } - else if (!((match = goToLineRegex2.Match(s)) is null) && match.Groups.Count == 2) { + else if ((match = goToLineRegex2.Match(s)) is not null && match.Groups.Count == 2) { line = currentLine; columnError = !TryParseOneBasedToZeroBased(match.Groups[1].Value, out column); } diff --git a/dnSpy/dnSpy/Text/Editor/IntraTextAdornmentService.cs b/dnSpy/dnSpy/Text/Editor/IntraTextAdornmentService.cs index 7e88ac254d..f74c395f7d 100644 --- a/dnSpy/dnSpy/Text/Editor/IntraTextAdornmentService.cs +++ b/dnSpy/dnSpy/Text/Editor/IntraTextAdornmentService.cs @@ -46,7 +46,7 @@ sealed class IntraTextAdornmentServiceSpaceNegotiatingAdornmentTaggerProvider : if (textView.TextBuffer != buffer) return null; var wpfTextView = textView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); + Debug2.Assert(wpfTextView is not null); if (wpfTextView is null) return null; return wpfTextView.Properties.GetOrCreateSingletonProperty( @@ -146,7 +146,7 @@ void UpdateIsSelected(AdornmentTagInfo adornmentInfo, ITextViewLine? line) { if (line is null) line = wpfTextView.TextViewLines.GetTextViewLineContainingBufferPosition(adornmentInfo.Span.Start); var selSpan = line is null ? null : wpfTextView.Selection.GetSelectionOnTextViewLine(line); - bool selected = !(selSpan is null) && selSpan.Value.Contains(new VirtualSnapshotSpan(adornmentInfo.Span)); + bool selected = selSpan is not null && selSpan.Value.Contains(new VirtualSnapshotSpan(adornmentInfo.Span)); IntraTextAdornment.SetIsSelected(adornmentInfo.UserUIElement, selected); } @@ -174,7 +174,7 @@ public void Initialize() { void WpfTextView_LayoutChanged(object? sender, TextViewLayoutChangedEventArgs e) { if (adornmentTagInfos.Count > 0) { - Debug2.Assert(!(layer is null)); + Debug2.Assert(layer is not null); currentLineIdentityTags.Clear(); foreach (var line in wpfTextView.TextViewLines) currentLineIdentityTags.Add(line.IdentityTag); @@ -194,11 +194,11 @@ void WpfTextView_LayoutChanged(object? sender, TextViewLayoutChangedEventArgs e) foreach (var identityTag in tags) { var adornmentInfo = identityTag as AdornmentTagInfo; - Debug2.Assert(!(adornmentInfo is null)); + Debug2.Assert(adornmentInfo is not null); if (adornmentInfo is null) continue; var bounds = line.GetAdornmentBounds(identityTag); - Debug2.Assert(!(bounds is null)); + Debug2.Assert(bounds is not null); if (bounds is null) continue; @@ -215,7 +215,7 @@ void WpfTextView_LayoutChanged(object? sender, TextViewLayoutChangedEventArgs e) foreach (var identityTag in tags) { var adornmentInfo = identityTag as AdornmentTagInfo; - Debug2.Assert(!(adornmentInfo is null)); + Debug2.Assert(adornmentInfo is not null); if (adornmentInfo is null) continue; var bounds = line.GetAdornmentBounds(identityTag); @@ -240,7 +240,7 @@ void WpfTextView_LayoutChanged(object? sender, TextViewLayoutChangedEventArgs e) } void UpdateAdornmentUIState(ITextViewLine line, AdornmentTagInfo adornmentInfo, TextBounds bounds) { - Debug2.Assert(!(adornmentInfo.TopUIElement is null)); + Debug2.Assert(adornmentInfo.TopUIElement is not null); double verticalScale = line.LineTransform.VerticalScale; adornmentInfo.TopUIElement.SetScale(verticalScale); Canvas.SetTop(adornmentInfo.TopUIElement, bounds.TextTop + line.Baseline - verticalScale * adornmentInfo.Tag!.Baseline); @@ -248,8 +248,8 @@ void UpdateAdornmentUIState(ITextViewLine line, AdornmentTagInfo adornmentInfo, } bool AddAdornment(AdornmentTagInfo adornmentInfo, ITextViewLine line) { - Debug2.Assert(!(adornmentInfo.TopUIElement is null)); - Debug2.Assert(!(layer is null)); + Debug2.Assert(adornmentInfo.TopUIElement is not null); + Debug2.Assert(layer is not null); SizeChangedEventHandler sizeChanged = (a, e) => { var bounds = line.GetAdornmentBounds(adornmentInfo); if (bounds is null) @@ -290,7 +290,7 @@ public void SetScale(double value) => } public void RegisterTagger(IIntraTextAdornmentServiceSpaceNegotiatingAdornmentTagger tagger) { - if (!(this.tagger is null)) + if (this.tagger is not null) throw new InvalidOperationException(); this.tagger = tagger ?? throw new ArgumentNullException(nameof(tagger)); } diff --git a/dnSpy/dnSpy/Text/Editor/KeyProcessorCollection.cs b/dnSpy/dnSpy/Text/Editor/KeyProcessorCollection.cs index 04fa263a4c..f3c2b884ab 100644 --- a/dnSpy/dnSpy/Text/Editor/KeyProcessorCollection.cs +++ b/dnSpy/dnSpy/Text/Editor/KeyProcessorCollection.cs @@ -145,7 +145,7 @@ void Reinitialize() { if (!wpfTextView.TextDataModel.ContentType.IsOfAnyType(provider.Metadata.ContentTypes)) continue; var keyProcessor = provider.Value.GetAssociatedProcessor(wpfTextView); - if (!(keyProcessor is null)) + if (keyProcessor is not null) list.Add(keyProcessor); } keyProcessors = list.ToArray(); diff --git a/dnSpy/dnSpy/Text/Editor/LineCompressor.cs b/dnSpy/dnSpy/Text/Editor/LineCompressor.cs index d0c9885ef7..200eb65a58 100644 --- a/dnSpy/dnSpy/Text/Editor/LineCompressor.cs +++ b/dnSpy/dnSpy/Text/Editor/LineCompressor.cs @@ -99,8 +99,8 @@ public LineTransform GetLineTransform(ITextViewLine line, double yPosition, View [MethodImpl(MethodImplOptions.AggressiveInlining)] LineKind GetLineType(ITextViewLine line) { var dsLine = line as IDsTextViewLine; - Debug2.Assert(!(dsLine is null)); - if (!(dsLine is null) && dsLine.HasAdornments) + Debug2.Assert(dsLine is not null); + if (dsLine is not null && dsLine.HasAdornments) return LineKind.Normal; if (line.Length == 0) return LineKind.EmptyOrWhitespace; diff --git a/dnSpy/dnSpy/Text/Editor/LineNumberMarginBase.cs b/dnSpy/dnSpy/Text/Editor/LineNumberMarginBase.cs index 4aa33f709c..8b2ed1434f 100644 --- a/dnSpy/dnSpy/Text/Editor/LineNumberMarginBase.cs +++ b/dnSpy/dnSpy/Text/Editor/LineNumberMarginBase.cs @@ -178,7 +178,7 @@ void UpdateLines(IList newOrReformattedLines, IList(); var lineStart = intersection.Value.Start.GetContainingLine(); @@ -206,7 +206,7 @@ void TagAggregator_BatchedTagsChanged(object? sender, BatchedTagsChangedEventArg } } } - if (!(intersectionSpans is null)) + if (intersectionSpans is not null) UpdateRange(new NormalizedSnapshotSpanCollection(intersectionSpans)); } @@ -236,8 +236,8 @@ void RemoveLineSeparatorElements(NormalizedSnapshotSpanCollection spans) { } void AddLineSeparatorElements(NormalizedSnapshotSpanCollection spans) { - Debug2.Assert(!(tagAggregator is null)); - Debug2.Assert(!(adornmentLayer is null)); + Debug2.Assert(tagAggregator is not null); + Debug2.Assert(adornmentLayer is not null); var textViewLines = wpfTextView.TextViewLines; // There's always at least one line in the collection Debug.Assert(textViewLines.Count > 0); @@ -312,7 +312,7 @@ void UpdateLines(IList newOrReformattedLines) { var lineSpans = new List(); ITextSnapshotLine? snapshotLine = null; foreach (var line in newOrReformattedLines) { - if (!(snapshotLine is null) && line.Start >= snapshotLine.Start && line.EndIncludingLineBreak <= snapshotLine.EndIncludingLineBreak) + if (snapshotLine is not null && line.Start >= snapshotLine.Start && line.EndIncludingLineBreak <= snapshotLine.EndIncludingLineBreak) continue; snapshotLine = line.Start.GetContainingLine(); lineSpans.Add(snapshotLine.Extent); @@ -322,7 +322,7 @@ void UpdateLines(IList newOrReformattedLines) { } void DisposeTagAggregator() { - if (!(tagAggregator is null)) { + if (tagAggregator is not null) { tagAggregator.BatchedTagsChanged -= TagAggregator_BatchedTagsChanged; tagAggregator.Dispose(); tagAggregator = null; @@ -334,7 +334,7 @@ void WpfTextView_Closed(object? sender, EventArgs e) { wpfTextView.Closed -= WpfTextView_Closed; wpfTextView.Options.OptionChanged -= Options_OptionChanged; wpfTextView.LayoutChanged -= WpfTextView_LayoutChanged; - if (!(editorFormatMap is null)) + if (editorFormatMap is not null) editorFormatMap.FormatMappingChanged -= EditorFormatMap_FormatMappingChanged; DisposeTagAggregator(); } diff --git a/dnSpy/dnSpy/Text/Editor/MarginContextMenuService.cs b/dnSpy/dnSpy/Text/Editor/MarginContextMenuService.cs index 7877171a38..79b669eac5 100644 --- a/dnSpy/dnSpy/Text/Editor/MarginContextMenuService.cs +++ b/dnSpy/dnSpy/Text/Editor/MarginContextMenuService.cs @@ -51,16 +51,16 @@ public GuidObjectsProvider(IWpfTextViewHost wpfTextViewHost, IWpfTextViewMargin } void InitializeHandlers() { - if (!(handlers is null)) + if (handlers is not null) return; var list = new List(marginContextMenuHandlerProviders.Length); foreach (var lazy in marginContextMenuHandlerProviders) { if (!StringComparer.OrdinalIgnoreCase.Equals(lazy.Metadata.MarginName, marginName)) continue; - if (!(lazy.Metadata.TextViewRoles is null) && !wpfTextViewHost.TextView.Roles.ContainsAny(lazy.Metadata.TextViewRoles)) + if (lazy.Metadata.TextViewRoles is not null && !wpfTextViewHost.TextView.Roles.ContainsAny(lazy.Metadata.TextViewRoles)) continue; var handler = lazy.Value.Create(wpfTextViewHost, margin); - if (!(handler is null)) + if (handler is not null) list.Add(handler); } handlers = list.ToArray(); @@ -69,7 +69,7 @@ void InitializeHandlers() { public IEnumerable GetGuidObjects(GuidObjectsProviderArgs args) { if (handlers is null) InitializeHandlers(); - Debug2.Assert(!(handlers is null)); + Debug2.Assert(handlers is not null); var point = Mouse.PrimaryDevice.GetPosition(margin.VisualElement); diff --git a/dnSpy/dnSpy/Text/Editor/MarkerHelper.cs b/dnSpy/dnSpy/Text/Editor/MarkerHelper.cs index 258c9c4fae..36de7882d7 100644 --- a/dnSpy/dnSpy/Text/Editor/MarkerHelper.cs +++ b/dnSpy/dnSpy/Text/Editor/MarkerHelper.cs @@ -49,8 +49,8 @@ public static bool IsMultiLineSpan(ITextView textView, SnapshotSpan bufferSpan) bool useVspaces = line.IsLastDocumentLine(); var lineExtent = new VirtualSnapshotSpan(new VirtualSnapshotPoint(line.Start), new VirtualSnapshotPoint(line.EndIncludingLineBreak, useVspaces ? span.End.VirtualSpaces : 0)); var extentTmp = lineExtent.Intersection(new VirtualSnapshotSpan(pos, span.End)); - Debug2.Assert(!(extentTmp is null)); - if (line.VisibilityState != VisibilityState.Unattached && !(extentTmp is null) && extentTmp.Value.Length != 0) { + Debug2.Assert(extentTmp is not null); + if (line.VisibilityState != VisibilityState.Unattached && extentTmp is not null && extentTmp.Value.Length != 0) { var extent = extentTmp.Value; Collection textBounds; if (extent.Start.IsInVirtualSpace) { @@ -78,7 +78,7 @@ public static bool IsMultiLineSpan(ITextView textView, SnapshotSpan bufferSpan) } if (createOutlinedPath) geo = geo!.GetOutlinedPathGeometry(); - if (!(geo is null) && geo.CanFreeze) + if (geo is not null && geo.CanFreeze) geo.Freeze(); return geo; } @@ -93,8 +93,8 @@ public static bool IsMultiLineSpan(ITextView textView, SnapshotSpan bufferSpan) Debug.Assert(span.SnapshotSpan.End <= line.EndIncludingLineBreak); var lineExtent = new VirtualSnapshotSpan(new VirtualSnapshotPoint(line.Start), new VirtualSnapshotPoint(line.EndIncludingLineBreak, span.End.VirtualSpaces)); var extentTmp = lineExtent.Intersection(span); - Debug2.Assert(!(extentTmp is null)); - if (line.VisibilityState != VisibilityState.Unattached && !(extentTmp is null)) { + Debug2.Assert(extentTmp is not null); + if (line.VisibilityState != VisibilityState.Unattached && extentTmp is not null) { var extent = extentTmp.Value; Collection textBounds; if (extent.Start.IsInVirtualSpace) { @@ -118,7 +118,7 @@ public static bool IsMultiLineSpan(ITextView textView, SnapshotSpan bufferSpan) } if (createOutlinedPath) geo = geo!.GetOutlinedPathGeometry(); - if (!(geo is null) && geo.CanFreeze) + if (geo is not null && geo.CanFreeze) geo.Freeze(); return geo; } diff --git a/dnSpy/dnSpy/Text/Editor/MouseLocation.cs b/dnSpy/dnSpy/Text/Editor/MouseLocation.cs index dfae719d0b..c10b459a75 100644 --- a/dnSpy/dnSpy/Text/Editor/MouseLocation.cs +++ b/dnSpy/dnSpy/Text/Editor/MouseLocation.cs @@ -51,7 +51,7 @@ public static MouseLocation Create(IWpfTextView wpfTextView, MouseEventArgs e, b var point = GetTextPoint(wpfTextView, e); var line = wpfTextView.TextViewLines.GetTextViewLineContainingYCoordinate(point.Y); - if (!(line is null)) + if (line is not null) textViewLine = line; else if (point.Y <= wpfTextView.ViewportTop) textViewLine = wpfTextView.TextViewLines.FirstVisibleLine; diff --git a/dnSpy/dnSpy/Text/Editor/MouseProcessorCollection.cs b/dnSpy/dnSpy/Text/Editor/MouseProcessorCollection.cs index fb90fa423a..5bbb40fd8c 100644 --- a/dnSpy/dnSpy/Text/Editor/MouseProcessorCollection.cs +++ b/dnSpy/dnSpy/Text/Editor/MouseProcessorCollection.cs @@ -53,7 +53,7 @@ public MouseProcessorCollection(UIElement mouseElement, UIElement? manipulationE mouseElement.AddHandler(UIElement.DragOverEvent, new DragEventHandler(MouseElement_DragOver), true); mouseElement.AddHandler(UIElement.DragLeaveEvent, new DragEventHandler(MouseElement_DragLeave), true); mouseElement.AddHandler(UIElement.DragEnterEvent, new DragEventHandler(MouseElement_DragEnter), true); - if (!(manipulationElement is null)) { + if (manipulationElement is not null) { manipulationElement.AddHandler(UIElement.TouchUpEvent, new EventHandler(ManipulationElement_TouchUp), true); manipulationElement.AddHandler(UIElement.TouchDownEvent, new EventHandler(ManipulationElement_TouchDown), true); manipulationElement.AddHandler(UIElement.StylusSystemGestureEvent, new StylusSystemGestureEventHandler(ManipulationElement_StylusSystemGesture), true); @@ -393,7 +393,7 @@ public void Dispose() { mouseElement.RemoveHandler(UIElement.DragOverEvent, new DragEventHandler(MouseElement_DragOver)); mouseElement.RemoveHandler(UIElement.DragLeaveEvent, new DragEventHandler(MouseElement_DragLeave)); mouseElement.RemoveHandler(UIElement.DragEnterEvent, new DragEventHandler(MouseElement_DragEnter)); - if (!(manipulationElement is null)) { + if (manipulationElement is not null) { manipulationElement.RemoveHandler(UIElement.TouchUpEvent, new EventHandler(ManipulationElement_TouchUp)); manipulationElement.RemoveHandler(UIElement.TouchDownEvent, new EventHandler(ManipulationElement_TouchDown)); manipulationElement.RemoveHandler(UIElement.StylusSystemGestureEvent, new StylusSystemGestureEventHandler(ManipulationElement_StylusSystemGesture)); diff --git a/dnSpy/dnSpy/Text/Editor/PopupSpaceReservationAgent.cs b/dnSpy/dnSpy/Text/Editor/PopupSpaceReservationAgent.cs index 55a5dbed4c..01172447c6 100644 --- a/dnSpy/dnSpy/Text/Editor/PopupSpaceReservationAgent.cs +++ b/dnSpy/dnSpy/Text/Editor/PopupSpaceReservationAgent.cs @@ -32,7 +32,7 @@ You should have received a copy of the GNU General Public License namespace dnSpy.Text.Editor { sealed class PopupSpaceReservationAgent : ISpaceReservationAgent { - bool IsVisible => !(popup.Child is null); + bool IsVisible => popup.Child is not null; public bool HasFocus => IsVisible && popup.IsKeyboardFocusWithin; public bool IsMouseOver => IsVisible && popup.IsMouseOver; public event EventHandler? GotFocus; @@ -328,7 +328,7 @@ void AddEvents() { if (content is FrameworkElement fwElem) fwElem.SizeChanged += Content_SizeChanged; var window = Window.GetWindow(wpfTextView.VisualElement); - if (!(window is null)) + if (window is not null) window.LocationChanged += Window_LocationChanged; content.GotFocus += Content_GotFocus; content.LostFocus += Content_LostFocus; @@ -344,7 +344,7 @@ void RemoveEvents() { if (content is FrameworkElement fwElem) fwElem.SizeChanged -= Content_SizeChanged; var window = Window.GetWindow(wpfTextView.VisualElement); - if (!(window is null)) + if (window is not null) window.LocationChanged -= Window_LocationChanged; content.GotFocus -= Content_GotFocus; content.LostFocus -= Content_LostFocus; diff --git a/dnSpy/dnSpy/Text/Editor/ReplCommandTargetFilter.cs b/dnSpy/dnSpy/Text/Editor/ReplCommandTargetFilter.cs index b844cc33c5..9789a615a3 100644 --- a/dnSpy/dnSpy/Text/Editor/ReplCommandTargetFilter.cs +++ b/dnSpy/dnSpy/Text/Editor/ReplCommandTargetFilter.cs @@ -232,7 +232,7 @@ public CommandTargetStatus Execute(Guid group, int cmdId, object? args, ref obje else if (group == CommandConstants.TextEditorGroup) { switch ((TextEditorIds)cmdId) { case TextEditorIds.BACKSPACE: - if (!(replEditor.ReplEditorOperations.ProvisionalCompositionSpan is null)) + if (replEditor.ReplEditorOperations.ProvisionalCompositionSpan is not null) replEditor.ReplEditorOperations.InsertText(string.Empty); else replEditor.ReplEditorOperations.Backspace(); diff --git a/dnSpy/dnSpy/Text/Editor/ReplCommands.cs b/dnSpy/dnSpy/Text/Editor/ReplCommands.cs index 28cff0e06a..a2ef3d5c67 100644 --- a/dnSpy/dnSpy/Text/Editor/ReplCommands.cs +++ b/dnSpy/dnSpy/Text/Editor/ReplCommands.cs @@ -89,7 +89,7 @@ public bool SelectPrevious(string? text = null) { return false; } - public bool CanSelectNext => HasCommands && !(selectedIndex is null); + public bool CanSelectNext => HasCommands && selectedIndex is not null; public bool SelectNext(string? text = null) { foreach (var t in NextCommands) { diff --git a/dnSpy/dnSpy/Text/Editor/ReplEditor.cs b/dnSpy/dnSpy/Text/Editor/ReplEditor.cs index 7280d36595..9aabc134d4 100644 --- a/dnSpy/dnSpy/Text/Editor/ReplEditor.cs +++ b/dnSpy/dnSpy/Text/Editor/ReplEditor.cs @@ -166,7 +166,7 @@ void StopRefreshTimer() { void DelayScreenRefresh() { if (wpfTextViewHost.IsClosed) return; - if (!(screenRefreshTimer is null)) + if (screenRefreshTimer is not null) return; int ms = wpfTextView.Options.GetReplRefreshScreenOnChangeWaitMilliSeconds(); if (ms > 0) @@ -202,7 +202,7 @@ void WriteOffsetOfPrompt(int? newValue, bool force = false) { cachedColorsList.AddOrUpdate(wpfTextView.TextSnapshot.Length, scriptOutputCachedTextColorsCollection); } else { - Debug2.Assert(!(scriptOutputCachedTextColorsCollection is null)); + Debug2.Assert(scriptOutputCachedTextColorsCollection is not null); scriptOutputCachedTextColorsCollection = null; } } @@ -216,7 +216,7 @@ public void Reset() { ClearPendingOutput(); ClearUndoRedoHistory(); CreateEmptyLastLineIfNeededAndMoveCaret(); - if (!(OffsetOfPrompt is null)) + if (OffsetOfPrompt is not null) AddCodeSubBuffer(); scriptOutputCachedTextColorsCollection = null; WriteOffsetOfPrompt(null, true); @@ -226,13 +226,13 @@ public bool IsAtEditingPosition { get { if (!IsCommandMode) return false; - Debug2.Assert(!(OffsetOfPrompt is null)); + Debug2.Assert(OffsetOfPrompt is not null); return CaretOffset >= OffsetOfPrompt.Value; } } public int FilterOffset(int offset) { - Debug2.Assert(!(OffsetOfPrompt is null)); + Debug2.Assert(OffsetOfPrompt is not null); if (offset < OffsetOfPrompt.Value) offset = OffsetOfPrompt.Value; var line = wpfTextView.TextSnapshot.GetLineFromPosition(offset); @@ -249,7 +249,7 @@ public int FilterOffset(int offset) { void ClearCurrentInput(bool removePrompt) { if (!IsCommandMode) return; - Debug2.Assert(!(OffsetOfPrompt is null)); + Debug2.Assert(OffsetOfPrompt is not null); int offs = removePrompt ? OffsetOfPrompt.Value : FilterOffset(OffsetOfPrompt.Value); MoveTo(offs); var span = Span.FromBounds(offs, wpfTextView.TextSnapshot.Length); @@ -300,7 +300,7 @@ string CurrentInput { Debug.Assert(IsCommandMode); if (!IsCommandMode) return string.Empty; - Debug2.Assert(!(OffsetOfPrompt is null)); + Debug2.Assert(OffsetOfPrompt is not null); string s = wpfTextView.TextBuffer.CurrentSnapshot.GetText(OffsetOfPrompt.Value, wpfTextView.TextSnapshot.Length - OffsetOfPrompt.Value); return ToInputString(s, PrimaryPrompt); @@ -349,7 +349,7 @@ public void ClearScreen() { if (!CanClearScreen) return; ClearPendingOutput(); - bool hasPrompt = !(OffsetOfPrompt is null); + bool hasPrompt = OffsetOfPrompt is not null; AddNewDocument(); ClearUndoRedoHistory(); WriteOffsetOfPrompt(null, true); @@ -408,7 +408,7 @@ void AddNewDocument() { async void TextBuffer_Changed(object? sender, TextContentChangedEventArgs e) { if (!IsCommandMode) return; - Debug2.Assert(!(OffsetOfPrompt is null)); + Debug2.Assert(OffsetOfPrompt is not null); var buf = CreateReplCommandInput(e); if (buf is null) return; @@ -499,7 +499,7 @@ void UpdateCommand(bool clearSearchText) { Debug.Assert(IsCommandMode); if (!IsCommandMode) return; - Debug2.Assert(!(OffsetOfPrompt is null)); + Debug2.Assert(OffsetOfPrompt is not null); var command = replCommands.SelectedCommand; if (command is null) @@ -523,7 +523,7 @@ void FlushScriptOutputUIThread() { return; var caretPos = wpfTextView.Caret.Position; - bool caretIsInEditingArea = !(OffsetOfPrompt is null) && CaretOffset >= OffsetOfPrompt.Value; + bool caretIsInEditingArea = OffsetOfPrompt is not null && CaretOffset >= OffsetOfPrompt.Value; ColorAndText[]? newPendingOutput = null; var sb = new StringBuilder(); @@ -540,8 +540,8 @@ void FlushScriptOutputUIThread() { cachedColorsList.RemoveLastCachedTextColorsCollection(); ClearCurrentInput(true); } - if (!(newPendingOutput is null)) { - Debug2.Assert(!(scriptOutputCachedTextColorsCollection is null)); + if (newPendingOutput is not null) { + Debug2.Assert(scriptOutputCachedTextColorsCollection is not null); foreach (var info in newPendingOutput) { sb.Append(info.Text); scriptOutputCachedTextColorsCollection?.Append(info.Color, info.Text); @@ -550,7 +550,7 @@ void FlushScriptOutputUIThread() { RawAppend(sb.ToString()); MoveToEnd(); if (isCommandMode) { - Debug2.Assert(!(currentCommand is null)); + Debug2.Assert(currentCommand is not null); int posBeforeNewLine = wpfTextView.TextSnapshot.Length; CreateEmptyLastLineIfNeededAndMoveCaret(); int extraLen = wpfTextView.TextSnapshot.Length - posBeforeNewLine; @@ -678,7 +678,7 @@ void CreateEmptyLastLineIfNeededAndMoveCaret() { void PrintPrompt() { // Can happen if we reset the script and it throws an OperationCanceledException - if (!(OffsetOfPrompt is null)) + if (OffsetOfPrompt is not null) return; CreateEmptyLastLineIfNeededAndMoveCaret(); @@ -694,7 +694,7 @@ void PrintPrompt() { /// /// true if we're reading user input and new user commands get executed when enter is pressed /// - bool IsCommandMode => !(OffsetOfPrompt is null); + bool IsCommandMode => OffsetOfPrompt is not null; /// /// true if the script is executing and we don't accept any user input @@ -805,7 +805,7 @@ void AddSubBuffer(ReplSubBuffer buffer) { } void AddCodeSubBuffer() { - Debug2.Assert(!(OffsetOfPrompt is null)); + Debug2.Assert(OffsetOfPrompt is not null); Debug.Assert(LastLine.Length == 0); AddSubBuffer(new ReplSubBuffer(ReplBufferKind.Code, OffsetOfPrompt.Value, LastLine.Start.Position)); } diff --git a/dnSpy/dnSpy/Text/Editor/ResourceDictionaryUtilities.cs b/dnSpy/dnSpy/Text/Editor/ResourceDictionaryUtilities.cs index c8b8e80c29..8b191616be 100644 --- a/dnSpy/dnSpy/Text/Editor/ResourceDictionaryUtilities.cs +++ b/dnSpy/dnSpy/Text/Editor/ResourceDictionaryUtilities.cs @@ -28,7 +28,7 @@ static class ResourceDictionaryUtilities { public static Brush? GetBrush(ResourceDictionary dict, string prop, Brush? defaultBrush = null) { var brush = dict[prop] as Brush ?? defaultBrush; - if (!(brush is null) && brush.CanFreeze) + if (brush is not null && brush.CanFreeze) brush.Freeze(); return brush; } diff --git a/dnSpy/dnSpy/Text/Editor/Search/SearchService.cs b/dnSpy/dnSpy/Text/Editor/Search/SearchService.cs index 8f1f684ef6..72b6906073 100644 --- a/dnSpy/dnSpy/Text/Editor/Search/SearchService.cs +++ b/dnSpy/dnSpy/Text/Editor/Search/SearchService.cs @@ -215,7 +215,7 @@ public CommandTargetStatus CanExecuteSearchControl(Guid group, int cmdId) { return CommandTargetStatus.NotHandled; if (!IsSearchControlVisible) return CommandTargetStatus.NotHandled; - Debug2.Assert(!(searchControl is null)); + Debug2.Assert(searchControl is not null); if (inIncrementalSearch) { if (group == CommandConstants.TextEditorGroup) { @@ -251,7 +251,7 @@ public CommandTargetStatus ExecuteSearchControl(Guid group, int cmdId, object? a return CommandTargetStatus.NotHandled; if (!IsSearchControlVisible) return CommandTargetStatus.NotHandled; - Debug2.Assert(!(searchControl is null)); + Debug2.Assert(searchControl is not null); if (group == CommandConstants.TextEditorGroup && cmdId == (int)TextEditorIds.CANCEL) { if (inIncrementalSearch) @@ -270,7 +270,7 @@ public CommandTargetStatus ExecuteSearchControl(Guid group, int cmdId, object? a case TextEditorIds.TYPECHAR: var s = args as string; - if (!(s is null) && s.IndexOfAny(LineConstants.newLineChars) < 0) + if (s is not null && s.IndexOfAny(LineConstants.newLineChars) < 0) SetIncrementalSearchString(SearchString + s); else CancelIncrementalSearch(); @@ -331,7 +331,7 @@ void SetIncrementalSearchString(string newSearchString) { } bool isIncrementalSearchCaretMove; - bool IsSearchControlVisible => !(layer is null) && !layer.IsEmpty; + bool IsSearchControlVisible => layer is not null && !layer.IsEmpty; void UseGlobalSettingsIfUiIsHidden(bool canOverwriteSearchString) { if (!IsSearchControlVisible) @@ -404,7 +404,7 @@ void ShowSearchControl(SearchKind searchKind, bool canOverwriteSearchString) { static void SelectAllWhenFocused(TextBox textBox) => textBox.GotKeyboardFocus += (s, e) => textBox.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => textBox.SelectAll())); - public bool HasSearchControlFocus => !(searchControl is null) && searchControl.IsKeyboardFocusWithin; + public bool HasSearchControlFocus => searchControl is not null && searchControl.IsKeyboardFocusWithin; void SearchControl_LostKeyboardFocus(object? sender, KeyboardFocusChangedEventArgs e) => OnPropertyChanged(nameof(HasSearchControlFocus)); void SearchControl_GotKeyboardFocus(object? sender, KeyboardFocusChangedEventArgs e) { CloseSearchControlIfIncrementalSearch(); @@ -463,7 +463,7 @@ void Caret_PositionChanged(object? sender, CaretPositionChangedEventArgs e) { } void FocusSearchStringTextBox() { - Debug2.Assert(!(searchControl is null)); + Debug2.Assert(searchControl is not null); Action? callback = null; // If it hasn't been loaded yet, it has no binding and we must select it in its Loaded event if (searchControl.searchStringTextBox.Text.Length == 0 && SearchString.Length != 0) @@ -474,7 +474,7 @@ void FocusSearchStringTextBox() { } void FocusReplaceStringTextBox() { - Debug2.Assert(!(searchControl is null)); + Debug2.Assert(searchControl is not null); Action? callback = null; // If it hasn't been loaded yet, it has no binding and we must select it in its Loaded event if (searchControl.replaceStringTextBox.Text.Length == 0 && ReplaceString.Length != 0) @@ -485,7 +485,7 @@ void FocusReplaceStringTextBox() { } void RepositionControl(bool recalcSize = false) { - Debug2.Assert(!(searchControl is null)); + Debug2.Assert(searchControl is not null); if (recalcSize) searchControl.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); PositionSearchControl(SearchControlPosition.Default); @@ -642,7 +642,7 @@ void CloseSearchControl() { void UpdateSearchStringFromCaretPosition(bool canSearch) { var newSearchString = TryGetSearchStringAtCaret(); - if (!(newSearchString is null)) + if (newSearchString is not null) SetSearchString(newSearchString, canSearch); } @@ -717,7 +717,7 @@ void ReplaceNext() { var res = ReplaceFindNextCore(out var expandedReplacePattern); if (res is null) return; - Debug2.Assert(!(expandedReplacePattern is null)); + Debug2.Assert(expandedReplacePattern is not null); var vres = new VirtualSnapshotSpan(res.Value); if (!wpfTextView.Selection.IsEmpty && wpfTextView.Selection.StreamSelectionSpan == vres) { @@ -734,7 +734,7 @@ void ReplaceNext() { res = ReplaceFindNextCore(out expandedReplacePattern); if (res is null) return; - Debug2.Assert(!(expandedReplacePattern is null)); + Debug2.Assert(expandedReplacePattern is not null); ShowSearchResult(res.Value); } else @@ -796,7 +796,7 @@ bool CanReplaceSpan(SnapshotSpan span, string newText) { var list = new List(replaceListenerProviders.Length); foreach (var provider in replaceListenerProviders) { var listener = provider.Value.Create(wpfTextView); - if (!(listener is null)) + if (listener is not null) list.Add(listener); } replaceListeners = list.Count == 0 ? Array.Empty() : list.ToArray(); @@ -859,7 +859,7 @@ void ReplaceAll() { } if (res is null) break; - Debug2.Assert(!(expandedReplacePattern is null)); + Debug2.Assert(expandedReplacePattern is not null); yield return (res.Value, expandedReplacePattern); if (startingPosition.Position == snapshot.Length) break; @@ -1098,7 +1098,7 @@ void UpdateTextMarkerSearch() { if (SearchString.Length == 0) { var oldColl = findResultCollection; findResultCollection = NormalizedSnapshotSpanCollection.Empty; - if (!(oldColl is null) && oldColl.Count != 0) + if (oldColl is not null && oldColl.Count != 0) RefreshAllTags(); SetFoundResult(true); return; diff --git a/dnSpy/dnSpy/Text/Editor/SmartIndentationService.cs b/dnSpy/dnSpy/Text/Editor/SmartIndentationService.cs index 48d6135215..3575ea6e68 100644 --- a/dnSpy/dnSpy/Text/Editor/SmartIndentationService.cs +++ b/dnSpy/dnSpy/Text/Editor/SmartIndentationService.cs @@ -55,7 +55,7 @@ ISmartIndent CreateSmartIndent(ITextView textView) { var contentType = textView.TextDataModel.ContentType; foreach (var p in providerSelector.GetProviders(contentType)) { var smartIndent = p.Value.CreateSmartIndent(textView); - if (!(smartIndent is null)) + if (smartIndent is not null) return smartIndent; } diff --git a/dnSpy/dnSpy/Text/Editor/SpaceReservationStack.cs b/dnSpy/dnSpy/Text/Editor/SpaceReservationStack.cs index 16c0f32175..ba6d92e659 100644 --- a/dnSpy/dnSpy/Text/Editor/SpaceReservationStack.cs +++ b/dnSpy/dnSpy/Text/Editor/SpaceReservationStack.cs @@ -41,7 +41,7 @@ public bool IsMouseOver { IEnumerable SpaceReservationManagers { get { foreach (var mgr in spaceReservationManagers) { - if (!(mgr is null)) + if (mgr is not null) yield return mgr; } } @@ -123,7 +123,7 @@ void WpfTextView_Closed(object? sender, EventArgs e) { wpfTextView.Closed -= WpfTextView_Closed; for (int i = 0; i < spaceReservationManagers.Length; i++) { var mgr = spaceReservationManagers[i]; - if (!(mgr is null)) { + if (mgr is not null) { spaceReservationManagers[i] = null; mgr.GotAggregateFocus -= SpaceReservationManager_GotAggregateFocus; mgr.LostAggregateFocus -= SpaceReservationManager_LostAggregateFocus; diff --git a/dnSpy/dnSpy/Text/Editor/TextCaret.cs b/dnSpy/dnSpy/Text/Editor/TextCaret.cs index 215de37602..5eb1894182 100644 --- a/dnSpy/dnSpy/Text/Editor/TextCaret.cs +++ b/dnSpy/dnSpy/Text/Editor/TextCaret.cs @@ -102,7 +102,7 @@ void CancelCompositionString() { } void InitializeIME() { - if (!(imeState.HwndSource is null)) + if (imeState.HwndSource is not null) return; imeState.HwndSource = PresentationSource.FromVisual(textView.VisualElement) as HwndSource; if (imeState.HwndSource is null) @@ -264,11 +264,11 @@ void MoveImeCompositionWindow() { var rootVisual = imeState.HwndSource!.RootVisual; GeneralTransform? generalTransform = null; - if (!(rootVisual is null) && rootVisual.IsAncestorOf(textView.VisualElement)) + if (rootVisual is not null && rootVisual.IsAncestorOf(textView.VisualElement)) generalTransform = textView.VisualElement.TransformToAncestor(rootVisual); var compTarget = imeState.HwndSource.CompositionTarget; - if (!(generalTransform is null) && !(compTarget is null)) { + if (generalTransform is not null && compTarget is not null) { var transform = compTarget.TransformToDevice; compForm.dwStyle = CFS_FORCE_POSITION; @@ -520,7 +520,7 @@ public CaretPosition MoveToPreviousCaretPosition() { void SavePreferredYCoordinate() { var line = GetVisibleCaretLine(); - if (!(line is null)) + if (line is not null) __preferredYCoordinate = (line.Top + line.Bottom) / 2 - textView.ViewportTop; else __preferredYCoordinate = 0; diff --git a/dnSpy/dnSpy/Text/Editor/TextCaretLayer.cs b/dnSpy/dnSpy/Text/Editor/TextCaretLayer.cs index daea4b1b42..67ff48dcc6 100644 --- a/dnSpy/dnSpy/Text/Editor/TextCaretLayer.cs +++ b/dnSpy/dnSpy/Text/Editor/TextCaretLayer.cs @@ -220,7 +220,7 @@ void StopTimer() { } void StartTimer() { - if (!(dispatcherTimer is null)) + if (dispatcherTimer is not null) throw new InvalidOperationException(); // Make sure the caret doesn't blink when it's moved layer.Opacity = 1; diff --git a/dnSpy/dnSpy/Text/Editor/TextEditorFactoryService.cs b/dnSpy/dnSpy/Text/Editor/TextEditorFactoryService.cs index 058f514eae..8ab1882aad 100644 --- a/dnSpy/dnSpy/Text/Editor/TextEditorFactoryService.cs +++ b/dnSpy/dnSpy/Text/Editor/TextEditorFactoryService.cs @@ -100,10 +100,10 @@ public GuidObjectsProvider(IWpfTextView wpfTextView, Func GetGuidObjects(GuidObjectsProviderArgs args) { yield return new GuidObject(MenuConstants.GUIDOBJ_WPF_TEXTVIEW_GUID, wpfTextView); var loc = wpfTextView.GetTextEditorPosition(args.OpenedFromKeyboard); - if (!(loc is null)) + if (loc is not null) yield return new GuidObject(MenuConstants.GUIDOBJ_TEXTEDITORPOSITION_GUID, loc); - if (!(createGuidObjects is null)) { + if (createGuidObjects is not null) { foreach (var guidObject in createGuidObjects(args)) yield return guidObject; } @@ -188,7 +188,7 @@ ITextViewModel CreateTextViewModel(ITextDataModel dataModel, ITextViewRoleSet ro var contentType = dataModel.ContentType; foreach (var p in providerSelector.GetProviders(contentType)) { var model = p.Value.CreateTextViewModel(dataModel, roles); - if (!(model is null)) + if (model is not null) return model; } return new TextViewModel(dataModel); @@ -209,7 +209,7 @@ public IDsWpfTextView CreateTextView(ITextViewModel viewModel, ITextViewRoleSet IDsWpfTextView CreateTextViewImpl(ITextViewModel textViewModel, ITextViewRoleSet roles, IEditorOptions parentOptions, TextViewCreatorOptions? options) { var wpfTextView = new WpfTextView(textViewModel, roles, parentOptions, editorOptionsFactoryService, commandService, smartIndentationService, formattedTextSourceFactoryService, viewClassifierAggregatorService, textAndAdornmentSequencerFactoryService, classificationFormatMapService, editorFormatMapService, adornmentLayerDefinitionService, lineTransformProviderService, spaceReservationStackProvider, wpfTextViewConnectionListenerServiceProvider, bufferGraphFactoryService, wpfTextViewCreationListeners, textViewCreationListeners); - if (!(options?.MenuGuid is null)) { + if (options?.MenuGuid is not null) { var guidObjectsProvider = new GuidObjectsProvider(wpfTextView, options.CreateGuidObjects); menuService.InitializeContextMenu(wpfTextView.VisualElement, options.MenuGuid.Value, guidObjectsProvider, new ContextMenuInitializer(wpfTextView)); } diff --git a/dnSpy/dnSpy/Text/Editor/TextMarkerService.cs b/dnSpy/dnSpy/Text/Editor/TextMarkerService.cs index fa031ff7ee..a900bd0f29 100644 --- a/dnSpy/dnSpy/Text/Editor/TextMarkerService.cs +++ b/dnSpy/dnSpy/Text/Editor/TextMarkerService.cs @@ -234,14 +234,14 @@ void TagAggregator_BatchedTagsChanged(object? sender, BatchedTagsChangedEventArg foreach (var mappingSpan in e.Spans) { foreach (var span in mappingSpan.GetSpans(wpfTextView.TextSnapshot)) { var intersection = wpfTextView.TextViewLines.FormattedSpan.Intersection(span); - if (!(intersection is null)) { + if (intersection is not null) { if (intersectionSpans is null) intersectionSpans = new List(); intersectionSpans.Add(intersection.Value); } } } - if (!(intersectionSpans is null)) + if (intersectionSpans is not null) UpdateRange(new NormalizedSnapshotSpanCollection(intersectionSpans)); } @@ -345,7 +345,7 @@ Brush GetBackgroundBrush(ResourceDictionary props) { newPen = new Pen(scBrush, PEN_THICKNESS); newPen.Freeze(); } - else if (!((newPen = props[MarkerFormatDefinition.BorderId] as Pen) is null)) { + else if ((newPen = props[MarkerFormatDefinition.BorderId] as Pen) is not null) { if (newPen.CanFreeze) newPen.Freeze(); } @@ -354,7 +354,7 @@ Brush GetBackgroundBrush(ResourceDictionary props) { } MarkerElement? TryCreateMarkerElement(SnapshotSpan span, ITextMarkerTag tag) { - Debug2.Assert(!(tag.Type is null)); + Debug2.Assert(tag.Type is not null); var geo = wpfTextView.TextViewLines.GetMarkerGeometry(span); if (geo is null) return null; diff --git a/dnSpy/dnSpy/Text/Editor/TextSelectionLayer.cs b/dnSpy/dnSpy/Text/Editor/TextSelectionLayer.cs index 12fba27a83..57539c7e9d 100644 --- a/dnSpy/dnSpy/Text/Editor/TextSelectionLayer.cs +++ b/dnSpy/dnSpy/Text/Editor/TextSelectionLayer.cs @@ -64,7 +64,7 @@ void UpdateBackgroundBrush() { if (BrushComparer.Equals(newBackgroundBrush, backgroundBrush)) return; backgroundBrush = newBackgroundBrush; - if (!(markerElement is null)) + if (markerElement is not null) markerElement.BackgroundBrush = backgroundBrush; } Brush? backgroundBrush; diff --git a/dnSpy/dnSpy/Text/Editor/TextViewMouseProcessorCollection.cs b/dnSpy/dnSpy/Text/Editor/TextViewMouseProcessorCollection.cs index ec480902c4..279ac4961a 100644 --- a/dnSpy/dnSpy/Text/Editor/TextViewMouseProcessorCollection.cs +++ b/dnSpy/dnSpy/Text/Editor/TextViewMouseProcessorCollection.cs @@ -47,7 +47,7 @@ public TextViewMouseProcessorCollection(IWpfTextView wpfTextView, Lazy> GetTags(NormalizedSnapshotSpanCollection s int pos = span.Start; // We check full lines so make sure we don't re-check the same line again - if (!(line is null) && line.ExtentIncludingLineBreak.End.Position > pos) + if (line is not null && line.ExtentIncludingLineBreak.End.Position > pos) continue; for (;;) { - if (!(line is null) && line.ExtentIncludingLineBreak.End.Position == pos) { + if (line is not null && line.ExtentIncludingLineBreak.End.Position == pos) { if (line.Snapshot.LineCount == line.LineNumber + 1) break; line = line.Snapshot.GetLineFromLineNumber(line.LineNumber + 1); diff --git a/dnSpy/dnSpy/Text/Editor/WpfTextView.LayoutHelper.cs b/dnSpy/dnSpy/Text/Editor/WpfTextView.LayoutHelper.cs index c5a9b33ce9..353c7a491e 100644 --- a/dnSpy/dnSpy/Text/Editor/WpfTextView.LayoutHelper.cs +++ b/dnSpy/dnSpy/Text/Editor/WpfTextView.LayoutHelper.cs @@ -97,11 +97,11 @@ public void LayoutLines(SnapshotPoint bufferPosition, ViewRelativePosition relat // just like in VS' IWpfTextViewLine collection. var firstInfo = infos[0]; var prevLine = AddLineTransform(GetLineBefore(firstInfo.Line), firstInfo.Y, ViewRelativePosition.Bottom); - if (!(prevLine is null)) + if (prevLine is not null) infos.Insert(0, new LineInfo(prevLine, firstInfo.Y - prevLine.Height)); var lastInfo = infos[infos.Count - 1]; var nextLine = AddLineTransform(GetLineAfter(lastInfo.Line), lastInfo.Y + lastInfo.Line.Height, ViewRelativePosition.Top); - if (!(nextLine is null)) + if (nextLine is not null) infos.Add(new LineInfo(nextLine, lastInfo.Y + lastInfo.Line.Height)); var keptLines = new HashSet(); @@ -165,7 +165,7 @@ public void LayoutLines(SnapshotPoint bufferPosition, ViewRelativePosition relat List CreateLineInfos(SnapshotPoint bufferPosition, ViewRelativePosition relativeTo, double verticalDistance, double viewportHeightOverride) { var lineInfos = new List(); var startLine = GetLine(bufferPosition); - Debug2.Assert(!(startLine is null)); + Debug2.Assert(startLine is not null); double newViewportBottom = NewViewportTop + viewportHeightOverride; double lineStartY; @@ -221,7 +221,7 @@ List CreateLineInfos(SnapshotPoint bufferPosition, ViewRelativePositio } IFormattedLine? AddLineTransform(IFormattedLine? line, double yPosition, ViewRelativePosition placement) { - if (!(line is null)) { + if (line is not null) { var lineTransform = lineTransformProvider.GetLineTransform(line, yPosition, placement); if (lineTransform != line.LineTransform) { line.SetLineTransform(lineTransform); diff --git a/dnSpy/dnSpy/Text/Editor/WpfTextView.MouseHoverHelper.cs b/dnSpy/dnSpy/Text/Editor/WpfTextView.MouseHoverHelper.cs index 0f0c6d9fb5..f2c8ba9db8 100644 --- a/dnSpy/dnSpy/Text/Editor/WpfTextView.MouseHoverHelper.cs +++ b/dnSpy/dnSpy/Text/Editor/WpfTextView.MouseHoverHelper.cs @@ -134,9 +134,9 @@ void Timer_Tick(object? sender, EventArgs e) { ClearMouseHoverPositionAndStopTimer(); return; } - Debug2.Assert(!(timerStart is null)); + Debug2.Assert(timerStart is not null); var list = GetHandlersToNotify(); - if (!(list is null)) { + if (list is not null) { var mhe = new MouseHoverEventArgs(owner, position.Value, owner.BufferGraph.CreateMappingPoint(new SnapshotPoint(owner.TextSnapshot, position.Value), PointTrackingMode.Positive)); foreach (var h in list) { h.Raised = true; diff --git a/dnSpy/dnSpy/Text/Editor/WpfTextView.cs b/dnSpy/dnSpy/Text/Editor/WpfTextView.cs index 3d74d5a7f2..e4d6b3eefe 100644 --- a/dnSpy/dnSpy/Text/Editor/WpfTextView.cs +++ b/dnSpy/dnSpy/Text/Editor/WpfTextView.cs @@ -232,14 +232,14 @@ public WpfTextView(ITextViewModel textViewModel, ITextViewRoleSet roles, IEditor void NotifyTextViewCreated(IContentType newContentType, IContentType? oldContentType) { foreach (var lz in wpfTextViewCreationListeners) { - if (!(oldContentType is null) && oldContentType.IsOfAnyType(lz.Metadata.ContentTypes)) + if (oldContentType is not null && oldContentType.IsOfAnyType(lz.Metadata.ContentTypes)) continue; if (!TextDataModel.ContentType.IsOfAnyType(lz.Metadata.ContentTypes)) continue; lz.Value.TextViewCreated(this); } foreach (var lz in textViewCreationListeners) { - if (!(oldContentType is null) && oldContentType.IsOfAnyType(lz.Metadata.ContentTypes)) + if (oldContentType is not null && oldContentType.IsOfAnyType(lz.Metadata.ContentTypes)) continue; if (!TextDataModel.ContentType.IsOfAnyType(lz.Metadata.ContentTypes)) continue; @@ -257,7 +257,7 @@ void IDsWpfTextView.InvalidateClassifications(SnapshotSpan span) { void DelayScreenRefresh() { if (IsClosed) return; - if (!(screenRefreshTimer is null)) + if (screenRefreshTimer is not null) return; int ms = Options.GetRefreshScreenOnChangeWaitMilliSeconds(); if (ms > 0) @@ -632,7 +632,7 @@ public void Close() { editorFormatMap.FormatMappingChanged -= EditorFormatMap_FormatMappingChanged; spaceReservationStack.GotAggregateFocus -= SpaceReservationStack_GotAggregateFocus; spaceReservationStack.LostAggregateFocus -= SpaceReservationStack_LostAggregateFocus; - if (!(metroWindow is null)) + if (metroWindow is not null) metroWindow.WindowDpiChanged -= MetroWindow_WindowDpiChanged; } @@ -669,13 +669,13 @@ public IWpfTextViewLine GetTextViewLineContainingBufferPosition(SnapshotPoint bu if (IsVisiblePhysicalLinesSnapshot(bufferPosition.Snapshot)) { foreach (var pline in visiblePhysicalLines) { var lline = pline.FindFormattedLineByBufferPosition(bufferPosition); - if (!(lline is null)) + if (lline is not null) return lline; } } var cachedLine = physicalLineCache.FindFormattedLineByBufferPosition(bufferPosition); - if (!(cachedLine is null)) + if (cachedLine is not null) return cachedLine; var physLine = CreatePhysicalLineNoCache(bufferPosition, ViewportWidth); @@ -689,7 +689,7 @@ public IWpfTextViewLine GetTextViewLineContainingBufferPosition(SnapshotPoint bu PhysicalLine CreatePhysicalLineNoCache(SnapshotPoint bufferPosition, double viewportWidthOverride) { if (bufferPosition.Snapshot != TextSnapshot) throw new ArgumentException(); - Debug2.Assert(!(FormattedLineSource is null)); + Debug2.Assert(FormattedLineSource is not null); if (formattedLineSourceIsInvalidated || FormattedLineSource.SourceTextSnapshot != TextSnapshot) CreateFormattedLineSource(viewportWidthOverride); return CreatePhysicalLineNoCache(FormattedLineSource, TextViewModel, VisualSnapshot, bufferPosition); @@ -739,7 +739,7 @@ void DisplayLines(SnapshotPoint bufferPosition, double verticalDistance, ViewRel if (invalidatedRegions.Capacity > 100) invalidatedRegions.TrimExcess(); - Debug2.Assert(!(FormattedLineSource is null)); + Debug2.Assert(FormattedLineSource is not null); if (!(FormattedLineSource.SourceTextSnapshot == TextSnapshot && FormattedLineSource.TopTextSnapshot == VisualSnapshot)) invalidateAllLines = true; if (invalidateAllLines || formattedLineSourceIsInvalidated) { @@ -758,10 +758,10 @@ void DisplayLines(SnapshotPoint bufferPosition, double verticalDistance, ViewRel var layoutHelper = new LayoutHelper(lineTransformProvider, newViewportTop ?? 0, oldVisibleLines, GetValidCachedLines(regionsToInvalidate), FormattedLineSource, TextViewModel, VisualSnapshot, TextSnapshot); layoutHelper.LayoutLines(bufferPosition, relativeTo, verticalDistance, ViewportLeft, viewportWidthOverride, viewportHeightOverride); - Debug2.Assert(!(layoutHelper.AllVisibleLines is null)); - Debug2.Assert(!(layoutHelper.NewOrReformattedLines is null)); - Debug2.Assert(!(layoutHelper.TranslatedLines is null)); - Debug2.Assert(!(layoutHelper.AllVisiblePhysicalLines is null)); + Debug2.Assert(layoutHelper.AllVisibleLines is not null); + Debug2.Assert(layoutHelper.NewOrReformattedLines is not null); + Debug2.Assert(layoutHelper.TranslatedLines is not null); + Debug2.Assert(layoutHelper.AllVisiblePhysicalLines is not null); visiblePhysicalLines.AddRange(layoutHelper.AllVisiblePhysicalLines); wpfTextViewLineCollection = new WpfTextViewLineCollection(this, TextSnapshot, layoutHelper.AllVisibleLines); @@ -879,9 +879,9 @@ void UpdateVisibleLines(double viewportWidthOverride, double ViewportHeightOverr void InitializeZoom() { var window = Window.GetWindow(this); metroWindow = window as MetroWindow; - if (!(window is null) && metroWindow is null) + if (window is not null && metroWindow is null) return; - if (!(metroWindow is null)) { + if (metroWindow is not null) { metroWindow.WindowDpiChanged += MetroWindow_WindowDpiChanged; MetroWindow_WindowDpiChanged(metroWindow, EventArgs.Empty); ZoomLevelChanged?.Invoke(this, new ZoomLevelChangedEventArgs(ZoomLevel, LayoutTransform)); @@ -896,8 +896,8 @@ void WpfTextView_Loaded(object? sender, RoutedEventArgs e) { Loaded -= WpfTextView_Loaded; var window = Window.GetWindow(this); metroWindow = window as MetroWindow; - Debug2.Assert(!(window is null)); - if (!(metroWindow is null)) { + Debug2.Assert(window is not null); + if (metroWindow is not null) { metroWindow.WindowDpiChanged += MetroWindow_WindowDpiChanged; MetroWindow_WindowDpiChanged(metroWindow, EventArgs.Empty); ZoomLevelChanged?.Invoke(this, new ZoomLevelChangedEventArgs(ZoomLevel, LayoutTransform)); @@ -906,7 +906,7 @@ void WpfTextView_Loaded(object? sender, RoutedEventArgs e) { } void MetroWindow_WindowDpiChanged(object? sender, EventArgs e) { - Debug2.Assert(!(sender is null) && sender == metroWindow); + Debug2.Assert(sender is not null && sender == metroWindow); ((MetroWindow)sender).SetScaleTransform(this, ZoomLevel / 100); } @@ -916,7 +916,7 @@ ILineTransformProvider LineTransformProvider { __lineTransformProvider = lineTransformProviderService.Create(this, removeExtraTextLineVerticalPixels); recreateLineTransformProvider = false; } - Debug2.Assert(!(__lineTransformProvider is null)); + Debug2.Assert(__lineTransformProvider is not null); return __lineTransformProvider; } } diff --git a/dnSpy/dnSpy/Text/Editor/WpfTextViewContainerMargin.cs b/dnSpy/dnSpy/Text/Editor/WpfTextViewContainerMargin.cs index 92b7dd9413..98ce7831f0 100644 --- a/dnSpy/dnSpy/Text/Editor/WpfTextViewContainerMargin.cs +++ b/dnSpy/dnSpy/Text/Editor/WpfTextViewContainerMargin.cs @@ -86,7 +86,7 @@ void UpdateMarginChildren() { foreach (var info in margins) { var margin = info.Margin.GetTextViewMargin(marginName); - if (!(margin is null)) + if (margin is not null) return margin; } diff --git a/dnSpy/dnSpy/Text/Editor/WpfTextViewLineCollection.cs b/dnSpy/dnSpy/Text/Editor/WpfTextViewLineCollection.cs index 4bc8db0103..dd201f9044 100644 --- a/dnSpy/dnSpy/Text/Editor/WpfTextViewLineCollection.cs +++ b/dnSpy/dnSpy/Text/Editor/WpfTextViewLineCollection.cs @@ -173,7 +173,7 @@ public int GetIndexOfTextLine(ITextViewLine textLine) { MarkerHelper.AddGeometries(textView, textBounds, isLineGeometry, clipToViewport, padding, 0, ref geo, ref createOutlinedPath); if (createOutlinedPath) geo = geo!.GetOutlinedPathGeometry(); - if (!(geo is null) && geo.CanFreeze) + if (geo is not null && geo.CanFreeze) geo.Freeze(); return geo; } diff --git a/dnSpy/dnSpy/Text/Editor/WpfTextViewMarginProviderCollection.cs b/dnSpy/dnSpy/Text/Editor/WpfTextViewMarginProviderCollection.cs index 6c3d71b2e7..6d55cd5931 100644 --- a/dnSpy/dnSpy/Text/Editor/WpfTextViewMarginProviderCollection.cs +++ b/dnSpy/dnSpy/Text/Editor/WpfTextViewMarginProviderCollection.cs @@ -90,7 +90,7 @@ void UpdateMargins() { } else { var margin = lazy.Value.CreateMargin(wpfTextViewHost, marginContainer); - if (!(margin is null)) + if (margin is not null) newInfos.Add(new WpfTextViewMarginInfo(lazy.Value, lazy.Metadata, margin)); } } diff --git a/dnSpy/dnSpy/Text/Editor/ZoomControlMargin.cs b/dnSpy/dnSpy/Text/Editor/ZoomControlMargin.cs index 9eea3e42a7..da982c64e3 100644 --- a/dnSpy/dnSpy/Text/Editor/ZoomControlMargin.cs +++ b/dnSpy/dnSpy/Text/Editor/ZoomControlMargin.cs @@ -117,8 +117,8 @@ protected override void OnKeyDown(KeyEventArgs e) { return; } if (Keyboard.Modifiers == ModifierKeys.None && e.Key == Key.Escape) { - Debug2.Assert(!(originalZoomLevel is null)); - if (!(originalZoomLevel is null)) + Debug2.Assert(originalZoomLevel is not null); + if (originalZoomLevel is not null) TextViewZoomLevel = originalZoomLevel.Value; UpdateTextWithZoomLevel(); wpfTextViewHost.TextView.VisualElement.Focus(); @@ -145,11 +145,11 @@ void ZoomControlMargin_IsVisibleChanged(object? sender, DependencyPropertyChange // The combobox is too tall, but I want to use the style from the UI.Wpf dll if (horizontalScrollBarMargin is null) { horizontalScrollBarMargin = wpfTextViewHost.GetTextViewMargin(PredefinedMarginNames.HorizontalScrollBar); - Debug2.Assert(!(horizontalScrollBarMargin is null)); - if (!(horizontalScrollBarMargin is null)) + Debug2.Assert(horizontalScrollBarMargin is not null); + if (horizontalScrollBarMargin is not null) horizontalScrollBarMargin.VisualElement.SizeChanged += VisualElement_SizeChanged; } - if (!(horizontalScrollBarMargin is null)) + if (horizontalScrollBarMargin is not null) Height = horizontalScrollBarMargin.VisualElement.Height; } else @@ -192,7 +192,7 @@ void UnregisterEvents() { public void Dispose() { IsVisibleChanged -= ZoomControlMargin_IsVisibleChanged; wpfTextViewHost.TextView.Options.OptionChanged -= Options_OptionChanged; - if (!(horizontalScrollBarMargin is null)) + if (horizontalScrollBarMargin is not null) horizontalScrollBarMargin.VisualElement.SizeChanged -= VisualElement_SizeChanged; UnregisterEvents(); } diff --git a/dnSpy/dnSpy/Text/Formatting/HtmlBuilderService.cs b/dnSpy/dnSpy/Text/Formatting/HtmlBuilderService.cs index f9ac2ae845..125aacb39e 100644 --- a/dnSpy/dnSpy/Text/Formatting/HtmlBuilderService.cs +++ b/dnSpy/dnSpy/Text/Formatting/HtmlBuilderService.cs @@ -76,7 +76,7 @@ string GenerateHtmlFragmentCore(NormalizedSnapshotSpanCollection spans, ITextVie try { int tabSize; IClassificationFormatMap classificationFormatMap; - if (!(textView is null)) { + if (textView is not null) { classifier = synchronousViewClassifierAggregatorService.GetSynchronousClassifier(textView); classificationFormatMap = classificationFormatMapService.GetClassificationFormatMap(textView); tabSize = textView.Options.GetTabSize(); diff --git a/dnSpy/dnSpy/Text/Formatting/LinePart.cs b/dnSpy/dnSpy/Text/Formatting/LinePart.cs index 6e565df8f7..4848c01cab 100644 --- a/dnSpy/dnSpy/Text/Formatting/LinePart.cs +++ b/dnSpy/dnSpy/Text/Formatting/LinePart.cs @@ -35,7 +35,7 @@ readonly struct LinePart { /// /// Length in column characters. This is never zero. /// - public int ColumnLength => !(AdornmentElement is null) ? 1 : Span.Length; + public int ColumnLength => AdornmentElement is not null ? 1 : Span.Length; /// /// Span relative to the start of the physical line () @@ -58,8 +58,8 @@ readonly struct LinePart { public readonly int Index; public LinePart(int index, int column, Span span, IAdornmentElement adornmentElement, TextRunProperties textRunProperties) { - Debug2.Assert(!(adornmentElement is null)); - Debug2.Assert(!(textRunProperties is null)); + Debug2.Assert(adornmentElement is not null); + Debug2.Assert(textRunProperties is not null); Index = index; Column = column; Span = span; @@ -69,7 +69,7 @@ public LinePart(int index, int column, Span span, IAdornmentElement adornmentEle public LinePart(int index, int column, Span span, TextRunProperties textRunProperties) { Debug.Assert(!span.IsEmpty); - Debug2.Assert(!(textRunProperties is null)); + Debug2.Assert(textRunProperties is not null); Index = index; Column = column; Span = span; @@ -95,7 +95,7 @@ public bool BelongsTo(int lineIndex) { } public override string ToString() { - if (!(AdornmentElement is null)) + if (AdornmentElement is not null) return $"{Span.ToString()} {AdornmentElement.ToString()}"; return Span.ToString(); } diff --git a/dnSpy/dnSpy/Text/Formatting/LinePartsCollection.cs b/dnSpy/dnSpy/Text/Formatting/LinePartsCollection.cs index c1a92619a4..989ce19b07 100644 --- a/dnSpy/dnSpy/Text/Formatting/LinePartsCollection.cs +++ b/dnSpy/dnSpy/Text/Formatting/LinePartsCollection.cs @@ -82,7 +82,7 @@ public int ConvertBufferPositionToColumn(SnapshotPoint bufferPosition) { linePart = LineParts[LineParts.Count - 1]; if (linePart is null) return 0; - if (!(linePart.Value.AdornmentElement is null)) + if (linePart.Value.AdornmentElement is not null) return linePart.Value.Column; return linePart.Value.Column + ((bufferPosition.Position - Span.Span.Start) - linePart.Value.Span.Start); } @@ -103,7 +103,7 @@ public SnapshotPoint ConvertColumnToBufferPosition(int column) { linePart = LineParts[LineParts.Count - 1]; if (linePart is null) return null; - if (!(linePart.Value.AdornmentElement is null)) + if (linePart.Value.AdornmentElement is not null) return null; return Span.Start + linePart.Value.Span.Start + (column - linePart.Value.Column); } diff --git a/dnSpy/dnSpy/Text/Formatting/LinePartsTextSource.cs b/dnSpy/dnSpy/Text/Formatting/LinePartsTextSource.cs index a424cbb98b..65601d3fe7 100644 --- a/dnSpy/dnSpy/Text/Formatting/LinePartsTextSource.cs +++ b/dnSpy/dnSpy/Text/Formatting/LinePartsTextSource.cs @@ -50,7 +50,7 @@ public override TextRun GetTextRun(int textSourceCharacterIndex) { if (linePart is null) return endOfLine; var part = linePart.Value; - if (!(part.AdornmentElement is null)) + if (part.AdornmentElement is not null) return new AdornmentTextRun(part); else { int offs = textSourceCharacterIndex - part.Column; @@ -98,7 +98,7 @@ sealed class AdornmentTextRun : TextEmbeddedObject { readonly IAdornmentElement adornmentElement; public AdornmentTextRun(in LinePart linePart) { - Debug2.Assert(!(linePart.AdornmentElement is null)); + Debug2.Assert(linePart.AdornmentElement is not null); adornmentElement = linePart.AdornmentElement; if (linePart.Span.Length != 0 || adornmentElement.Affinity == PositionAffinity.Successor) { BreakBefore = LineBreakCondition.BreakPossible; @@ -128,7 +128,7 @@ public override TextEmbeddedObjectMetrics Format(double remainingParagraphWidth) public int GetColumnOfFirstNonWhitespace() { int column = 0; foreach (var part in linePartsCollection.LineParts) { - if (!(part.AdornmentElement is null)) + if (part.AdornmentElement is not null) break; int len = part.Span.Length; int start = part.Span.Start; diff --git a/dnSpy/dnSpy/Text/Formatting/LineTransformProviderService.cs b/dnSpy/dnSpy/Text/Formatting/LineTransformProviderService.cs index 059de2f425..793a0b77aa 100644 --- a/dnSpy/dnSpy/Text/Formatting/LineTransformProviderService.cs +++ b/dnSpy/dnSpy/Text/Formatting/LineTransformProviderService.cs @@ -55,7 +55,7 @@ public ILineTransformProvider Create(IWpfTextView textView, bool removeExtraText if (!textView.Roles.ContainsAny(p.Metadata.TextViewRoles)) continue; var source = p.Value.Create(textView); - if (!(source is null)) + if (source is not null) list.Add(source); } return new LineTransformProvider(list.ToArray(), removeExtraTextLineVerticalPixels); diff --git a/dnSpy/dnSpy/Text/Formatting/PhysicalLineCache.cs b/dnSpy/dnSpy/Text/Formatting/PhysicalLineCache.cs index 28945f537a..469377c668 100644 --- a/dnSpy/dnSpy/Text/Formatting/PhysicalLineCache.cs +++ b/dnSpy/dnSpy/Text/Formatting/PhysicalLineCache.cs @@ -41,7 +41,7 @@ public PhysicalLineCache(int maxCacheSize) { for (int i = 0; i < cache.Count; i++) { var physLine = cache[i]; var line = physLine.FindFormattedLineByBufferPosition(point); - if (!(line is null)) + if (line is not null) return line; } return null; diff --git a/dnSpy/dnSpy/Text/Formatting/TextAndAdornmentSequencer.cs b/dnSpy/dnSpy/Text/Formatting/TextAndAdornmentSequencer.cs index 1cd0858643..7352663313 100644 --- a/dnSpy/dnSpy/Text/Formatting/TextAndAdornmentSequencer.cs +++ b/dnSpy/dnSpy/Text/Formatting/TextAndAdornmentSequencer.cs @@ -111,7 +111,7 @@ public ITextAndAdornmentCollection CreateTextAndAdornmentCollection(SnapshotSpan sequenceList.Add(new TextSequenceElement(BufferGraph.CreateMappingSpan(textSpan, SpanTrackingMode.EdgeExclusive))); if (info.Span.Start != end || (info.Span.Length == 0 && info.AdornmentElement.Affinity == PositionAffinity.Predecessor)) { bool canAppend = true; - if (!(lastAddedAdornment is null) && lastAddedAdornment.Value.Span.End > info.Span.Start) + if (lastAddedAdornment is not null && lastAddedAdornment.Value.Span.End > info.Span.Start) canAppend = false; if (canAppend) { sequenceList.Add(info.AdornmentElement); diff --git a/dnSpy/dnSpy/Text/Formatting/WpfTextViewLine.cs b/dnSpy/dnSpy/Text/Formatting/WpfTextViewLine.cs index 4786c29556..ae855deed1 100644 --- a/dnSpy/dnSpy/Text/Formatting/WpfTextViewLine.cs +++ b/dnSpy/dnSpy/Text/Formatting/WpfTextViewLine.cs @@ -327,7 +327,7 @@ public bool HasAdornments { if (!IsValid) throw new ObjectDisposedException(nameof(WpfTextViewLine)); foreach (var part in linePartsCollection.LineParts) { - if (!(part.AdornmentElement is null)) + if (part.AdornmentElement is not null) return true; } return false; @@ -517,7 +517,7 @@ public VirtualSnapshotPoint GetVirtualBufferPositionFromXCoordinate(double xCoor throw new ObjectDisposedException(nameof(WpfTextViewLine)); var pos = GetBufferPositionFromXCoordinate(xCoordinate); - if (!(pos is null)) + if (pos is not null) return new VirtualSnapshotPoint(pos.Value); if (xCoordinate <= TextLeft) return new VirtualSnapshotPoint(ExtentIncludingLineBreak.Start); @@ -531,7 +531,7 @@ public VirtualSnapshotPoint GetInsertionBufferPositionFromXCoordinate(double xCo throw new ObjectDisposedException(nameof(WpfTextViewLine)); var pos = GetBufferPositionFromXCoordinate(xCoordinate); - if (!(pos is null)) { + if (pos is not null) { if (pos.Value < End) { var bounds = GetExtendedCharacterBounds(pos.Value); // Get closest buffer position @@ -599,7 +599,7 @@ int GetLastColumn(SnapshotPoint point) { throw new ArgumentException(); int column = FilterColumn(linePartsCollection.ConvertBufferPositionToColumn(point)); var part = linePartsCollection.GetLinePartFromColumn(column); - if (!(part is null)) { + if (part is not null) { var lineParts = linePartsCollection.LineParts; int lineIndex = point - linePartsCollection.Span.Start; for (int i = part.Value.Index + 1; i < lineParts.Count; i++, column++) { @@ -648,7 +648,7 @@ TF.TextBounds GetTextBounds(int column) { column -= textSpan.Length; } - return ((column == 0 && IsLastTextViewLineForSnapshotLine) || IsLastVisualLine) && !(lastTextSpan is null) ? lastTextSpan.Value.Properties : null; + return ((column == 0 && IsLastTextViewLineForSnapshotLine) || IsLastVisualLine) && lastTextSpan is not null ? lastTextSpan.Value.Properties : null; } public Collection GetNormalizedTextBounds(SnapshotSpan bufferSpan) { diff --git a/dnSpy/dnSpy/Text/Groups/OptionsStorage.cs b/dnSpy/dnSpy/Text/Groups/OptionsStorage.cs index a6f6e528d8..574d6b2dec 100644 --- a/dnSpy/dnSpy/Text/Groups/OptionsStorage.cs +++ b/dnSpy/dnSpy/Text/Groups/OptionsStorage.cs @@ -142,7 +142,7 @@ bool TryGetValue(TextViewGroupOption option, string textValue, out object? value value = c.ConvertFromInvariantString(textValue); if (type.IsValueType && value is null) return false; - if (!(value is null) && !type.IsAssignableFrom(value.GetType())) + if (value is not null && !type.IsAssignableFrom(value.GetType())) return false; return true; } diff --git a/dnSpy/dnSpy/Text/Groups/TextViewOptionsGroup.cs b/dnSpy/dnSpy/Text/Groups/TextViewOptionsGroup.cs index cc0dd7c31c..34f2a86680 100644 --- a/dnSpy/dnSpy/Text/Groups/TextViewOptionsGroup.cs +++ b/dnSpy/dnSpy/Text/Groups/TextViewOptionsGroup.cs @@ -48,12 +48,12 @@ public TextViewOptionsGroup(string groupName, IContentTypeRegistryService conten this.groupName = groupName ?? throw new ArgumentNullException(nameof(groupName)); foreach (var option in defaultOptions) { - Debug2.Assert(!(option.Name is null)); + Debug2.Assert(option.Name is not null); if (option.Name is null) continue; var ct = option.ContentType is null ? null : contentTypeRegistryService.GetContentType(option.ContentType); - Debug2.Assert(!(ct is null)); + Debug2.Assert(ct is not null); if (ct is null) continue; @@ -71,7 +71,7 @@ public TextViewOptionsGroup(string groupName, IContentTypeRegistryService conten TextViewGroupOptionCollection GetCollection(IContentType? contentType) { if (contentType is null) contentType = contentTypeRegistryService.GetContentType(ContentTypes.Any); - Debug2.Assert(!(contentType is null)); + Debug2.Assert(contentType is not null); if (contentType is null) return ErrorCollection; diff --git a/dnSpy/dnSpy/Text/Groups/TextViewOptionsGroupService.cs b/dnSpy/dnSpy/Text/Groups/TextViewOptionsGroupService.cs index 7d8247fe05..5d607d3a9f 100644 --- a/dnSpy/dnSpy/Text/Groups/TextViewOptionsGroupService.cs +++ b/dnSpy/dnSpy/Text/Groups/TextViewOptionsGroupService.cs @@ -82,12 +82,12 @@ ContentTypeOptionDefinition[] GetDefaultOptions(string groupName) { continue; options.AddRange(lz.Value.GetOptions()); } - return options.Where(a => !(a.ContentType is null) && !(a.Name is null) && !(a.Type is null)).ToArray(); + return options.Where(a => a.ContentType is not null && a.Name is not null && a.Type is not null).ToArray(); } void ITextViewOptionsGroupServiceImpl.TextViewCreated(ITextView textView) { var wpfTextView = textView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); + Debug2.Assert(wpfTextView is not null); if (wpfTextView is null) return; @@ -97,7 +97,7 @@ void ITextViewOptionsGroupServiceImpl.TextViewCreated(ITextView textView) { foreach (var lz in textViewOptionsGroupNameProviders) { var name = lz.Value.TryGetGroupName(wpfTextView); - if (!(name is null)) { + if (name is not null) { var group = GetGroup(name); group.TextViewCreated(wpfTextView); break; diff --git a/dnSpy/dnSpy/Text/Operations/EditorOperations.cs b/dnSpy/dnSpy/Text/Operations/EditorOperations.cs index f976019147..c667684868 100644 --- a/dnSpy/dnSpy/Text/Operations/EditorOperations.cs +++ b/dnSpy/dnSpy/Text/Operations/EditorOperations.cs @@ -219,7 +219,7 @@ public bool Capitalize() { if (!info.IsSignificant) continue; var newSpan = span.Overlap(info.Span); - Debug2.Assert(!(newSpan is null)); + Debug2.Assert(newSpan is not null); if (newSpan is null) continue; var s = info.Span.GetText(); @@ -238,7 +238,7 @@ public bool Capitalize() { } ed.Apply(); } - Debug2.Assert(!(lastWord.Span.Snapshot is null)); + Debug2.Assert(lastWord.Span.Snapshot is not null); if (lastWord.IsSignificant) Caret.MoveTo(new SnapshotPoint(Snapshot, lastWord.Span.End.Position)); @@ -271,7 +271,7 @@ bool CopyToClipboard(string text, string? htmlText, bool isFullLineData, bool is dataObj.SetData(VS_COPY_FULL_LINE_DATA_FORMAT, true); if (isBoxData) dataObj.SetData(VS_COPY_BOX_DATA_FORMAT, true); - if (!(htmlText is null)) + if (htmlText is not null) dataObj.SetData(DataFormats.Html, htmlText); Clipboard.SetDataObject(dataObj); return true; @@ -1502,15 +1502,15 @@ public void PageUp(bool extendSelection) { public void ScrollColumnLeft() { var wpfTextView = TextView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); - if (!(wpfTextView is null)) + Debug2.Assert(wpfTextView is not null); + if (wpfTextView is not null) wpfTextView.ViewScroller.ScrollViewportHorizontallyByPixels(-wpfTextView.FormattedLineSource.ColumnWidth); } public void ScrollColumnRight() { var wpfTextView = TextView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); - if (!(wpfTextView is null)) + Debug2.Assert(wpfTextView is not null); + if (wpfTextView is not null) wpfTextView.ViewScroller.ScrollViewportHorizontallyByPixels(wpfTextView.FormattedLineSource.ColumnWidth); } @@ -1700,7 +1700,7 @@ public void SwapCaretAndAnchor() { if (!Roles.Contains(PredefinedTextViewRoles.Zoomable)) return null; var wpfTextView = TextView as IWpfTextView; - Debug2.Assert(!(wpfTextView is null)); + Debug2.Assert(wpfTextView is not null); return wpfTextView; } diff --git a/dnSpy/dnSpy/Text/Operations/ReplEditorOperations.cs b/dnSpy/dnSpy/Text/Operations/ReplEditorOperations.cs index eb2587aedd..e7a9ed0ed5 100644 --- a/dnSpy/dnSpy/Text/Operations/ReplEditorOperations.cs +++ b/dnSpy/dnSpy/Text/Operations/ReplEditorOperations.cs @@ -139,14 +139,14 @@ public void AddUserInput(string text, bool clearSearchText = true) { var firstSpan = default(SnapshotSpan); using (var ed = wpfTextView.TextBuffer.CreateEdit()) { foreach (var span in GetNormalizedSpansToReplaceWithText()) { - Debug2.Assert(!(span.Snapshot is null)); + Debug2.Assert(span.Snapshot is not null); if (firstSpan.Snapshot is null) firstSpan = span; ed.Replace(span, s); } ed.Apply(); } - Debug2.Assert(!(firstSpan.Snapshot is null)); + Debug2.Assert(firstSpan.Snapshot is not null); wpfTextView.Selection.Clear(); wpfTextView.Caret.MoveTo(new SnapshotPoint(wpfTextView.TextSnapshot, firstSpan.Start.Position + s.Length)); wpfTextView.Caret.EnsureVisible(); diff --git a/dnSpy/dnSpy/Text/Operations/TextSearchNavigator.cs b/dnSpy/dnSpy/Text/Operations/TextSearchNavigator.cs index 6b1667ced1..731fecad9f 100644 --- a/dnSpy/dnSpy/Text/Operations/TextSearchNavigator.cs +++ b/dnSpy/dnSpy/Text/Operations/TextSearchNavigator.cs @@ -32,12 +32,12 @@ sealed class TextSearchNavigator : ITextSearchNavigator { public SnapshotPoint? StartPoint { get { - if (!(startPoint is null)) + if (startPoint is not null) startPoint = startPoint.Value.TranslateTo(buffer.CurrentSnapshot, (SearchOptions & FindOptions.SearchReverse) != 0 ? PointTrackingMode.Negative : PointTrackingMode.Positive); return startPoint; } set { - if (!(value is null) && value.Value.Snapshot.TextBuffer != buffer) + if (value is not null && value.Value.Snapshot.TextBuffer != buffer) throw new ArgumentException(); startPoint = value; } @@ -79,7 +79,7 @@ public bool Find() { throw new InvalidOperationException(); SnapshotPoint startingPosition; - if (!(CurrentResult is null)) { + if (CurrentResult is not null) { if ((SearchOptions & FindOptions.SearchReverse) != 0) { if (CurrentResult.Value.End.Position > 0) startingPosition = CurrentResult.Value.End - 1; @@ -97,7 +97,7 @@ public bool Find() { return FindFailed(); } } - else if (!(StartPoint is null)) + else if (StartPoint is not null) startingPosition = StartPoint.Value; else startingPosition = new SnapshotPoint(buffer.CurrentSnapshot, 0); diff --git a/dnSpy/dnSpy/Text/Operations/TextSearchService.cs b/dnSpy/dnSpy/Text/Operations/TextSearchService.cs index 77da0d0046..20ac43a44d 100644 --- a/dnSpy/dnSpy/Text/Operations/TextSearchService.cs +++ b/dnSpy/dnSpy/Text/Operations/TextSearchService.cs @@ -82,7 +82,7 @@ public FindResult(int position, int length, string? expandedReplacePattern) { } bool IsWholeWord(ITextStructureNavigator? textStructureNavigator, ITextSnapshot snapshot, FindResult result) { - Debug2.Assert(!(textStructureNavigator is null)); + Debug2.Assert(textStructureNavigator is not null); if (textStructureNavigator is null) return false; if (result.Length == 0) @@ -326,7 +326,7 @@ IEnumerable FindAllSingleLineForward(ITextSnapshotLine startLine, IT continue; var text = range.Value.GetText(); int index = 0; - if (!(regex is null)) { + if (regex is not null) { foreach (var res in GetRegexResults(regex, range.Value.Start, text, index, searchPattern, options, replacePattern)) yield return res; } @@ -356,7 +356,7 @@ IEnumerable FindAllSingleLineReverse(ITextSnapshotLine startLine, IT continue; var text = range.Value.GetText(); int index = text.Length; - if (!(regex is null)) { + if (regex is not null) { foreach (var res in GetRegexResults(regex, range.Value.Start, text, index, searchPattern, options, replacePattern)) yield return res; } @@ -433,7 +433,7 @@ static bool IsWord(ITextSnapshot snapshot, int position, int length) { IEnumerable GetRegexResults(Regex regex, SnapshotPoint searchTextPosition, string searchText, int index, string searchPattern, FindOptions options, string? replacePattern) { bool onlyWords = (options & FindOptions.WholeWord) != 0; foreach (Match? match in regex.Matches(searchText, index)) { - Debug2.Assert(!(match is null)); + Debug2.Assert(match is not null); int position = searchTextPosition.Position + match.Index; if (!onlyWords || IsWord(searchTextPosition.Snapshot, position, searchPattern.Length)) yield return new FindResult(position, match.Length, replacePattern is null ? null : match.Result(replacePattern)); diff --git a/dnSpy/dnSpy/Text/Operations/TextStructureNavigatorSelectorService.cs b/dnSpy/dnSpy/Text/Operations/TextStructureNavigatorSelectorService.cs index f8a48b4cab..147ff6778f 100644 --- a/dnSpy/dnSpy/Text/Operations/TextStructureNavigatorSelectorService.cs +++ b/dnSpy/dnSpy/Text/Operations/TextStructureNavigatorSelectorService.cs @@ -66,7 +66,7 @@ public ITextStructureNavigator CreateTextStructureNavigator(ITextBuffer textBuff providerSelector = new ProviderSelector(contentTypeRegistryService, textStructureNavigatorProviders); foreach (var p in providerSelector.GetProviders(contentType)) { var nav = p.Value.CreateTextStructureNavigator(textBuffer); - if (!(nav is null)) + if (nav is not null) return nav; } Debug.Fail($"Couldn't find a {nameof(ITextStructureNavigatorProvider)}"); diff --git a/dnSpy/dnSpy/Text/Operations/TextUndoHistory.cs b/dnSpy/dnSpy/Text/Operations/TextUndoHistory.cs index aa26b47170..67ad7b7050 100644 --- a/dnSpy/dnSpy/Text/Operations/TextUndoHistory.cs +++ b/dnSpy/dnSpy/Text/Operations/TextUndoHistory.cs @@ -89,7 +89,7 @@ public ITextUndoTransaction CreateTransaction(string description) { throw new InvalidOperationException(); if (description is null) throw new ArgumentNullException(nameof(description)); - if (!(currentTransaction is null)) + if (currentTransaction is not null) throw new InvalidOperationException(); ClearRedo(); return currentTransaction = new TextUndoTransaction(this, undoList.LastOrDefault(), description); @@ -98,7 +98,7 @@ public ITextUndoTransaction CreateTransaction(string description) { public void Redo(int count) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); - if (!(currentTransaction is null)) + if (currentTransaction is not null) throw new InvalidOperationException(); if (State != TextUndoHistoryState.Idle) throw new InvalidOperationException(); @@ -118,7 +118,7 @@ public void Redo(int count) { public void Undo(int count) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); - if (!(currentTransaction is null)) + if (currentTransaction is not null) throw new InvalidOperationException(); if (State != TextUndoHistoryState.Idle) throw new InvalidOperationException(); diff --git a/dnSpy/dnSpy/Text/ProviderSelector.cs b/dnSpy/dnSpy/Text/ProviderSelector.cs index dd972a107a..2f7d282391 100644 --- a/dnSpy/dnSpy/Text/ProviderSelector.cs +++ b/dnSpy/dnSpy/Text/ProviderSelector.cs @@ -55,7 +55,7 @@ Lazy[] CreateProviderList(IContentType contentType foreach (var provider in providers) { foreach (var ctString in provider.Metadata.ContentTypes) { var ct = contentTypeRegistryService.GetContentType(ctString); - Debug2.Assert(!(ct is null)); + Debug2.Assert(ct is not null); if (ct is null) continue; int dist = GetDistance(ct, contentType); diff --git a/dnSpy/dnSpy/Text/Tagging/TagAggregatorBase.cs b/dnSpy/dnSpy/Text/Tagging/TagAggregatorBase.cs index 6fe95e00f0..dc8f4a4e74 100644 --- a/dnSpy/dnSpy/Text/Tagging/TagAggregatorBase.cs +++ b/dnSpy/dnSpy/Text/Tagging/TagAggregatorBase.cs @@ -87,7 +87,7 @@ public IEnumerable> GetTags(NormalizedSnapshotSpanCollection var snapshotSpansSnapshot = snapshotSpans[0].Snapshot; foreach (var tagger in taggers) { var syncTagger = tagger as ISynchronousTagger; - var tags = !(syncTagger is null) ? syncTagger.GetTags(snapshotSpans, cancellationToken) : tagger.GetTags(snapshotSpans); + var tags = syncTagger is not null ? syncTagger.GetTags(snapshotSpans, cancellationToken) : tagger.GetTags(snapshotSpans); cancellationToken.ThrowIfCancellationRequested(); foreach (var tagSpan in tags) { var newSpan = tagSpan.Span.TranslateTo(snapshotSpansSnapshot, SpanTrackingMode.EdgeExclusive); @@ -141,7 +141,7 @@ void RaiseTagsChanged(SnapshotSpan span, object? sender = null) { return; IMappingSpan? mappingSpan = null; TagsChanged?.Invoke(sender ?? this, new TagsChangedEventArgs(mappingSpan = BufferGraph.CreateMappingSpan(span, SpanTrackingMode.EdgeExclusive))); - if (!(BatchedTagsChanged is null)) { + if (BatchedTagsChanged is not null) { lock (lockObj) { batchedTagsChangedList.Add(mappingSpan ?? BufferGraph.CreateMappingSpan(span, SpanTrackingMode.EdgeExclusive)); if (batchedTagsChangedList.Count == 1) diff --git a/dnSpy/dnSpy/Text/Tagging/TaggerFactory.cs b/dnSpy/dnSpy/Text/Tagging/TaggerFactory.cs index a30c3a45b1..af34ae0a60 100644 --- a/dnSpy/dnSpy/Text/Tagging/TaggerFactory.cs +++ b/dnSpy/dnSpy/Text/Tagging/TaggerFactory.cs @@ -45,11 +45,11 @@ public IEnumerable> Create(ITextView textView, ITextBuffer textBuf var type = typeof(T); foreach (var info in textViewTaggerProviders) { - if (!(info.Metadata.TextViewRoles is null) && !textView.Roles.ContainsAny(info.Metadata.TextViewRoles)) + if (info.Metadata.TextViewRoles is not null && !textView.Roles.ContainsAny(info.Metadata.TextViewRoles)) continue; if (CanCreateTagger(contentType, type, info.Metadata.ContentTypes, info.Metadata.TagTypes)) { var tagger = info.Value.CreateTagger(textView, textBuffer); - if (!(tagger is null)) + if (tagger is not null) yield return tagger; } } @@ -60,7 +60,7 @@ public IEnumerable> Create(ITextBuffer textBuffer, IContentType co foreach (var info in textBufferTaggerProviders) { if (CanCreateTagger(contentType, type, info.Metadata.ContentTypes, info.Metadata.TagTypes)) { var tagger = info.Value.CreateTagger(textBuffer); - if (!(tagger is null)) + if (tagger is not null) yield return tagger; } } diff --git a/dnSpy/dnSpy/Text/Tagging/Xml/XamlAttributeValueClassifier.cs b/dnSpy/dnSpy/Text/Tagging/Xml/XamlAttributeValueClassifier.cs index be69bfbbf8..bba1532143 100644 --- a/dnSpy/dnSpy/Text/Tagging/Xml/XamlAttributeValueClassifier.cs +++ b/dnSpy/dnSpy/Text/Tagging/Xml/XamlAttributeValueClassifier.cs @@ -106,7 +106,7 @@ public bool Initialize(SnapshotSpan span) { } public IEnumerable GetTags() { - Debug2.Assert(!(snapshot is null)); + Debug2.Assert(snapshot is not null); // This is the first { delimiter yield return new XamlSpan(new SnapshotSpan(snapshot, spanStart, 1), XamlKind.Delimiter); @@ -130,17 +130,17 @@ public IEnumerable GetTags() { var name = GetNextName(cspan.Value); if (readingExtensionClass) { yield return new XamlSpan(new SnapshotSpan(snapshot, name.Item1.Span), XamlKind.Class); - if (!(name.Item2 is null)) + if (name.Item2 is not null) yield return new XamlSpan(new SnapshotSpan(snapshot, name.Item2.Value.Span), XamlKind.Delimiter); - if (!(name.Item3 is null)) + if (name.Item3 is not null) yield return new XamlSpan(new SnapshotSpan(snapshot, name.Item3.Value.Span), XamlKind.Class); readingExtensionClass = false; } else { yield return new XamlSpan(new SnapshotSpan(snapshot, name.Item1.Span), XamlKind.ParameterName); - if (!(name.Item2 is null)) + if (name.Item2 is not null) yield return new XamlSpan(new SnapshotSpan(snapshot, name.Item2.Value.Span), XamlKind.Delimiter); - if (!(name.Item3 is null)) + if (name.Item3 is not null) yield return new XamlSpan(new SnapshotSpan(snapshot, name.Item3.Value.Span), XamlKind.ParameterName); var next = GetNextSpan(); @@ -162,9 +162,9 @@ public IEnumerable GetTags() { name = GetNextName(next.Value); yield return new XamlSpan(new SnapshotSpan(snapshot, name.Item1.Span), XamlKind.ParameterValue); - if (!(name.Item2 is null)) + if (name.Item2 is not null) yield return new XamlSpan(new SnapshotSpan(snapshot, name.Item2.Value.Span), XamlKind.Delimiter); - if (!(name.Item3 is null)) + if (name.Item3 is not null) yield return new XamlSpan(new SnapshotSpan(snapshot, name.Item3.Value.Span), XamlKind.ParameterValue); } else { @@ -187,13 +187,13 @@ CharSpan3 GetNextName(in CharSpan item1) { Debug.Assert(item1.Kind == TokenKind.Name); var item2 = GetNextSpan(); if (item2 is null || item2.Value.Span.Length != 1 || item2.Value.Kind != TokenKind.Colon) { - if (!(item2 is null)) + if (item2 is not null) Undo(item2.Value); return new CharSpan3(item1); } var item3 = GetNextSpan(); if (item3 is null || item3.Value.Kind != TokenKind.Name) { - if (!(item3 is null)) + if (item3 is not null) Undo(item3.Value); return new CharSpan3(item1, item2); } @@ -202,14 +202,14 @@ CharSpan3 GetNextName(in CharSpan item1) { void Undo(in CharSpan charSpan) { Debug2.Assert(nextCharSpan is null); - if (!(nextCharSpan is null)) + if (nextCharSpan is not null) throw new InvalidOperationException(); nextCharSpan = charSpan; } CharSpan? nextCharSpan; CharSpan? GetNextSpan() { - if (!(nextCharSpan is null)) { + if (nextCharSpan is not null) { var res = nextCharSpan; nextCharSpan = null; return res; @@ -273,7 +273,7 @@ void SkipWhitespace() { } int NextChar() { - Debug2.Assert(!(snapshot is null)); + Debug2.Assert(snapshot is not null); if (bufferPos >= bufferLen) { int len = spanEnd - snapshotPos; if (len == 0) @@ -289,7 +289,7 @@ int NextChar() { } int PeekChar() { - Debug2.Assert(!(snapshot is null)); + Debug2.Assert(snapshot is not null); if (bufferPos >= bufferLen) { int len = spanEnd - snapshotPos; if (len == 0) diff --git a/dnSpy/dnSpy/Text/Tagging/Xml/XmlTaggerBase.cs b/dnSpy/dnSpy/Text/Tagging/Xml/XmlTaggerBase.cs index 1de6e8904e..d43acccefa 100644 --- a/dnSpy/dnSpy/Text/Tagging/Xml/XmlTaggerBase.cs +++ b/dnSpy/dnSpy/Text/Tagging/Xml/XmlTaggerBase.cs @@ -35,17 +35,17 @@ public event EventHandler? TagsChanged { add { } remove { protected XmlTaggerBase(TaggerClassificationTypes taggerClassificationTypes) { if (taggerClassificationTypes is null) throw new ArgumentNullException(nameof(taggerClassificationTypes)); - Debug2.Assert(!(taggerClassificationTypes.Attribute?.ClassificationType is null)); - Debug2.Assert(!(taggerClassificationTypes.AttributeQuotes?.ClassificationType is null)); - Debug2.Assert(!(taggerClassificationTypes.AttributeValue?.ClassificationType is null)); - Debug2.Assert(!(taggerClassificationTypes.AttributeValueXaml?.ClassificationType is null)); - Debug2.Assert(!(taggerClassificationTypes.CDataSection?.ClassificationType is null)); - Debug2.Assert(!(taggerClassificationTypes.Comment?.ClassificationType is null)); - Debug2.Assert(!(taggerClassificationTypes.Delimiter?.ClassificationType is null)); - Debug2.Assert(!(taggerClassificationTypes.Keyword?.ClassificationType is null)); - Debug2.Assert(!(taggerClassificationTypes.Name?.ClassificationType is null)); - Debug2.Assert(!(taggerClassificationTypes.ProcessingInstruction?.ClassificationType is null)); - Debug2.Assert(!(taggerClassificationTypes.Text?.ClassificationType is null)); + Debug2.Assert(taggerClassificationTypes.Attribute?.ClassificationType is not null); + Debug2.Assert(taggerClassificationTypes.AttributeQuotes?.ClassificationType is not null); + Debug2.Assert(taggerClassificationTypes.AttributeValue?.ClassificationType is not null); + Debug2.Assert(taggerClassificationTypes.AttributeValueXaml?.ClassificationType is not null); + Debug2.Assert(taggerClassificationTypes.CDataSection?.ClassificationType is not null); + Debug2.Assert(taggerClassificationTypes.Comment?.ClassificationType is not null); + Debug2.Assert(taggerClassificationTypes.Delimiter?.ClassificationType is not null); + Debug2.Assert(taggerClassificationTypes.Keyword?.ClassificationType is not null); + Debug2.Assert(taggerClassificationTypes.Name?.ClassificationType is not null); + Debug2.Assert(taggerClassificationTypes.ProcessingInstruction?.ClassificationType is not null); + Debug2.Assert(taggerClassificationTypes.Text?.ClassificationType is not null); this.taggerClassificationTypes = taggerClassificationTypes; } diff --git a/dnSpy/dnSpy/Text/TextBuffer.cs b/dnSpy/dnSpy/Text/TextBuffer.cs index 15cf7c378b..221fdd05c9 100644 --- a/dnSpy/dnSpy/Text/TextBuffer.cs +++ b/dnSpy/dnSpy/Text/TextBuffer.cs @@ -47,7 +47,7 @@ public void ChangeContentType(IContentType newContentType, object? editTag) { void CreateNewCurrentSnapshot(IList? changes, int? reiteratedVersionNumber = null, ITextSource? afterTextSource = null) { // It's null the first time it's called from the ctor - if (!(changes is null)) + if (changes is not null) currentTextVersion = currentTextVersion.SetChanges(changes, reiteratedVersionNumber); var textSource = afterTextSource ?? Document.CreateSnapshot(); var textImage = new TextImage(this, textSource, currentTextVersion.ImageVersion); @@ -75,7 +75,7 @@ event EventHandler? ITextBuffer2.ChangedOnBackgroun internal TextDocument Document { get => document; private set { - if (!(document is null)) + if (document is not null) throw new InvalidOperationException(); document = value; CreateNewCurrentSnapshot(null); @@ -95,7 +95,7 @@ public TextBuffer(IContentType contentType, string text) { Document.SetOwnerThread(null); } - public bool EditInProgress => !(textEditInProgress is null); + public bool EditInProgress => textEditInProgress is not null; public bool CheckEditAccess() => CheckAccess(); TextEdit? textEditInProgress; @@ -199,7 +199,7 @@ internal bool IsSafeToAccessDocumentFromSnapshot(TextImage snapshot) { } public void TakeThreadOwnership() { - if (!(ownerThread is null) && ownerThread != Thread.CurrentThread) + if (ownerThread is not null && ownerThread != Thread.CurrentThread) throw new InvalidOperationException(); ownerThread = Thread.CurrentThread; Document.SetOwnerThread(ownerThread); diff --git a/dnSpy/dnSpy/Text/TextBufferFactoryService.cs b/dnSpy/dnSpy/Text/TextBufferFactoryService.cs index 1df4fabacc..0e44d5fe36 100644 --- a/dnSpy/dnSpy/Text/TextBufferFactoryService.cs +++ b/dnSpy/dnSpy/Text/TextBufferFactoryService.cs @@ -43,9 +43,9 @@ sealed class TextBufferFactoryService : ITextBufferFactoryService3 { InertContentType = contentTypeRegistryService.GetContentType(ContentTypes.Inert); PlaintextContentType = contentTypeRegistryService.GetContentType(ContentTypes.PlainText); TextContentType = contentTypeRegistryService.GetContentType(ContentTypes.Text); - Debug2.Assert(!(InertContentType is null)); - Debug2.Assert(!(PlaintextContentType is null)); - Debug2.Assert(!(TextContentType is null)); + Debug2.Assert(InertContentType is not null); + Debug2.Assert(PlaintextContentType is not null); + Debug2.Assert(TextContentType is not null); } public ITextBuffer CreateTextBuffer() => CreateTextBuffer(TextContentType); diff --git a/dnSpy/dnSpy/Text/WPF/BrushComparer.cs b/dnSpy/dnSpy/Text/WPF/BrushComparer.cs index d396ea09f3..e4c6900c62 100644 --- a/dnSpy/dnSpy/Text/WPF/BrushComparer.cs +++ b/dnSpy/dnSpy/Text/WPF/BrushComparer.cs @@ -32,7 +32,7 @@ public static bool Equals(Brush? a, Brush? b) { var sa = a as SolidColorBrush; var sb = b as SolidColorBrush; - if (!(sa is null) && !(sb is null)) { + if (sa is not null && sb is not null) { if (sa.Color.A == 0 && sb.Color.A == 0) return true; return sa.Color.A == sb.Color.A && sa.Color.R == sb.Color.R && sa.Color.G == sb.Color.G && sa.Color.B == sb.Color.B; diff --git a/dnSpy/dnSpy/Themes/AppCommandLineArgsHandler.cs b/dnSpy/dnSpy/Themes/AppCommandLineArgsHandler.cs index a7f38a41c6..7513c5f9d4 100644 --- a/dnSpy/dnSpy/Themes/AppCommandLineArgsHandler.cs +++ b/dnSpy/dnSpy/Themes/AppCommandLineArgsHandler.cs @@ -38,7 +38,7 @@ public void OnNewArgs(IAppCommandLineArgs args) { bool isGuid = Guid.TryParse(args.Theme, out var guid); var theme = themeService.AllThemes.FirstOrDefault(a => isGuid ? a.Guid == guid : !string.IsNullOrEmpty(a.Name) && StringComparer.InvariantCulture.Equals(a.Name, args.Theme)); - if (!(theme is null)) + if (theme is not null) themeService.Theme = theme; } } diff --git a/dnSpy/dnSpy/Themes/ColorInfo.cs b/dnSpy/dnSpy/Themes/ColorInfo.cs index 5aa7a4ec85..5e84c0263c 100644 --- a/dnSpy/dnSpy/Themes/ColorInfo.cs +++ b/dnSpy/dnSpy/Themes/ColorInfo.cs @@ -61,12 +61,12 @@ public ColorColorInfo(ColorType colorType, string description) : base(colorType, description) => ForegroundResourceKey = null; public override IEnumerable<(object?, object)> GetResourceKeyValues(ThemeColor hlColor) { - if (!(ForegroundResourceKey is null)) { - Debug2.Assert(!(hlColor.Foreground is null)); + if (ForegroundResourceKey is not null) { + Debug2.Assert(hlColor.Foreground is not null); yield return (ForegroundResourceKey, ((SolidColorBrush)hlColor.Foreground).Color); } - if (!(BackgroundResourceKey is null)) { - Debug2.Assert(!(hlColor.Background is null)); + if (BackgroundResourceKey is not null) { + Debug2.Assert(hlColor.Background is not null); yield return (BackgroundResourceKey, ((SolidColorBrush)hlColor.Background).Color); } } @@ -81,12 +81,12 @@ public BrushColorInfo(ColorType colorType, string description) } public override IEnumerable<(object?, object)> GetResourceKeyValues(ThemeColor hlColor) { - if (!(ForegroundResourceKey is null)) { - Debug2.Assert(!(hlColor.Foreground is null)); + if (ForegroundResourceKey is not null) { + Debug2.Assert(hlColor.Foreground is not null); yield return (ForegroundResourceKey, hlColor.Foreground); } - if (!(BackgroundResourceKey is null)) { - Debug2.Assert(!(hlColor.Background is null)); + if (BackgroundResourceKey is not null) { + Debug2.Assert(hlColor.Background is not null); yield return (BackgroundResourceKey, hlColor.Background); } } @@ -101,13 +101,13 @@ public DrawingBrushColorInfo(ColorType colorType, string description) : base(colorType, description) => ForegroundResourceKey = null; public override IEnumerable<(object?, object)> GetResourceKeyValues(ThemeColor hlColor) { - if (!(ForegroundResourceKey is null)) { - Debug2.Assert(!(hlColor.Foreground is null)); + if (ForegroundResourceKey is not null) { + Debug2.Assert(hlColor.Foreground is not null); var brush = hlColor.Foreground; yield return (ForegroundResourceKey, CreateDrawingBrush(brush)); } - if (!(BackgroundResourceKey is null)) { - Debug2.Assert(!(hlColor.Background is null)); + if (BackgroundResourceKey is not null) { + Debug2.Assert(hlColor.Background is not null); var brush = hlColor.Background; yield return (BackgroundResourceKey, CreateDrawingBrush(brush)); } diff --git a/dnSpy/dnSpy/Themes/Theme.cs b/dnSpy/dnSpy/Themes/Theme.cs index 0c234f08bf..9d87290b32 100644 --- a/dnSpy/dnSpy/Themes/Theme.cs +++ b/dnSpy/dnSpy/Themes/Theme.cs @@ -72,7 +72,7 @@ static Theme() { static void InitColorInfos(ColorInfo[] infos) { foreach (var info in infos) { int i = ToIndex(info.ColorType); - if (!(colorInfos[i] is null)) { + if (colorInfos[i] is not null) { Debug.Fail("Duplicate"); throw new Exception("Duplicate"); } @@ -103,13 +103,13 @@ public Theme(XElement root) { MenuName = menuName.Value; var hcName = root.Attribute("is-high-contrast"); - IsHighContrast = !(hcName is null) && (bool)hcName; + IsHighContrast = hcName is not null && (bool)hcName; var darkThemeName = root.Attribute("is-dark"); - IsDark = !(darkThemeName is null) && (bool)darkThemeName; + IsDark = darkThemeName is not null && (bool)darkThemeName; var lightThemeName = root.Attribute("is-light"); - IsLight = !(lightThemeName is null) && (bool)lightThemeName; + IsLight = lightThemeName is not null && (bool)lightThemeName; var sort = root.Attribute("order"); Order = sort is null ? 1 : (double)sort; @@ -118,7 +118,7 @@ public Theme(XElement root) { hlColors[i] = new Color(colorInfos[i]); var colors = root.Element("colors"); - if (!(colors is null)) { + if (colors is not null) { foreach (var color in colors.Elements("color")) { ColorType colorType = 0; var hl = ReadColor(color, ref colorType); @@ -173,12 +173,12 @@ void RecalculateInheritedColorProperties() { } Brush? GetForeground(ColorInfo? info, bool canIncludeDefault) { - while (!(info is null)) { + while (info is not null) { if (!canIncludeDefault && info.ColorType == ColorType.DefaultText) break; var color = hlColors[ToIndex(info.ColorType)]; var val = color.OriginalColor.Foreground; - if (!(val is null)) + if (val is not null) return val; info = info.Parent; } @@ -186,12 +186,12 @@ void RecalculateInheritedColorProperties() { } Brush? GetBackground(ColorInfo? info, bool canIncludeDefault) { - while (!(info is null)) { + while (info is not null) { if (!canIncludeDefault && info.ColorType == ColorType.DefaultText) break; var color = hlColors[ToIndex(info.ColorType)]; var val = color.OriginalColor.Background; - if (!(val is null)) + if (val is not null) return val; info = info.Parent; } @@ -199,12 +199,12 @@ void RecalculateInheritedColorProperties() { } Brush? GetColor3(ColorInfo? info, bool canIncludeDefault) { - while (!(info is null)) { + while (info is not null) { if (!canIncludeDefault && info.ColorType == ColorType.DefaultText) break; var color = hlColors[ToIndex(info.ColorType)]; var val = color.OriginalColor.Color3; - if (!(val is null)) + if (val is not null) return val; info = info.Parent; } @@ -212,12 +212,12 @@ void RecalculateInheritedColorProperties() { } Brush? GetColor4(ColorInfo? info, bool canIncludeDefault) { - while (!(info is null)) { + while (info is not null) { if (!canIncludeDefault && info.ColorType == ColorType.DefaultText) break; var color = hlColors[ToIndex(info.ColorType)]; var val = color.OriginalColor.Color4; - if (!(val is null)) + if (val is not null) return val; info = info.Parent; } @@ -225,12 +225,12 @@ void RecalculateInheritedColorProperties() { } FontStyle? GetFontStyle(ColorInfo? info, bool canIncludeDefault) { - while (!(info is null)) { + while (info is not null) { if (!canIncludeDefault && info.ColorType == ColorType.DefaultText) break; var color = hlColors[ToIndex(info.ColorType)]; var val = color.OriginalColor.FontStyle; - if (!(val is null)) + if (val is not null) return val; info = info.Parent; } @@ -238,12 +238,12 @@ void RecalculateInheritedColorProperties() { } FontWeight? GetFontWeight(ColorInfo? info, bool canIncludeDefault) { - while (!(info is null)) { + while (info is not null) { if (!canIncludeDefault && info.ColorType == ColorType.DefaultText) break; var color = hlColors[ToIndex(info.ColorType)]; var val = color.OriginalColor.FontWeight; - if (!(val is null)) + if (val is not null) return val; info = info.Parent; } @@ -275,27 +275,27 @@ Color GetColorInternal(ColorType colorType) { hl.Name = colorType.ToString(); var fg = GetAttribute(color, "fg", colorInfo.DefaultForeground); - if (!(fg is null)) + if (fg is not null) hl.Foreground = CreateColor(fg); var bg = GetAttribute(color, "bg", colorInfo.DefaultBackground); - if (!(bg is null)) + if (bg is not null) hl.Background = CreateColor(bg); var color3 = GetAttribute(color, "color3", colorInfo.DefaultColor3); - if (!(color3 is null)) + if (color3 is not null) hl.Color3 = CreateColor(color3); var color4 = GetAttribute(color, "color4", colorInfo.DefaultColor4); - if (!(color4 is null)) + if (color4 is not null) hl.Color4 = CreateColor(color4); var italics = color.Attribute("italics") ?? color.Attribute("italic"); - if (!(italics is null)) + if (italics is not null) hl.FontStyle = (bool)italics ? FontStyles.Italic : FontStyles.Normal; var bold = color.Attribute("bold"); - if (!(bold is null)) + if (bold is not null) hl.FontWeight = (bool)bold ? FontWeights.Bold : FontWeights.Normal; return hl; @@ -306,16 +306,16 @@ ThemeColor CreateThemeColor(ColorType colorType) { var colorInfo = colorInfos[ToIndex(colorType)]; - if (!(colorInfo.DefaultForeground is null)) + if (colorInfo.DefaultForeground is not null) hl.Foreground = CreateColor(colorInfo.DefaultForeground); - if (!(colorInfo.DefaultBackground is null)) + if (colorInfo.DefaultBackground is not null) hl.Background = CreateColor(colorInfo.DefaultBackground); - if (!(colorInfo.DefaultColor3 is null)) + if (colorInfo.DefaultColor3 is not null) hl.Color3 = CreateColor(colorInfo.DefaultColor3); - if (!(colorInfo.DefaultColor4 is null)) + if (colorInfo.DefaultColor4 is not null) hl.Color4 = CreateColor(colorInfo.DefaultColor4); return hl; @@ -323,7 +323,7 @@ ThemeColor CreateThemeColor(ColorType colorType) { static string? GetAttribute(XElement xml, string attr, string? defVal) { var a = xml.Attribute(attr); - if (!(a is null)) + if (a is not null) return a.Value; return defVal; } @@ -333,7 +333,7 @@ ThemeColor CreateThemeColor(ColorType colorType) { if (color.StartsWith("SystemColors.")) { string shortName = color.Substring(13); var property = typeof(SystemColors).GetProperty(shortName + "Brush"); - Debug2.Assert(!(property is null)); + Debug2.Assert(property is not null); if (property is null) return null; return (Brush)property.GetValue(null, null)!; diff --git a/dnSpy/dnSpy/Themes/ThemeService.cs b/dnSpy/dnSpy/Themes/ThemeService.cs index 4d66c49f97..3af1c12696 100644 --- a/dnSpy/dnSpy/Themes/ThemeService.cs +++ b/dnSpy/dnSpy/Themes/ThemeService.cs @@ -117,8 +117,8 @@ public event EventHandler ThemeChangedLowPriority { void InitializeResources() { var app = Application.Current; - Debug2.Assert(!(app is null)); - if (!(app is null)) + Debug2.Assert(app is not null); + if (app is not null) ((Theme)Theme).UpdateResources(app.Resources); } diff --git a/dnSpy/dnSpy/ToolBars/ToolBarService.cs b/dnSpy/dnSpy/ToolBars/ToolBarService.cs index 60540306c3..97edc54bf4 100644 --- a/dnSpy/dnSpy/ToolBars/ToolBarService.cs +++ b/dnSpy/dnSpy/ToolBars/ToolBarService.cs @@ -77,7 +77,7 @@ sealed class ToolBarService : IToolBarService { } void InitializeToolBarItems() { - if (!(guidToGroups is null)) + if (guidToGroups is not null) return; var dict = new Dictionary>(); @@ -128,7 +128,7 @@ IEnumerable GetToolBarItemMDs() { public ToolBar InitializeToolBar(ToolBar? toolBar, Guid toolBarGuid, IInputElement? commandTarget) { InitializeToolBarItems(); - Debug2.Assert(!(guidToGroups is null)); + Debug2.Assert(guidToGroups is not null); if (toolBar is null) { toolBar = new ToolBar(); toolBar.FocusVisualStyle = null; @@ -157,7 +157,7 @@ public ToolBar InitializeToolBar(ToolBar? toolBar, Guid toolBarGuid, IInputEleme foreach (var item in items) { var obj = Create(item, ctx, commandTarget); - if (!(obj is null)) + if (obj is not null) toolBar.Items.Add(obj); } } @@ -183,7 +183,7 @@ object Create(ToolBarButtonMD md, IToolBarItemContext ctx, IInputElement? comman var md2 = (IToolBarButtonMetadata)md.Metadata; var cmdHolder = item as ICommandHolder; - var cmd = !(cmdHolder is null) ? cmdHolder.Command : new RelayCommand(a => item.Execute(ctx), a => item.IsEnabled(ctx)); + var cmd = cmdHolder is not null ? cmdHolder.Command : new RelayCommand(a => item.Execute(ctx), a => item.IsEnabled(ctx)); var header = ResourceHelper.GetStringOrNull(item, md2.Header); var icon = md2.Icon; @@ -193,8 +193,8 @@ object Create(ToolBarButtonMD md, IToolBarItemContext ctx, IInputElement? comman var imgRef = item.GetIcon(ctx) ?? ImageReferenceHelper.GetImageReference(item, icon) ?? default; var toggleButtonCmd = item as IToolBarToggleButton; - Debug2.Assert(md2.IsToggleButton == (!(toggleButtonCmd is null)), "Implement IToolBarToggleButton if IsToggleButton is true"); - if (!(toggleButtonCmd is null)) + Debug2.Assert(md2.IsToggleButton == (toggleButtonCmd is not null), "Implement IToolBarToggleButton if IsToggleButton is true"); + if (toggleButtonCmd is not null) return CreateToggleButton(toggleButtonCmd.GetBinding(ctx), cmd, commandTarget, header, toolTip, imgRef); return new ToolBarButtonVM(cmd, commandTarget, header, toolTip, imgRef); } @@ -211,8 +211,8 @@ object CreateToggleButton(Binding binding, ICommand command, IInputElement? comm }); } var checkBox = new CheckBox { Content = sp }; - Debug2.Assert(!(binding is null)); - if (!(binding is null)) + Debug2.Assert(binding is not null); + if (binding is not null) checkBox.SetBinding(ToggleButton.IsCheckedProperty, binding); if (!string.IsNullOrEmpty(toolTip)) checkBox.ToolTip = toolTip; diff --git a/dnSpy/dnSpy/ToolWindows/TabContentImpl.cs b/dnSpy/dnSpy/ToolWindows/TabContentImpl.cs index f4fb9cb9bc..d03ba4edab 100644 --- a/dnSpy/dnSpy/ToolWindows/TabContentImpl.cs +++ b/dnSpy/dnSpy/ToolWindows/TabContentImpl.cs @@ -36,14 +36,14 @@ sealed class TabContentImpl : ITabContent, IFocusable, INotifyPropertyChanged { bool IFocusable.CanFocus { get { var focusable = Content as IFocusable; - return !(focusable is null) && focusable.CanFocus; + return focusable is not null && focusable.CanFocus; } } void IFocusable.Focus() { var focusable = Content as IFocusable; - Debug2.Assert(!(focusable is null)); - if (!(focusable is null)) + Debug2.Assert(focusable is not null); + if (focusable is not null) focusable.Focus(); } @@ -69,7 +69,7 @@ public object? UIObject { if (contentPresenter is null) { contentPresenter = new ContentPresenter { Content = this }; contentPresenter.MouseDown += (s, e) => { - if (!e.Handled && !(Owner is null)) { + if (!e.Handled && Owner is not null) { Owner.SetFocus(this); e.Handled = true; } @@ -99,7 +99,7 @@ bool IsKeyboardFocusWithin { if (contentPresenter?.IsKeyboardFocusWithin == true) return true; var f = ContentUIObject as IInputElement; - return !(f is null) && f.IsKeyboardFocusWithin; + return f is not null && f.IsKeyboardFocusWithin; } } @@ -127,7 +127,7 @@ public object? ContentUIObject { public ToolWindowGroup? Owner { get { - Debug2.Assert(!(owner is null)); + Debug2.Assert(owner is not null); return owner; } set => owner = value; @@ -148,7 +148,7 @@ public TabContentImpl(ToolWindowGroup owner, ToolWindowContent content) { public void OnVisibilityChanged(TabContentVisibilityEvent visEvent) { var ev = Convert(visEvent); - if (!(ev is null)) { + if (ev is not null) { #if DEBUG switch (ev) { case ToolWindowContentVisibilityEvent.Added: @@ -196,7 +196,7 @@ public void OnVisibilityChanged(TabContentVisibilityEvent visEvent) { case TabContentVisibilityEvent.Removed: elementZoomer.Dispose(); RemoveEvents(); - if (!(contentPresenter is null)) + if (contentPresenter is not null) contentPresenter.Content = null; contentPresenter = null; OnPropertyChanged(nameof(UIObject)); @@ -259,7 +259,7 @@ void ToolWindowContent_PropertyChanged(object? sender, PropertyChangedEventArgs void Close() { if (!CanClose) return; - if (!(Owner is null)) + if (Owner is not null) Owner.Close(this); } @@ -267,7 +267,7 @@ void Close() { void ShowWindowPositionMenu(object? uiObj) { var fe = uiObj as FrameworkElement; - Debug2.Assert(!(fe is null)); + Debug2.Assert(fe is not null); if (fe is null) return; diff --git a/dnSpy/dnSpy/ToolWindows/ToolWindowGroup.cs b/dnSpy/dnSpy/ToolWindows/ToolWindowGroup.cs index 6849727fb8..733f576107 100644 --- a/dnSpy/dnSpy/ToolWindows/ToolWindowGroup.cs +++ b/dnSpy/dnSpy/ToolWindows/ToolWindowGroup.cs @@ -50,7 +50,7 @@ public ToolWindowGroup(IToolWindowGroupService toolWindowGroupService, ITabGroup void TabGroup_TabContentAttached(object? sender, TabContentAttachedEventArgs e) { var impl = e.TabContent as TabContentImpl; - Debug2.Assert(!(impl is null)); + Debug2.Assert(impl is not null); if (impl is null) return; if (e.Attached) @@ -67,7 +67,7 @@ public void Close(ToolWindowContent content) { if (content is null) throw new ArgumentNullException(nameof(content)); var impl = GetTabContentImpl(content); - Debug2.Assert(!(impl is null)); + Debug2.Assert(impl is not null); if (impl is null) return; TabGroup.Close(impl); @@ -81,7 +81,7 @@ public void MoveTo(IToolWindowGroup destGroup, ToolWindowContent content) { if (content is null) throw new ArgumentNullException(nameof(content)); var impl = GetTabContentImpl(content); - Debug2.Assert(!(impl is null)); + Debug2.Assert(impl is not null); if (impl is null) throw new InvalidOperationException(); if (destGroup == this) @@ -104,7 +104,7 @@ public void SetFocus(ToolWindowContent content) { if (content is null) throw new ArgumentNullException(nameof(content)); var impl = GetTabContentImpl(content); - Debug2.Assert(!(impl is null)); + Debug2.Assert(impl is not null); if (impl is null) return; TabGroup.SetFocus(impl); diff --git a/dnSpy/dnSpy/ToolWindows/ToolWindowGroupService.cs b/dnSpy/dnSpy/ToolWindows/ToolWindowGroupService.cs index ef0bc4d71d..89b8a6bd7b 100644 --- a/dnSpy/dnSpy/ToolWindows/ToolWindowGroupService.cs +++ b/dnSpy/dnSpy/ToolWindows/ToolWindowGroupService.cs @@ -89,7 +89,7 @@ public ToolWindowGroupService(ITabGroupService tabGroupService) { static ToolWindowContent? GetToolWindowContent(ITabContent? selected) => ((TabContentImpl?)selected)?.Content; void TabGroupService_TabSelectionChanged(object? sender, TabSelectedEventArgs e) { - if (!(e.Selected is null)) { + if (e.Selected is not null) { Debug.Assert(e.TabGroup.ActiveTabContent == e.Selected); e.TabGroup.SetFocus(e.Selected); } @@ -111,7 +111,7 @@ public void Close(IToolWindowGroup group) { tabGroupService.Close(impl.TabGroup); } - public bool CloseAllTabsCanExecute => !(tabGroupService.ActiveTabGroup is null) && tabGroupService.ActiveTabGroup.TabContents.Count() > 1 && tabGroupService.CloseAllTabsCanExecute; + public bool CloseAllTabsCanExecute => tabGroupService.ActiveTabGroup is not null && tabGroupService.ActiveTabGroup.TabContents.Count() > 1 && tabGroupService.CloseAllTabsCanExecute; public void CloseAllTabs() => tabGroupService.CloseAllTabs(); public bool NewHorizontalTabGroupCanExecute => tabGroupService.NewHorizontalTabGroupCanExecute; public void NewHorizontalTabGroup() => tabGroupService.NewHorizontalTabGroup(a => new ToolWindowGroup(this, a)); diff --git a/dnSpy/dnSpy/ToolWindows/ToolWindowService.cs b/dnSpy/dnSpy/ToolWindows/ToolWindowService.cs index 6adb266a85..af3a3ff89d 100644 --- a/dnSpy/dnSpy/ToolWindows/ToolWindowService.cs +++ b/dnSpy/dnSpy/ToolWindows/ToolWindowService.cs @@ -70,11 +70,11 @@ public GuidObjectsProvider(InitializeContextMenuHelper owner, ITabGroup tabGroup } public IEnumerable GetGuidObjects(GuidObjectsProviderArgs args) { - Debug2.Assert(!(owner.ToolWindowGroupService is null)); - if (!(owner.ToolWindowGroupService is null)) { + Debug2.Assert(owner.ToolWindowGroupService is not null); + if (owner.ToolWindowGroupService is not null) { var twg = owner.ToolWindowGroupService.GetToolWindowGroup(tabGroup); - Debug2.Assert(!(twg is null)); - if (!(twg is null)) + Debug2.Assert(twg is not null); + if (twg is not null) yield return new GuidObject(MenuConstants.GUIDOBJ_TOOLWINDOWGROUP_GUID, twg); } } diff --git a/dnSpy/dnSpy/TreeView/TreeViewImpl.cs b/dnSpy/dnSpy/TreeView/TreeViewImpl.cs index 39e7664a33..40ed14750b 100644 --- a/dnSpy/dnSpy/TreeView/TreeViewImpl.cs +++ b/dnSpy/dnSpy/TreeView/TreeViewImpl.cs @@ -113,9 +113,9 @@ void SharpTreeView_SelectionChanged(object? sender, SelectionChangedEventArgs e) static TreeViewSelectionChangedEventArgs Convert(SelectionChangedEventArgs e) { TreeNodeData[]? added = null, removed = null; - if (!(e.AddedItems is null)) + if (e.AddedItems is not null) added = Convert(e.AddedItems); - if (!(e.RemovedItems is null)) + if (e.RemovedItems is not null) removed = Convert(e.RemovedItems); return new TreeViewSelectionChangedEventArgs(added, removed); } @@ -128,7 +128,7 @@ static TreeNodeData[] Convert(System.Collections.IEnumerable list) => TreeNodeImpl Create(TreeNodeData data) { Debug2.Assert(data.TreeNode is null); var impl = new TreeNodeImpl(this, data); - if (!(treeViewListener is null)) + if (treeViewListener is not null) treeViewListener.OnEvent(this, new TreeViewListenerEventArgs(TreeViewListenerEvent.NodeCreated, impl)); data.Initialize(); if (!impl.LazyLoading) @@ -171,7 +171,7 @@ int GetInsertIndex(TreeNodeImpl owner, TreeNodeImpl impl, ITreeNodeGroup group) if (children.Count >= 1) { var lastData = children[children.Count - 1].Data; var lastGroup = lastData.TreeNodeGroup; - if (!(lastGroup is null)) { + if (lastGroup is not null) { int x = Compare(impl.Data, lastData, group, lastGroup); if (x > 0) return children.Count; @@ -217,7 +217,7 @@ public void SelectItems(IEnumerable items) { sharpTreeView.SelectedItem = null; else sharpTreeView.SelectedItems.Clear(); - var nodes = items.Where(a => !(a is null)).Select(a => (TreeNodeImpl)a.TreeNode).ToArray(); + var nodes = items.Where(a => a is not null).Select(a => (TreeNodeImpl)a.TreeNode).ToArray(); if (nodes.Length > 0) { sharpTreeView.FocusNode(nodes[0].Node); sharpTreeView.SelectedItem = nodes[0].Node; @@ -267,7 +267,7 @@ public void RefreshAllNodes() { if (node is null) return null; var impl = node.TreeNode as TreeNodeImpl; - Debug2.Assert(!(impl is null)); + Debug2.Assert(impl is not null); return impl?.Node; } @@ -300,7 +300,7 @@ bool CollapseUnusedNodes(IEnumerable nodes, HashSet internal Brush GetNodeForegroundBrush() { var brush = sharpTreeView.TryFindResource(foregroundBrushResourceKey) as Brush; - Debug2.Assert(!(brush is null)); + Debug2.Assert(brush is not null); return brush; } }