From 172aac18481d079d77a8545c9ac45fdb64387433 Mon Sep 17 00:00:00 2001 From: buyaa-n Date: Mon, 3 Feb 2020 10:11:04 -0800 Subject: [PATCH] Annotate System.ComponentModel.Composition for nullable (#1842) * Annotating System.ComponentModel.Composition for nullable --- .../Diagnostics/DebuggerTraceWriter.cs | 2 +- .../ref/System.ComponentModel.Composition.cs | 272 +++++++++--------- .../System.ComponentModel.Composition.csproj | 1 + .../Microsoft/Internal/AttributeServices.cs | 4 +- .../CollectionServices.CollectionOfObject.cs | 2 +- .../Collections/CollectionServices.cs | 45 ++- .../Collections/WeakReferenceCollection.cs | 4 +- .../Microsoft/Internal/ContractServices.cs | 5 +- .../Microsoft/Internal/GenerationServices.cs | 87 +++--- .../Microsoft/Internal/ReflectionInvoke.cs | 10 +- .../Microsoft/Internal/ReflectionServices.cs | 26 +- .../src/Microsoft/Internal/Requires.cs | 12 +- .../System.ComponentModel.Composition.csproj | 2 + .../AttributedExportDefinition.cs | 13 +- .../AttributedModelDiscovery.cs | 8 +- .../AttributedPartCreationInfo.cs | 42 ++- .../Composition/AttributedModelServices.cs | 10 +- .../CatalogReflectionContextAttribute.cs | 4 +- .../Composition/ChangeRejectedException.cs | 14 +- .../CompositionContractMismatchException.cs | 8 +- .../Composition/CompositionError.cs | 36 +-- .../CompositionErrorDebuggerProxy.cs | 4 +- .../Composition/CompositionException.cs | 24 +- .../Composition/CompositionResult.cs | 8 +- .../Composition/CompositionResultOfT.cs | 9 +- .../Composition/ConstraintServices.cs | 22 +- .../Composition/ContractNameServices.cs | 18 +- .../Composition/ErrorBuilder.cs | 2 +- .../Composition/ExportAttribute.cs | 16 +- .../Composition/ExportMetadataAttribute.cs | 4 +- .../Composition/ExportServices.cs | 42 ++- .../Composition/Hosting/AggregateCatalog.cs | 18 +- .../Hosting/AggregateExportProvider.cs | 20 +- .../Composition/Hosting/ApplicationCatalog.cs | 12 +- .../Composition/Hosting/AssemblyCatalog.cs | 8 +- .../Composition/Hosting/AtomicComposition.cs | 40 +-- .../Hosting/AtomicCompositionExtensions.cs | 8 +- .../CatalogExportProvider.CatalogExport.cs | 8 +- .../CatalogExportProvider.FactoryExport.cs | 8 +- ...atalogExportProvider.ScopeFactoryExport.cs | 16 +- .../CatalogExportProvider.ScopeManager.cs | 14 +- .../Hosting/CatalogExportProvider.cs | 128 ++++----- .../ComposablePartCatalogChangeEventArgs.cs | 4 +- .../ComposablePartCatalogCollection.cs | 40 ++- .../Hosting/ComposablePartExportProvider.cs | 28 +- ...ositionBatch.SingleExportComposablePart.cs | 4 +- .../Composition/Hosting/CompositionBatch.cs | 2 +- ...ositionContainer.CompositionServiceShim.cs | 2 +- .../Hosting/CompositionContainer.cs | 77 +++-- .../Composition/Hosting/CompositionLock.cs | 8 +- .../Hosting/CompositionScopeDefinition.cs | 26 +- .../Composition/Hosting/CompositionService.cs | 6 +- .../Hosting/CompositionServices.cs | 63 ++-- ...ryCatalog.DirectoryCatalogDebuggerProxy.cs | 2 +- .../Composition/Hosting/DirectoryCatalog.cs | 44 ++- .../ExportProvider.GetExportOverrides.cs | 69 ++--- .../Composition/Hosting/ExportProvider.cs | 20 +- .../Hosting/ExportsChangeEventArgs.cs | 6 +- .../FilteredCatalog.DependenciesTraversal.cs | 14 +- .../FilteredCatalog.DependentsTraversal.cs | 14 +- ...Catalog.IComposablePartCatalogTraversal.cs | 3 +- .../Hosting/FilteredCatalog.Traversal.cs | 11 +- .../Composition/Hosting/FilteredCatalog.cs | 31 +- .../INotifyComposablePartCatalogChanged.cs | 4 +- .../Hosting/ImportEngine.EngineContext.cs | 8 +- .../Hosting/ImportEngine.PartManager.cs | 21 +- .../ImportEngine.RecompositionManager.cs | 11 +- .../Composition/Hosting/ImportEngine.cs | 81 +++--- .../ImportSourceImportDefinitionHelpers.cs | 8 +- .../Composition/Hosting/ScopingExtensions.cs | 3 +- .../Composition/Hosting/TypeCatalog.cs | 21 +- .../Composition/IAttributedImport.cs | 4 +- .../Composition/ImportAttribute.cs | 16 +- .../ImportCardinalityMismatchException.cs | 8 +- ...rdinalityMismatchExceptionDebuggerProxy.cs | 2 +- .../Composition/ImportManyAttribute.cs | 16 +- .../Composition/InheritedExportAttribute.cs | 12 +- .../Composition/MetadataServices.cs | 19 +- .../Composition/MetadataViewGenerator.cs | 30 +- .../MetadataViewImplementationAttribute.cs | 4 +- .../Composition/MetadataViewProvider.cs | 19 +- .../Composition/PartMetadataAttribute.cs | 4 +- .../Composition/Primitives/ComposablePart.cs | 4 +- .../Primitives/ComposablePartCatalog.cs | 11 +- .../Primitives/ComposablePartDefinition.cs | 11 +- .../Primitives/ComposablePartException.cs | 22 +- .../ComposablePartExceptionDebuggerProxy.cs | 4 +- .../Primitives/CompositionElement.cs | 12 +- .../CompositionElementDebuggerProxy.cs | 4 +- .../CompositionElementExtensions.cs | 13 +- .../ContractBasedImportDefinition.cs | 17 +- .../Composition/Primitives/Export.cs | 22 +- .../Primitives/ExportDefinition.cs | 8 +- .../Primitives/ExportedDelegate.cs | 8 +- .../Primitives/ICompositionElement.cs | 2 +- .../Primitives/ImportDefinition.cs | 14 +- .../Primitives/PrimitivesServices.cs | 18 +- .../SerializableCompositionElement.cs | 12 +- .../DisposableReflectionComposablePart.cs | 5 +- .../ExportfactoryCreator.LifetimeContext.cs | 10 +- .../ReflectionModel/ExportfactoryCreator.cs | 14 +- .../ReflectionModel/ExportingMember.cs | 6 +- .../ReflectionModel/GenericServices.cs | 10 +- .../GenericSpecializationPartCreationInfo.cs | 102 ++++--- .../IReflectionPartCreationInfo.cs | 4 +- .../Composition/ReflectionModel/ImportType.cs | 19 +- .../ReflectionModel/ImportingItem.cs | 15 +- .../ReflectionModel/ImportingMember.cs | 26 +- .../ReflectionModel/LazyMemberInfo.cs | 16 +- .../PartCreatorExportDefinition.cs | 13 +- .../PartCreatorMemberImportDefinition.cs | 2 +- .../PartCreatorParameterImportDefinition.cs | 2 +- .../ReflectionComposablePart.cs | 91 +++--- .../ReflectionComposablePartDefinition.cs | 63 ++-- .../ReflectionModel/ReflectionExtensions.cs | 8 +- .../ReflectionModel/ReflectionField.cs | 4 +- .../ReflectionImportDefinition.cs | 12 +- .../ReflectionModel/ReflectionItem.cs | 2 +- .../ReflectionModel/ReflectionMember.cs | 4 +- .../ReflectionMemberExportDefinition.cs | 10 +- .../ReflectionMemberImportDefinition.cs | 8 +- .../ReflectionModel/ReflectionMethod.cs | 4 +- .../ReflectionModelServices.cs | 104 +++---- .../ReflectionModel/ReflectionParameter.cs | 2 +- .../ReflectionParameterImportDefinition.cs | 8 +- .../ReflectionModel/ReflectionProperty.cs | 26 +- .../ReflectionModel/ReflectionType.cs | 2 +- .../ReflectionWritableMember.cs | 2 +- 128 files changed, 1257 insertions(+), 1320 deletions(-) diff --git a/src/libraries/Common/src/System/Composition/Diagnostics/DebuggerTraceWriter.cs b/src/libraries/Common/src/System/Composition/Diagnostics/DebuggerTraceWriter.cs index ad0652e21ac..5584f56dac8 100644 --- a/src/libraries/Common/src/System/Composition/Diagnostics/DebuggerTraceWriter.cs +++ b/src/libraries/Common/src/System/Composition/Diagnostics/DebuggerTraceWriter.cs @@ -10,7 +10,7 @@ namespace System.Composition.Diagnostics { internal sealed class DebuggerTraceWriter : TraceWriter { - private static readonly string s_sourceName = typeof(DebuggerTraceWriter).Assembly.GetName().Name; + private static readonly string s_sourceName = typeof(DebuggerTraceWriter).Assembly.GetName().Name!; public override bool CanWriteInformation { diff --git a/src/libraries/System.ComponentModel.Composition/ref/System.ComponentModel.Composition.cs b/src/libraries/System.ComponentModel.Composition/ref/System.ComponentModel.Composition.cs index 4d71f316a50..1ade2b50735 100644 --- a/src/libraries/System.ComponentModel.Composition/ref/System.ComponentModel.Composition.cs +++ b/src/libraries/System.ComponentModel.Composition/ref/System.ComponentModel.Composition.cs @@ -24,12 +24,12 @@ namespace System.ComponentModel.Composition public static System.ComponentModel.Composition.Primitives.ComposablePart CreatePart(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition, object attributedPart) { throw null; } public static System.ComponentModel.Composition.Primitives.ComposablePart CreatePart(object attributedPart) { throw null; } public static System.ComponentModel.Composition.Primitives.ComposablePart CreatePart(object attributedPart, System.Reflection.ReflectionContext reflectionContext) { throw null; } - public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Type type, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; } - public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Type type, System.ComponentModel.Composition.Primitives.ICompositionElement origin, bool ensureIsDiscoverable) { throw null; } + public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Type type, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; } + public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Type type, System.ComponentModel.Composition.Primitives.ICompositionElement? origin, bool ensureIsDiscoverable) { throw null; } public static bool Exports(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, System.Type contractType) { throw null; } public static bool Exports(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part) { throw null; } public static string GetContractName(System.Type type) { throw null; } - public static TMetadataView GetMetadataView(System.Collections.Generic.IDictionary metadata) { throw null; } + public static TMetadataView GetMetadataView(System.Collections.Generic.IDictionary metadata) { throw null; } public static string GetTypeIdentity(System.Reflection.MethodInfo method) { throw null; } public static string GetTypeIdentity(System.Type type) { throw null; } public static bool Imports(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part, System.Type contractType) { throw null; } @@ -48,35 +48,35 @@ namespace System.ComponentModel.Composition public partial class ChangeRejectedException : System.ComponentModel.Composition.CompositionException { public ChangeRejectedException() { } - public ChangeRejectedException(System.Collections.Generic.IEnumerable errors) { } - public ChangeRejectedException(string message) { } - public ChangeRejectedException(string message, System.Exception innerException) { } + public ChangeRejectedException(System.Collections.Generic.IEnumerable? errors) { } + public ChangeRejectedException(string? message) { } + public ChangeRejectedException(string? message, System.Exception? innerException) { } public override string Message { get { throw null; } } } public partial class CompositionContractMismatchException : System.Exception { public CompositionContractMismatchException() { } protected CompositionContractMismatchException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public CompositionContractMismatchException(string message) { } - public CompositionContractMismatchException(string message, System.Exception innerException) { } + public CompositionContractMismatchException(string? message) { } + public CompositionContractMismatchException(string? message, System.Exception? innerException) { } } public partial class CompositionError { - public CompositionError(string message) { } - public CompositionError(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element) { } - public CompositionError(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element, System.Exception exception) { } - public CompositionError(string message, System.Exception exception) { } + public CompositionError(string? message) { } + public CompositionError(string? message, System.ComponentModel.Composition.Primitives.ICompositionElement? element) { } + public CompositionError(string? message, System.ComponentModel.Composition.Primitives.ICompositionElement? element, System.Exception? exception) { } + public CompositionError(string? message, System.Exception? exception) { } public string Description { get { throw null; } } - public System.ComponentModel.Composition.Primitives.ICompositionElement Element { get { throw null; } } - public System.Exception Exception { get { throw null; } } + public System.ComponentModel.Composition.Primitives.ICompositionElement? Element { get { throw null; } } + public System.Exception? Exception { get { throw null; } } public override string ToString() { throw null; } } public partial class CompositionException : System.Exception { public CompositionException() { } - public CompositionException(System.Collections.Generic.IEnumerable errors) { } - public CompositionException(string message) { } - public CompositionException(string message, System.Exception innerException) { } + public CompositionException(System.Collections.Generic.IEnumerable? errors) { } + public CompositionException(string? message) { } + public CompositionException(string? message, System.Exception? innerException) { } public System.Collections.ObjectModel.ReadOnlyCollection Errors { get { throw null; } } public override string Message { get { throw null; } } public System.Collections.ObjectModel.ReadOnlyCollection RootCauses { get { throw null; } } @@ -91,11 +91,11 @@ namespace System.ComponentModel.Composition public partial class ExportAttribute : System.Attribute { public ExportAttribute() { } - public ExportAttribute(string contractName) { } - public ExportAttribute(string contractName, System.Type contractType) { } - public ExportAttribute(System.Type contractType) { } - public string ContractName { get { throw null; } } - public System.Type ContractType { get { throw null; } } + public ExportAttribute(string? contractName) { } + public ExportAttribute(string? contractName, System.Type? contractType) { } + public ExportAttribute(System.Type? contractType) { } + public string? ContractName { get { throw null; } } + public System.Type? ContractType { get { throw null; } } } public partial class ExportFactory { @@ -116,10 +116,10 @@ namespace System.ComponentModel.Composition [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Field | System.AttributeTargets.Interface | System.AttributeTargets.Method | System.AttributeTargets.Property, AllowMultiple=true, Inherited=false)] public sealed partial class ExportMetadataAttribute : System.Attribute { - public ExportMetadataAttribute(string name, object value) { } + public ExportMetadataAttribute(string? name, object? value) { } public bool IsMultiple { get { throw null; } set { } } public string Name { get { throw null; } } - public object Value { get { throw null; } } + public object? Value { get { throw null; } } } public partial interface ICompositionService { @@ -129,13 +129,13 @@ namespace System.ComponentModel.Composition public partial class ImportAttribute : System.Attribute { public ImportAttribute() { } - public ImportAttribute(string contractName) { } - public ImportAttribute(string contractName, System.Type contractType) { } - public ImportAttribute(System.Type contractType) { } + public ImportAttribute(string? contractName) { } + public ImportAttribute(string? contractName, System.Type? contractType) { } + public ImportAttribute(System.Type? contractType) { } public bool AllowDefault { get { throw null; } set { } } public bool AllowRecomposition { get { throw null; } set { } } - public string ContractName { get { throw null; } } - public System.Type ContractType { get { throw null; } } + public string? ContractName { get { throw null; } } + public System.Type? ContractType { get { throw null; } } public System.ComponentModel.Composition.CreationPolicy RequiredCreationPolicy { get { throw null; } set { } } public System.ComponentModel.Composition.ImportSource Source { get { throw null; } set { } } } @@ -143,8 +143,8 @@ namespace System.ComponentModel.Composition { public ImportCardinalityMismatchException() { } protected ImportCardinalityMismatchException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public ImportCardinalityMismatchException(string message) { } - public ImportCardinalityMismatchException(string message, System.Exception innerException) { } + public ImportCardinalityMismatchException(string? message) { } + public ImportCardinalityMismatchException(string? message, System.Exception? innerException) { } } [System.AttributeUsageAttribute(System.AttributeTargets.Constructor, AllowMultiple=false, Inherited=false)] public partial class ImportingConstructorAttribute : System.Attribute @@ -155,12 +155,12 @@ namespace System.ComponentModel.Composition public partial class ImportManyAttribute : System.Attribute { public ImportManyAttribute() { } - public ImportManyAttribute(string contractName) { } - public ImportManyAttribute(string contractName, System.Type contractType) { } - public ImportManyAttribute(System.Type contractType) { } + public ImportManyAttribute(string? contractName) { } + public ImportManyAttribute(string? contractName, System.Type? contractType) { } + public ImportManyAttribute(System.Type? contractType) { } public bool AllowRecomposition { get { throw null; } set { } } - public string ContractName { get { throw null; } } - public System.Type ContractType { get { throw null; } } + public string? ContractName { get { throw null; } } + public System.Type? ContractType { get { throw null; } } public System.ComponentModel.Composition.CreationPolicy RequiredCreationPolicy { get { throw null; } set { } } public System.ComponentModel.Composition.ImportSource Source { get { throw null; } set { } } } @@ -174,9 +174,9 @@ namespace System.ComponentModel.Composition public partial class InheritedExportAttribute : System.ComponentModel.Composition.ExportAttribute { public InheritedExportAttribute() { } - public InheritedExportAttribute(string contractName) { } - public InheritedExportAttribute(string contractName, System.Type contractType) { } - public InheritedExportAttribute(System.Type contractType) { } + public InheritedExportAttribute(string? contractName) { } + public InheritedExportAttribute(string? contractName, System.Type? contractType) { } + public InheritedExportAttribute(System.Type? contractType) { } } public partial interface IPartImportsSatisfiedNotification { @@ -190,8 +190,8 @@ namespace System.ComponentModel.Composition [System.AttributeUsageAttribute(System.AttributeTargets.Interface, AllowMultiple=false, Inherited=false)] public sealed partial class MetadataViewImplementationAttribute : System.Attribute { - public MetadataViewImplementationAttribute(System.Type implementationType) { } - public System.Type ImplementationType { get { throw null; } } + public MetadataViewImplementationAttribute(System.Type? implementationType) { } + public System.Type? ImplementationType { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public sealed partial class PartCreationPolicyAttribute : System.Attribute @@ -202,9 +202,9 @@ namespace System.ComponentModel.Composition [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true, Inherited=false)] public sealed partial class PartMetadataAttribute : System.Attribute { - public PartMetadataAttribute(string name, object value) { } + public PartMetadataAttribute(string? name, object? value) { } public string Name { get { throw null; } } - public object Value { get { throw null; } } + public object? Value { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)] public sealed partial class PartNotDiscoverableAttribute : System.Attribute @@ -217,11 +217,11 @@ namespace System.ComponentModel.Composition.Hosting public partial class AggregateCatalog : System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.ComponentModel.Composition.Hosting.INotifyComposablePartCatalogChanged { public AggregateCatalog() { } - public AggregateCatalog(System.Collections.Generic.IEnumerable catalogs) { } - public AggregateCatalog(params System.ComponentModel.Composition.Primitives.ComposablePartCatalog[] catalogs) { } + public AggregateCatalog(System.Collections.Generic.IEnumerable? catalogs) { } + public AggregateCatalog(params System.ComponentModel.Composition.Primitives.ComposablePartCatalog[]? catalogs) { } public System.Collections.Generic.ICollection Catalogs { get { throw null; } } - public event System.EventHandler Changed { add { } remove { } } - public event System.EventHandler Changing { add { } remove { } } + public event System.EventHandler? Changed { add { } remove { } } + public event System.EventHandler? Changing { add { } remove { } } protected override void Dispose(bool disposing) { } public override System.Collections.Generic.IEnumerator GetEnumerator() { throw null; } public override System.Collections.Generic.IEnumerable> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; } @@ -230,12 +230,12 @@ namespace System.ComponentModel.Composition.Hosting } public partial class AggregateExportProvider : System.ComponentModel.Composition.Hosting.ExportProvider, System.IDisposable { - public AggregateExportProvider(System.Collections.Generic.IEnumerable providers) { } - public AggregateExportProvider(params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { } + public AggregateExportProvider(System.Collections.Generic.IEnumerable? providers) { } + public AggregateExportProvider(params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { } public System.Collections.ObjectModel.ReadOnlyCollection Providers { get { throw null; } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } - protected override System.Collections.Generic.IEnumerable GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; } + protected override System.Collections.Generic.IEnumerable GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { throw null; } } public partial class ApplicationCatalog : System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.ComponentModel.Composition.Primitives.ICompositionElement { @@ -244,7 +244,7 @@ namespace System.ComponentModel.Composition.Hosting public ApplicationCatalog(System.Reflection.ReflectionContext reflectionContext) { } public ApplicationCatalog(System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { } string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } } - System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } } + System.ComponentModel.Composition.Primitives.ICompositionElement? System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } } protected override void Dispose(bool disposing) { } public override System.Collections.Generic.IEnumerator GetEnumerator() { throw null; } public override System.Collections.Generic.IEnumerable> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; } @@ -262,7 +262,7 @@ namespace System.ComponentModel.Composition.Hosting public AssemblyCatalog(string codeBase, System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { } public System.Reflection.Assembly Assembly { get { throw null; } } string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } } - System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } } + System.ComponentModel.Composition.Primitives.ICompositionElement? System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } } protected override void Dispose(bool disposing) { } public override System.Collections.Generic.IEnumerator GetEnumerator() { throw null; } public override System.Collections.Generic.IEnumerable> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; } @@ -271,15 +271,15 @@ namespace System.ComponentModel.Composition.Hosting public partial class AtomicComposition : System.IDisposable { public AtomicComposition() { } - public AtomicComposition(System.ComponentModel.Composition.Hosting.AtomicComposition outerAtomicComposition) { } + public AtomicComposition(System.ComponentModel.Composition.Hosting.AtomicComposition? outerAtomicComposition) { } public void AddCompleteAction(System.Action completeAction) { } public void AddRevertAction(System.Action revertAction) { } public void Complete() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } - public void SetValue(object key, object value) { } - public bool TryGetValue(object key, bool localAtomicCompositionOnly, out T value) { throw null; } - public bool TryGetValue(object key, out T value) { throw null; } + public void SetValue(object key, object? value) { } + public bool TryGetValue(object key, bool localAtomicCompositionOnly, [System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T value) { throw null; } + public bool TryGetValue(object key, [System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T value) { throw null; } } public partial class CatalogExportProvider : System.ComponentModel.Composition.Hosting.ExportProvider, System.IDisposable { @@ -287,10 +287,11 @@ namespace System.ComponentModel.Composition.Hosting public CatalogExportProvider(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, bool isThreadSafe) { } public CatalogExportProvider(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions) { } public System.ComponentModel.Composition.Primitives.ComposablePartCatalog Catalog { get { throw null; } } - public System.ComponentModel.Composition.Hosting.ExportProvider SourceProvider { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.DisallowNullAttribute] + public System.ComponentModel.Composition.Hosting.ExportProvider? SourceProvider { get { throw null; } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } - protected override System.Collections.Generic.IEnumerable GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; } + protected override System.Collections.Generic.IEnumerable GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { throw null; } } public static partial class CatalogExtensions { @@ -298,9 +299,9 @@ namespace System.ComponentModel.Composition.Hosting } public partial class ComposablePartCatalogChangeEventArgs : System.EventArgs { - public ComposablePartCatalogChangeEventArgs(System.Collections.Generic.IEnumerable addedDefinitions, System.Collections.Generic.IEnumerable removedDefinitions, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { } + public ComposablePartCatalogChangeEventArgs(System.Collections.Generic.IEnumerable addedDefinitions, System.Collections.Generic.IEnumerable removedDefinitions, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { } public System.Collections.Generic.IEnumerable AddedDefinitions { get { throw null; } } - public System.ComponentModel.Composition.Hosting.AtomicComposition AtomicComposition { get { throw null; } } + public System.ComponentModel.Composition.Hosting.AtomicComposition? AtomicComposition { get { throw null; } } public System.Collections.Generic.IEnumerable RemovedDefinitions { get { throw null; } } } public partial class ComposablePartExportProvider : System.ComponentModel.Composition.Hosting.ExportProvider, System.IDisposable @@ -308,16 +309,17 @@ namespace System.ComponentModel.Composition.Hosting public ComposablePartExportProvider() { } public ComposablePartExportProvider(bool isThreadSafe) { } public ComposablePartExportProvider(System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions) { } - public System.ComponentModel.Composition.Hosting.ExportProvider SourceProvider { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.DisallowNullAttribute] + public System.ComponentModel.Composition.Hosting.ExportProvider? SourceProvider { get { throw null; } set { } } public void Compose(System.ComponentModel.Composition.Hosting.CompositionBatch batch) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } - protected override System.Collections.Generic.IEnumerable GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; } + protected override System.Collections.Generic.IEnumerable? GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { throw null; } } public partial class CompositionBatch { public CompositionBatch() { } - public CompositionBatch(System.Collections.Generic.IEnumerable partsToAdd, System.Collections.Generic.IEnumerable partsToRemove) { } + public CompositionBatch(System.Collections.Generic.IEnumerable? partsToAdd, System.Collections.Generic.IEnumerable? partsToRemove) { } public System.Collections.ObjectModel.ReadOnlyCollection PartsToAdd { get { throw null; } } public System.Collections.ObjectModel.ReadOnlyCollection PartsToRemove { get { throw null; } } public System.ComponentModel.Composition.Primitives.ComposablePart AddExport(System.ComponentModel.Composition.Primitives.Export export) { throw null; } @@ -336,17 +338,17 @@ namespace System.ComponentModel.Composition.Hosting public partial class CompositionContainer : System.ComponentModel.Composition.Hosting.ExportProvider, System.ComponentModel.Composition.ICompositionService, System.IDisposable { public CompositionContainer() { } - public CompositionContainer(System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { } - public CompositionContainer(params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { } - public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, bool isThreadSafe, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { } - public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { } - public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { } - public System.ComponentModel.Composition.Primitives.ComposablePartCatalog Catalog { get { throw null; } } + public CompositionContainer(System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions, params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { } + public CompositionContainer(params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { } + public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog? catalog, bool isThreadSafe, params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { } + public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog? catalog, System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions, params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { } + public CompositionContainer(System.ComponentModel.Composition.Primitives.ComposablePartCatalog? catalog, params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { } + public System.ComponentModel.Composition.Primitives.ComposablePartCatalog? Catalog { get { throw null; } } public System.Collections.ObjectModel.ReadOnlyCollection Providers { get { throw null; } } public void Compose(System.ComponentModel.Composition.Hosting.CompositionBatch batch) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } - protected override System.Collections.Generic.IEnumerable GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; } + protected override System.Collections.Generic.IEnumerable? GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { throw null; } public void ReleaseExport(System.ComponentModel.Composition.Primitives.Export export) { } public void ReleaseExports(System.Collections.Generic.IEnumerable exports) { } public void ReleaseExports(System.Collections.Generic.IEnumerable> exports) { } @@ -369,8 +371,8 @@ namespace System.ComponentModel.Composition.Hosting public CompositionScopeDefinition(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.Collections.Generic.IEnumerable children, System.Collections.Generic.IEnumerable publicSurface) { } public virtual System.Collections.Generic.IEnumerable Children { get { throw null; } } public virtual System.Collections.Generic.IEnumerable PublicSurface { get { throw null; } } - public event System.EventHandler Changed { add { } remove { } } - public event System.EventHandler Changing { add { } remove { } } + public event System.EventHandler? Changed { add { } remove { } } + public event System.EventHandler? Changing { add { } remove { } } protected override void Dispose(bool disposing) { } public override System.Collections.Generic.IEnumerator GetEnumerator() { throw null; } public override System.Collections.Generic.IEnumerable> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; } @@ -398,9 +400,9 @@ namespace System.ComponentModel.Composition.Hosting public string Path { get { throw null; } } public string SearchPattern { get { throw null; } } string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } } - System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } } - public event System.EventHandler Changed { add { } remove { } } - public event System.EventHandler Changing { add { } remove { } } + System.ComponentModel.Composition.Primitives.ICompositionElement? System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } } + public event System.EventHandler? Changed { add { } remove { } } + public event System.EventHandler? Changing { add { } remove { } } protected override void Dispose(bool disposing) { } public override System.Collections.Generic.IEnumerator GetEnumerator() { throw null; } public override System.Collections.Generic.IEnumerable> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; } @@ -412,35 +414,39 @@ namespace System.ComponentModel.Composition.Hosting public abstract partial class ExportProvider { protected ExportProvider() { } - public event System.EventHandler ExportsChanged { add { } remove { } } - public event System.EventHandler ExportsChanging { add { } remove { } } + public event System.EventHandler? ExportsChanged { add { } remove { } } + public event System.EventHandler? ExportsChanging { add { } remove { } } + [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute] public T GetExportedValueOrDefault() { throw null; } - public T GetExportedValueOrDefault(string contractName) { throw null; } + [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute] + public T GetExportedValueOrDefault(string? contractName) { throw null; } public System.Collections.Generic.IEnumerable GetExportedValues() { throw null; } - public System.Collections.Generic.IEnumerable GetExportedValues(string contractName) { throw null; } + public System.Collections.Generic.IEnumerable GetExportedValues(string? contractName) { throw null; } + [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute] public T GetExportedValue() { throw null; } - public T GetExportedValue(string contractName) { throw null; } + [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute] + public T GetExportedValue(string? contractName) { throw null; } public System.Collections.Generic.IEnumerable GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; } - public System.Collections.Generic.IEnumerable GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; } - public System.Collections.Generic.IEnumerable> GetExports(System.Type type, System.Type metadataViewType, string contractName) { throw null; } - protected abstract System.Collections.Generic.IEnumerable GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition); + public System.Collections.Generic.IEnumerable GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { throw null; } + public System.Collections.Generic.IEnumerable> GetExports(System.Type type, System.Type? metadataViewType, string? contractName) { throw null; } + protected abstract System.Collections.Generic.IEnumerable? GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition); public System.Collections.Generic.IEnumerable> GetExports() { throw null; } - public System.Collections.Generic.IEnumerable> GetExports(string contractName) { throw null; } + public System.Collections.Generic.IEnumerable> GetExports(string? contractName) { throw null; } public System.Collections.Generic.IEnumerable> GetExports() { throw null; } - public System.Collections.Generic.IEnumerable> GetExports(string contractName) { throw null; } - public System.Lazy GetExport() { throw null; } - public System.Lazy GetExport(string contractName) { throw null; } - public System.Lazy GetExport() { throw null; } - public System.Lazy GetExport(string contractName) { throw null; } + public System.Collections.Generic.IEnumerable> GetExports(string? contractName) { throw null; } + public System.Lazy? GetExport() { throw null; } + public System.Lazy? GetExport(string? contractName) { throw null; } + public System.Lazy? GetExport() { throw null; } + public System.Lazy? GetExport(string? contractName) { throw null; } protected virtual void OnExportsChanged(System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs e) { } protected virtual void OnExportsChanging(System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs e) { } - public bool TryGetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition, out System.Collections.Generic.IEnumerable exports) { throw null; } + public bool TryGetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition, out System.Collections.Generic.IEnumerable? exports) { throw null; } } public partial class ExportsChangeEventArgs : System.EventArgs { - public ExportsChangeEventArgs(System.Collections.Generic.IEnumerable addedExports, System.Collections.Generic.IEnumerable removedExports, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { } + public ExportsChangeEventArgs(System.Collections.Generic.IEnumerable addedExports, System.Collections.Generic.IEnumerable removedExports, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { } public System.Collections.Generic.IEnumerable AddedExports { get { throw null; } } - public System.ComponentModel.Composition.Hosting.AtomicComposition AtomicComposition { get { throw null; } } + public System.ComponentModel.Composition.Hosting.AtomicComposition? AtomicComposition { get { throw null; } } public System.Collections.Generic.IEnumerable ChangedContractNames { get { throw null; } } public System.Collections.Generic.IEnumerable RemovedExports { get { throw null; } } } @@ -448,8 +454,8 @@ namespace System.ComponentModel.Composition.Hosting { public FilteredCatalog(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.Func filter) { } public System.ComponentModel.Composition.Hosting.FilteredCatalog Complement { get { throw null; } } - public event System.EventHandler Changed { add { } remove { } } - public event System.EventHandler Changing { add { } remove { } } + public event System.EventHandler? Changed { add { } remove { } } + public event System.EventHandler? Changing { add { } remove { } } protected override void Dispose(bool disposing) { } public override System.Collections.Generic.IEnumerator GetEnumerator() { throw null; } public override System.Collections.Generic.IEnumerable> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; } @@ -467,15 +473,15 @@ namespace System.ComponentModel.Composition.Hosting public ImportEngine(System.ComponentModel.Composition.Hosting.ExportProvider sourceProvider, System.ComponentModel.Composition.Hosting.CompositionOptions compositionOptions) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } - public void PreviewImports(System.ComponentModel.Composition.Primitives.ComposablePart part, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { } - public void ReleaseImports(System.ComponentModel.Composition.Primitives.ComposablePart part, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { } + public void PreviewImports(System.ComponentModel.Composition.Primitives.ComposablePart part, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { } + public void ReleaseImports(System.ComponentModel.Composition.Primitives.ComposablePart part, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { } public void SatisfyImports(System.ComponentModel.Composition.Primitives.ComposablePart part) { } public void SatisfyImportsOnce(System.ComponentModel.Composition.Primitives.ComposablePart part) { } } public partial interface INotifyComposablePartCatalogChanged { - event System.EventHandler Changed; - event System.EventHandler Changing; + event System.EventHandler? Changed; + event System.EventHandler? Changing; } public static partial class ScopingExtensions { @@ -494,7 +500,7 @@ namespace System.ComponentModel.Composition.Hosting public TypeCatalog(System.Collections.Generic.IEnumerable types, System.Reflection.ReflectionContext reflectionContext, System.ComponentModel.Composition.Primitives.ICompositionElement definitionOrigin) { } public TypeCatalog(params System.Type[] types) { } string System.ComponentModel.Composition.Primitives.ICompositionElement.DisplayName { get { throw null; } } - System.ComponentModel.Composition.Primitives.ICompositionElement System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } } + System.ComponentModel.Composition.Primitives.ICompositionElement? System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } } protected override void Dispose(bool disposing) { } public override System.Collections.Generic.IEnumerator GetEnumerator() { throw null; } public override string ToString() { throw null; } @@ -507,9 +513,9 @@ namespace System.ComponentModel.Composition.Primitives protected ComposablePart() { } public abstract System.Collections.Generic.IEnumerable ExportDefinitions { get; } public abstract System.Collections.Generic.IEnumerable ImportDefinitions { get; } - public virtual System.Collections.Generic.IDictionary Metadata { get { throw null; } } + public virtual System.Collections.Generic.IDictionary Metadata { get { throw null; } } public virtual void Activate() { } - public abstract object GetExportedValue(System.ComponentModel.Composition.Primitives.ExportDefinition definition); + public abstract object? GetExportedValue(System.ComponentModel.Composition.Primitives.ExportDefinition definition); public abstract void SetImport(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.Collections.Generic.IEnumerable exports); } public abstract partial class ComposablePartCatalog : System.Collections.Generic.IEnumerable, System.Collections.IEnumerable, System.IDisposable @@ -528,61 +534,61 @@ namespace System.ComponentModel.Composition.Primitives protected ComposablePartDefinition() { } public abstract System.Collections.Generic.IEnumerable ExportDefinitions { get; } public abstract System.Collections.Generic.IEnumerable ImportDefinitions { get; } - public virtual System.Collections.Generic.IDictionary Metadata { get { throw null; } } + public virtual System.Collections.Generic.IDictionary Metadata { get { throw null; } } public abstract System.ComponentModel.Composition.Primitives.ComposablePart CreatePart(); } public partial class ComposablePartException : System.Exception { public ComposablePartException() { } protected ComposablePartException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public ComposablePartException(string message) { } - public ComposablePartException(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element) { } - public ComposablePartException(string message, System.ComponentModel.Composition.Primitives.ICompositionElement element, System.Exception innerException) { } - public ComposablePartException(string message, System.Exception innerException) { } - public System.ComponentModel.Composition.Primitives.ICompositionElement Element { get { throw null; } } + public ComposablePartException(string? message) { } + public ComposablePartException(string? message, System.ComponentModel.Composition.Primitives.ICompositionElement? element) { } + public ComposablePartException(string? message, System.ComponentModel.Composition.Primitives.ICompositionElement? element, System.Exception? innerException) { } + public ComposablePartException(string? message, System.Exception? innerException) { } + public System.ComponentModel.Composition.Primitives.ICompositionElement? Element { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class ContractBasedImportDefinition : System.ComponentModel.Composition.Primitives.ImportDefinition { protected ContractBasedImportDefinition() { } - public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy) { } - public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary metadata) { } + public ContractBasedImportDefinition(string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy) { } + public ContractBasedImportDefinition(string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary metadata) { } public override System.Linq.Expressions.Expression> Constraint { get { throw null; } } public virtual System.ComponentModel.Composition.CreationPolicy RequiredCreationPolicy { get { throw null; } } public virtual System.Collections.Generic.IEnumerable> RequiredMetadata { get { throw null; } } - public virtual string RequiredTypeIdentity { get { throw null; } } + public virtual string? RequiredTypeIdentity { get { throw null; } } public override bool IsConstraintSatisfiedBy(System.ComponentModel.Composition.Primitives.ExportDefinition exportDefinition) { throw null; } public override string ToString() { throw null; } } public partial class Export { protected Export() { } - public Export(System.ComponentModel.Composition.Primitives.ExportDefinition definition, System.Func exportedValueGetter) { } - public Export(string contractName, System.Collections.Generic.IDictionary metadata, System.Func exportedValueGetter) { } - public Export(string contractName, System.Func exportedValueGetter) { } + public Export(System.ComponentModel.Composition.Primitives.ExportDefinition definition, System.Func exportedValueGetter) { } + public Export(string contractName, System.Collections.Generic.IDictionary? metadata, System.Func exportedValueGetter) { } + public Export(string contractName, System.Func exportedValueGetter) { } public virtual System.ComponentModel.Composition.Primitives.ExportDefinition Definition { get { throw null; } } - public System.Collections.Generic.IDictionary Metadata { get { throw null; } } - public object Value { get { throw null; } } - protected virtual object GetExportedValueCore() { throw null; } + public System.Collections.Generic.IDictionary Metadata { get { throw null; } } + public object? Value { get { throw null; } } + protected virtual object? GetExportedValueCore() { throw null; } } public partial class ExportDefinition { protected ExportDefinition() { } - public ExportDefinition(string contractName, System.Collections.Generic.IDictionary metadata) { } + public ExportDefinition(string contractName, System.Collections.Generic.IDictionary? metadata) { } public virtual string ContractName { get { throw null; } } - public virtual System.Collections.Generic.IDictionary Metadata { get { throw null; } } + public virtual System.Collections.Generic.IDictionary Metadata { get { throw null; } } public override string ToString() { throw null; } } public partial class ExportedDelegate { protected ExportedDelegate() { } - public ExportedDelegate(object instance, System.Reflection.MethodInfo method) { } - public virtual System.Delegate CreateDelegate(System.Type delegateType) { throw null; } + public ExportedDelegate(object? instance, System.Reflection.MethodInfo method) { } + public virtual System.Delegate? CreateDelegate(System.Type delegateType) { throw null; } } public partial interface ICompositionElement { string DisplayName { get; } - System.ComponentModel.Composition.Primitives.ICompositionElement Origin { get; } + System.ComponentModel.Composition.Primitives.ICompositionElement? Origin { get; } } public enum ImportCardinality { @@ -593,14 +599,14 @@ namespace System.ComponentModel.Composition.Primitives public partial class ImportDefinition { protected ImportDefinition() { } - public ImportDefinition(System.Linq.Expressions.Expression> constraint, string contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { } - public ImportDefinition(System.Linq.Expressions.Expression> constraint, string contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.Collections.Generic.IDictionary metadata) { } + public ImportDefinition(System.Linq.Expressions.Expression> constraint, string? contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { } + public ImportDefinition(System.Linq.Expressions.Expression> constraint, string? contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.Collections.Generic.IDictionary? metadata) { } public virtual System.ComponentModel.Composition.Primitives.ImportCardinality Cardinality { get { throw null; } } public virtual System.Linq.Expressions.Expression> Constraint { get { throw null; } } public virtual string ContractName { get { throw null; } } public virtual bool IsPrerequisite { get { throw null; } } public virtual bool IsRecomposable { get { throw null; } } - public virtual System.Collections.Generic.IDictionary Metadata { get { throw null; } } + public virtual System.Collections.Generic.IDictionary Metadata { get { throw null; } } public virtual bool IsConstraintSatisfiedBy(System.ComponentModel.Composition.Primitives.ExportDefinition exportDefinition) { throw null; } public override string ToString() { throw null; } } @@ -615,7 +621,7 @@ namespace System.ComponentModel.Composition.ReflectionModel public LazyMemberInfo(System.Reflection.MemberTypes memberType, System.Func accessorsCreator) { throw null; } public LazyMemberInfo(System.Reflection.MemberTypes memberType, params System.Reflection.MemberInfo[] accessors) { throw null; } public System.Reflection.MemberTypes MemberType { get { throw null; } } - public override bool Equals(object obj) { throw null; } + public override bool Equals(object? obj) { throw null; } public System.Reflection.MemberInfo[] GetAccessors() { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo left, System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo right) { throw null; } @@ -623,13 +629,13 @@ namespace System.ComponentModel.Composition.ReflectionModel } public static partial class ReflectionModelServices { - public static System.ComponentModel.Composition.Primitives.ExportDefinition CreateExportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo exportingMember, string contractName, System.Lazy> metadata, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; } - public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPreRequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; } - public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; } - public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; } - public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy parameter, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; } - public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy parameter, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; } - public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Lazy partType, bool isDisposalRequired, System.Lazy> imports, System.Lazy> exports, System.Lazy> metadata, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; } + public static System.ComponentModel.Composition.Primitives.ExportDefinition CreateExportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo exportingMember, string contractName, System.Lazy> metadata, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; } + public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPreRequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; } + public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; } + public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo importingMember, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; } + public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy parameter, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; } + public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy parameter, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; } + public static System.ComponentModel.Composition.Primitives.ComposablePartDefinition CreatePartDefinition(System.Lazy partType, bool isDisposalRequired, System.Lazy>? imports, System.Lazy>? exports, System.Lazy>? metadata, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; } public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition GetExportFactoryProductImportDefinition(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; } public static System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo GetExportingMember(System.ComponentModel.Composition.Primitives.ExportDefinition exportDefinition) { throw null; } public static System.ComponentModel.Composition.ReflectionModel.LazyMemberInfo GetImportingMember(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; } @@ -638,6 +644,6 @@ namespace System.ComponentModel.Composition.ReflectionModel public static bool IsDisposalRequired(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition) { throw null; } public static bool IsExportFactoryImportDefinition(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; } public static bool IsImportingParameter(System.ComponentModel.Composition.Primitives.ImportDefinition importDefinition) { throw null; } - public static bool TryMakeGenericPartDefinition(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition, System.Collections.Generic.IEnumerable genericParameters, out System.ComponentModel.Composition.Primitives.ComposablePartDefinition specialization) { throw null; } + public static bool TryMakeGenericPartDefinition(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition, System.Collections.Generic.IEnumerable genericParameters, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.ComponentModel.Composition.Primitives.ComposablePartDefinition? specialization) { throw null; } } } diff --git a/src/libraries/System.ComponentModel.Composition/ref/System.ComponentModel.Composition.csproj b/src/libraries/System.ComponentModel.Composition/ref/System.ComponentModel.Composition.csproj index 974e475345d..6a72da4b53f 100644 --- a/src/libraries/System.ComponentModel.Composition/ref/System.ComponentModel.Composition.csproj +++ b/src/libraries/System.ComponentModel.Composition/ref/System.ComponentModel.Composition.csproj @@ -1,6 +1,7 @@ netstandard2.0-Debug;netstandard2.0-Release + enable diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/AttributeServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/AttributeServices.cs index 8f9ec5aee11..a95ca29d735 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/AttributeServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/AttributeServices.cs @@ -19,12 +19,12 @@ namespace Microsoft.Internal return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit); } - public static T GetFirstAttribute(this ICustomAttributeProvider attributeProvider) where T : class + public static T? GetFirstAttribute(this ICustomAttributeProvider attributeProvider) where T : class { return GetAttributes(attributeProvider).FirstOrDefault(); } - public static T GetFirstAttribute(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class + public static T? GetFirstAttribute(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class { return GetAttributes(attributeProvider, inherit).FirstOrDefault(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs index 82dc72392dc..f50a231616f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs @@ -39,7 +39,7 @@ namespace Microsoft.Internal.Collections Type collectionType = typeof(CollectionOfObject<>).MakeGenericType(underlyingItemType); - return (ICollection)Activator.CreateInstance(collectionType, collectionObject); + return (ICollection)Activator.CreateInstance(collectionType, collectionObject)!; } private class CollectionOfObjectList : ICollection diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs index be8239c7b7c..71a388e0e25 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs @@ -31,15 +31,14 @@ namespace Microsoft.Internal.Collections return false; } - public static Type GetEnumerableElementType(Type type) + public static Type? GetEnumerableElementType(Type type) { if (type.UnderlyingSystemType == StringType || !IEnumerableType.IsAssignableFrom(type)) { return null; } - Type closedType; - if (ReflectionServices.TryGetGenericInterfaceType(type, IEnumerableOfTType, out closedType)) + if (ReflectionServices.TryGetGenericInterfaceType(type, IEnumerableOfTType, out Type? closedType)) { return closedType.GetGenericArguments()[0]; } @@ -47,10 +46,9 @@ namespace Microsoft.Internal.Collections return null; } - public static Type GetCollectionElementType(Type type) + public static Type? GetCollectionElementType(Type type) { - Type closedType; - if (ReflectionServices.TryGetGenericInterfaceType(type, ICollectionOfTType, out closedType)) + if (ReflectionServices.TryGetGenericInterfaceType(type, ICollectionOfTType, out Type? closedType)) { return closedType.GetGenericArguments()[0]; } @@ -68,7 +66,7 @@ namespace Microsoft.Internal.Collections return new ReadOnlyCollection(source.AsArray()); } - public static IEnumerable ConcatAllowingNull(this IEnumerable source, IEnumerable second) + public static IEnumerable? ConcatAllowingNull(this IEnumerable? source, IEnumerable? second) { if (second == null || !second.FastAny()) { @@ -83,7 +81,7 @@ namespace Microsoft.Internal.Collections return source.Concat(second); } - public static ICollection ConcatAllowingNull(this ICollection source, ICollection second) + public static ICollection? ConcatAllowingNull(this ICollection? source, ICollection? second) { if (second == null || (second.Count == 0)) { @@ -101,7 +99,7 @@ namespace Microsoft.Internal.Collections return result; } - public static List FastAppendToListAllowNulls(this List source, IEnumerable second) + public static List? FastAppendToListAllowNulls(this List? source, IEnumerable? second) { if (second == null) { @@ -115,8 +113,7 @@ namespace Microsoft.Internal.Collections } // if the second is List, and contains very few elements there's no need for AddRange - List secondAsList = second as List; - if (secondAsList != null) + if (second is List secondAsList) { if (secondAsList.Count == 0) { @@ -135,7 +132,7 @@ namespace Microsoft.Internal.Collections } - private static List FastAppendToListAllowNulls(this List source, T value) + private static List FastAppendToListAllowNulls(this List? source, T value) { if (source == null) { @@ -146,9 +143,9 @@ namespace Microsoft.Internal.Collections return source; } - public static List FastAppendToListAllowNulls( - this List source, T value, - IEnumerable second) + public static List? FastAppendToListAllowNulls( + this List? source, T value, + IEnumerable? second) { if (second == null) { @@ -177,8 +174,7 @@ namespace Microsoft.Internal.Collections } // Cast to ICollection instead of ICollection for performance reasons. - ICollection collection = source as ICollection; - if (collection != null) + if (source is ICollection collection) { return collection.Count switch { @@ -213,8 +209,7 @@ namespace Microsoft.Internal.Collections // sources. // Cast to ICollection instead of ICollection for performance reasons. - ICollection collection = source as ICollection; - if (collection != null) + if (source is ICollection collection) { return collection.Count > 0; } @@ -238,9 +233,7 @@ namespace Microsoft.Internal.Collections public static T[] AsArray(this IEnumerable enumerable) { - T[] array = enumerable as T[]; - - if (array != null) + if (enumerable is T[] array) { return array; } @@ -250,9 +243,7 @@ namespace Microsoft.Internal.Collections public static List AsList(this IEnumerable enumerable) { - List list = enumerable as List; - - if (list != null) + if (enumerable is List list) { return list; } @@ -269,7 +260,7 @@ namespace Microsoft.Internal.Collections for (int i = 0; i < thisArray.Length; i++) { - if (!thisArray[i].Equals(thatArray[i])) + if (!thisArray[i]!.Equals(thatArray[i])) { return false; } @@ -287,7 +278,7 @@ namespace Microsoft.Internal.Collections for (int i = 0; i < thisList.Count; i++) { - if (!thisList[i].Equals(thatList[i])) + if (!thisList[i]!.Equals(thatList[i])) { return false; } diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/WeakReferenceCollection.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/WeakReferenceCollection.cs index e335ec2ad13..599d1cdad4d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/WeakReferenceCollection.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/WeakReferenceCollection.cs @@ -68,9 +68,7 @@ namespace Microsoft.Internal.Collections foreach (var weakItem in _items) { - T item = weakItem.Target as T; - - if (item != null) + if (weakItem.Target is T item) { aliveItems.Add(item); } diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ContractServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ContractServices.cs index 32e5cd720b7..307d7925754 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ContractServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ContractServices.cs @@ -9,7 +9,7 @@ namespace Microsoft.Internal { internal static class ContractServices { - public static bool TryCast(Type contractType, object value, out object result) + public static bool TryCast(Type contractType, object? value, out object? result) { if (value == null) { @@ -25,8 +25,7 @@ namespace Microsoft.Internal // We couldn't cast see if a delegate works for us. if (typeof(Delegate).IsAssignableFrom(contractType)) { - ExportedDelegate exportedDelegate = value as ExportedDelegate; - if (exportedDelegate != null) + if (value is ExportedDelegate exportedDelegate) { result = exportedDelegate.CreateDelegate(contractType.UnderlyingSystemType); return (result != null); diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs index e827568a9be..d1b6ca35fd4 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs @@ -15,29 +15,29 @@ namespace Microsoft.Internal internal static class GenerationServices { // Type.GetTypeFromHandle - private static readonly MethodInfo _typeGetTypeFromHandleMethod = typeof(Type).GetMethod("GetTypeFromHandle"); + private static readonly MethodInfo s_typeGetTypeFromHandleMethod = typeof(Type).GetMethod("GetTypeFromHandle")!; // typeofs are pretty expensive, so we cache them statically - private static readonly Type TypeType = typeof(System.Type); - private static readonly Type StringType = typeof(string); - private static readonly Type CharType = typeof(char); - private static readonly Type BooleanType = typeof(bool); - private static readonly Type ByteType = typeof(byte); - private static readonly Type SByteType = typeof(sbyte); - private static readonly Type Int16Type = typeof(short); - private static readonly Type UInt16Type = typeof(ushort); - private static readonly Type Int32Type = typeof(int); - private static readonly Type UInt32Type = typeof(uint); - private static readonly Type Int64Type = typeof(long); - private static readonly Type UInt64Type = typeof(ulong); - private static readonly Type DoubleType = typeof(double); - private static readonly Type SingleType = typeof(float); - private static readonly Type IEnumerableTypeofT = typeof(System.Collections.Generic.IEnumerable<>); - private static readonly Type IEnumerableType = typeof(System.Collections.IEnumerable); - - private static readonly MethodInfo ExceptionGetData = typeof(Exception).GetProperty("Data").GetGetMethod(); - private static readonly MethodInfo DictionaryAdd = typeof(IDictionary).GetMethod("Add"); - private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes); + private static readonly Type s_typeType = typeof(System.Type); + private static readonly Type s_stringType = typeof(string); + private static readonly Type s_charType = typeof(char); + private static readonly Type s_booleanType = typeof(bool); + private static readonly Type s_byteType = typeof(byte); + private static readonly Type s_sByteType = typeof(sbyte); + private static readonly Type s_int16Type = typeof(short); + private static readonly Type s_uInt16Type = typeof(ushort); + private static readonly Type s_int32Type = typeof(int); + private static readonly Type s_uInt32Type = typeof(uint); + private static readonly Type s_int64Type = typeof(long); + private static readonly Type s_uInt64Type = typeof(ulong); + private static readonly Type s_doubleType = typeof(double); + private static readonly Type s_singleType = typeof(float); + private static readonly Type s_iEnumerableTypeofT = typeof(System.Collections.Generic.IEnumerable<>); + private static readonly Type s_iEnumerableType = typeof(System.Collections.IEnumerable); + + private static readonly MethodInfo ExceptionGetData = typeof(Exception).GetProperty("Data")!.GetGetMethod()!; + private static readonly MethodInfo DictionaryAdd = typeof(IDictionary).GetMethod("Add")!; + private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes)!; public static ILGenerator CreateGeneratorForPublicConstructor(this TypeBuilder typeBuilder, Type[] ctrArgumentTypes) { @@ -67,7 +67,7 @@ namespace Microsoft.Internal /// Everything else cannot be represented as literals /// /// - public static void LoadValue(this ILGenerator ilGenerator, object value) + public static void LoadValue(this ILGenerator ilGenerator, object? value) { Debug.Assert(ilGenerator != null); @@ -95,28 +95,28 @@ namespace Microsoft.Internal // // Generate IL depending on the valueType - this is messier than it should ever be, but sadly necessary // - if (valueType == GenerationServices.StringType) + if (valueType == GenerationServices.s_stringType) { // we need to check for strings before enumerables, because strings are IEnumerable ilGenerator.LoadString((string)rawValue); } - else if (GenerationServices.TypeType.IsAssignableFrom(valueType)) + else if (GenerationServices.s_typeType.IsAssignableFrom(valueType)) { ilGenerator.LoadTypeOf((Type)rawValue); } - else if (GenerationServices.IEnumerableType.IsAssignableFrom(valueType)) + else if (GenerationServices.s_iEnumerableType.IsAssignableFrom(valueType)) { // NOTE : strings and dictionaries are also enumerables, but we have already handled those ilGenerator.LoadEnumerable((IEnumerable)rawValue); } else if ( - (valueType == GenerationServices.CharType) || - (valueType == GenerationServices.BooleanType) || - (valueType == GenerationServices.ByteType) || - (valueType == GenerationServices.SByteType) || - (valueType == GenerationServices.Int16Type) || - (valueType == GenerationServices.UInt16Type) || - (valueType == GenerationServices.Int32Type) + (valueType == GenerationServices.s_charType) || + (valueType == GenerationServices.s_booleanType) || + (valueType == GenerationServices.s_byteType) || + (valueType == GenerationServices.s_sByteType) || + (valueType == GenerationServices.s_int16Type) || + (valueType == GenerationServices.s_uInt16Type) || + (valueType == GenerationServices.s_int32Type) ) { // NOTE : Everything that is 32 bit or less uses ldc.i4. We need to pass int32, even if the actual types is shorter - this is IL memory model @@ -125,29 +125,29 @@ namespace Microsoft.Internal // We have a special case for that next ilGenerator.LoadInt((int)Convert.ChangeType(rawValue, typeof(int), CultureInfo.InvariantCulture)); } - else if (valueType == GenerationServices.UInt32Type) + else if (valueType == GenerationServices.s_uInt32Type) { // NOTE : This one is a bit tricky. Ldc.I4 takes an Int32 as an argument, although it really treats it as a 32bit number // That said, some UInt32 values are larger that Int32.MaxValue, so the Convert call above will fail, which is why // we need to treat this case individually and cast to uint, and then - unchecked - to int. ilGenerator.LoadInt(unchecked((int)((uint)rawValue))); } - else if (valueType == GenerationServices.Int64Type) + else if (valueType == GenerationServices.s_int64Type) { ilGenerator.LoadLong((long)rawValue); } - else if (valueType == GenerationServices.UInt64Type) + else if (valueType == GenerationServices.s_uInt64Type) { // NOTE : This one is a bit tricky. Ldc.I8 takes an Int64 as an argument, although it really treats it as a 64bit number // That said, some UInt64 values are larger that Int64.MaxValue, so the direct case we use above (or Convert, for that matter)will fail, which is why // we need to treat this case individually and cast to ulong, and then - unchecked - to long. ilGenerator.LoadLong(unchecked((long)((ulong)rawValue))); } - else if (valueType == GenerationServices.SingleType) + else if (valueType == GenerationServices.s_singleType) { ilGenerator.LoadFloat((float)rawValue); } - else if (valueType == GenerationServices.DoubleType) + else if (valueType == GenerationServices.s_doubleType) { ilGenerator.LoadDouble((double)rawValue); } @@ -251,9 +251,8 @@ namespace Microsoft.Internal } // We load enumerable as an array - this is the most compact and efficient way of representing it - Type elementType = null; - Type closedType = null; - if (ReflectionServices.TryGetGenericInterfaceType(enumerable.GetType(), GenerationServices.IEnumerableTypeofT, out closedType)) + Type elementType; + if (ReflectionServices.TryGetGenericInterfaceType(enumerable.GetType(), GenerationServices.s_iEnumerableTypeofT, out Type? closedType)) { elementType = closedType.GetGenericArguments()[0]; } @@ -273,7 +272,7 @@ namespace Microsoft.Internal ilGenerator.Emit(OpCodes.Stloc, generatedArrayLocal); int index = 0; - foreach (object value in enumerable) + foreach (object? value in enumerable) { // //array[] = value; @@ -283,7 +282,7 @@ namespace Microsoft.Internal ilGenerator.LoadValue(value); if (GenerationServices.IsBoxingRequiredForValue(value) && !elementType.IsValueType) { - ilGenerator.Emit(OpCodes.Box, value.GetType()); + ilGenerator.Emit(OpCodes.Box, value!.GetType()); } ilGenerator.Emit(OpCodes.Stelem, elementType); index++; @@ -292,7 +291,7 @@ namespace Microsoft.Internal ilGenerator.Emit(OpCodes.Ldloc, generatedArrayLocal); } - private static bool IsBoxingRequiredForValue(object value) + private static bool IsBoxingRequiredForValue(object? value) { if (value == null) { @@ -357,7 +356,7 @@ namespace Microsoft.Internal //typeofs() translate into ldtoken and Type::GetTypeFromHandle call ilGenerator.Emit(OpCodes.Ldtoken, type); - ilGenerator.EmitCall(OpCodes.Call, GenerationServices._typeGetTypeFromHandleMethod, null); + ilGenerator.EmitCall(OpCodes.Call, GenerationServices.s_typeGetTypeFromHandleMethod, null); } } } diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionInvoke.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionInvoke.cs index 45caab23ae2..393ca2a782e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionInvoke.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionInvoke.cs @@ -9,27 +9,27 @@ namespace Microsoft.Internal { internal static class ReflectionInvoke { - public static object SafeCreateInstance(this Type type, params object[] arguments) + public static object? SafeCreateInstance(this Type type, params object?[]? arguments) { return Activator.CreateInstance(type, arguments); } - public static object SafeInvoke(this ConstructorInfo constructor, params object[] arguments) + public static object SafeInvoke(this ConstructorInfo constructor, params object?[]? arguments) { return constructor.Invoke(arguments); } - public static object SafeInvoke(this MethodInfo method, object instance, params object[] arguments) + public static object? SafeInvoke(this MethodInfo method, object? instance, params object?[]? arguments) { return method.Invoke(instance, arguments); } - public static object SafeGetValue(this FieldInfo field, object instance) + public static object? SafeGetValue(this FieldInfo field, object? instance) { return field.GetValue(instance); } - public static void SafeSetValue(this FieldInfo field, object instance, object value) + public static void SafeSetValue(this FieldInfo field, object? instance, object? value) { field.SetValue(instance, value); } diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs index 74a01cb4820..a0b896bc262 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs @@ -7,6 +7,8 @@ using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Reflection; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics; namespace Microsoft.Internal { @@ -14,27 +16,29 @@ namespace Microsoft.Internal { public static Assembly Assembly(this MemberInfo member) { - Type type = member as Type; - if (type != null) + if (member is Type type) { return type.Assembly; } + Debug.Assert(member.DeclaringType != null); return member.DeclaringType.Assembly; } public static bool IsVisible(this ConstructorInfo constructor) { - return constructor.DeclaringType.IsVisible && constructor.IsPublic; + return constructor.DeclaringType!.IsVisible && constructor.IsPublic; } public static bool IsVisible(this FieldInfo field) { + Debug.Assert(field.DeclaringType != null); return field.DeclaringType.IsVisible && field.IsPublic; } public static bool IsVisible(this MethodInfo method) { + Debug.Assert(method.DeclaringType != null); if (!method.DeclaringType.IsVisible) return false; @@ -54,7 +58,7 @@ namespace Microsoft.Internal return true; } - public static string GetDisplayName(Type declaringType, string name) + public static string GetDisplayName(Type declaringType, string? name) { if (declaringType == null) { @@ -79,10 +83,10 @@ namespace Microsoft.Internal return AttributedModelServices.GetTypeIdentity(((Type)member)); } - return GetDisplayName(member.DeclaringType, member.Name); + return GetDisplayName(member.DeclaringType!, member.Name); } - internal static bool TryGetGenericInterfaceType(Type instanceType, Type targetOpenInterfaceType, out Type targetClosedInterfaceType) + internal static bool TryGetGenericInterfaceType(Type instanceType, Type targetOpenInterfaceType, [NotNullWhen(true)] out Type? targetClosedInterfaceType) { // The interface must be open if (!targetOpenInterfaceType.IsInterface || @@ -107,7 +111,7 @@ namespace Microsoft.Internal // more expensive implementation of GetInterface, this does mean that we're // takign the chance that there aren't too many types which implement multiple // interfaces by the same name... - Type targetInterface = instanceType.GetInterface(targetOpenInterfaceType.Name, false); + Type? targetInterface = instanceType.GetInterface(targetOpenInterfaceType.Name, false); if (targetInterface != null && targetInterface.UnderlyingSystemType.GetGenericTypeDefinition() == targetOpenInterfaceType.UnderlyingSystemType) { @@ -133,7 +137,8 @@ namespace Microsoft.Internal { IEnumerable declaredMethods = type.GetDeclaredMethods(); - Type baseType = type.BaseType; + Type? baseType = type.BaseType; + Debug.Assert(baseType != null); if (baseType.UnderlyingSystemType != typeof(object)) { return declaredMethods.Concat(baseType.GetAllMethods()); @@ -156,7 +161,8 @@ namespace Microsoft.Internal { IEnumerable declaredFields = type.GetDeclaredFields(); - Type baseType = type.BaseType; + Type? baseType = type.BaseType; + Debug.Assert(baseType != null); if (baseType.UnderlyingSystemType != typeof(object)) { return declaredFields.Concat(baseType.GetAllFields()); @@ -175,7 +181,7 @@ namespace Microsoft.Internal } } - internal static bool HasBaseclassOf(this Type type, Type baseClass) + internal static bool HasBaseclassOf(this Type? type, Type baseClass) { if (type == baseClass) { diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Requires.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Requires.cs index 010856abe42..aab09fa2d72 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Requires.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Requires.cs @@ -22,7 +22,7 @@ namespace Microsoft.Internal } [DebuggerStepThrough] - public static void NullOrNotNullElements(IEnumerable> values, string parameterName) + public static void NullOrNotNullElements(IEnumerable>? values, string parameterName) where TKey : class where TValue : class { @@ -30,14 +30,14 @@ namespace Microsoft.Internal } [DebuggerStepThrough] - public static void NullOrNotNullElements(IEnumerable values, string parameterName) + public static void NullOrNotNullElements(IEnumerable? values, string parameterName) where T : class { NotNullElements(values, parameterName); } [DebuggerStepThrough] - private static void NotNullElements(IEnumerable values, string parameterName) + private static void NotNullElements(IEnumerable? values, string parameterName) where T : class { if (values != null) @@ -53,14 +53,14 @@ namespace Microsoft.Internal } [DebuggerStepThrough] - public static void NullOrNotNullElements(T[] values, string parameterName) + public static void NullOrNotNullElements(T[]? values, string parameterName) where T : class { NotNullElements(values, parameterName); } [DebuggerStepThrough] - private static void NotNullElements(T[] values, string parameterName) + private static void NotNullElements(T[]? values, string parameterName) where T : class { if (values != null) @@ -76,7 +76,7 @@ namespace Microsoft.Internal } [DebuggerStepThrough] - private static void NotNullElements(IEnumerable> values, string parameterName) + private static void NotNullElements(IEnumerable>? values, string parameterName) where TKey : class where TValue : class { diff --git a/src/libraries/System.ComponentModel.Composition/src/System.ComponentModel.Composition.csproj b/src/libraries/System.ComponentModel.Composition/src/System.ComponentModel.Composition.csproj index f7067b40ec7..99aae7aa20f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System.ComponentModel.Composition.csproj +++ b/src/libraries/System.ComponentModel.Composition/src/System.ComponentModel.Composition.csproj @@ -7,6 +7,8 @@ $(NoWarn);CS1573 SR.PlatformNotSupported_ComponentModel_Composition $(NetCoreAppCurrent)-Debug;$(NetCoreAppCurrent)-Release;netcoreapp2.0-Debug;netcoreapp2.0-Release;netstandard2.0-Debug;netstandard2.0-Release + enable + $(NoWarn);nullable diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs index 5dd1e602224..cc83ca44cc0 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs @@ -15,12 +15,12 @@ namespace System.ComponentModel.Composition.AttributedModel private readonly AttributedPartCreationInfo _partCreationInfo; private readonly MemberInfo _member; private readonly ExportAttribute _exportAttribute; - private readonly Type _typeIdentityType; + private readonly Type? _typeIdentityType; - private IDictionary _metadata; + private IDictionary? _metadata; - public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo, MemberInfo member, ExportAttribute exportAttribute, Type typeIdentityType, string contractName) - : base(contractName, (IDictionary)null) + public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo, MemberInfo member, ExportAttribute exportAttribute, Type? typeIdentityType, string contractName) + : base(contractName, (IDictionary?)null) { if (partCreationInfo == null) { @@ -43,14 +43,13 @@ namespace System.ComponentModel.Composition.AttributedModel _typeIdentityType = typeIdentityType; } - public override IDictionary Metadata + public override IDictionary Metadata { get { if (_metadata == null) { - IDictionary metadata; - _member.TryExportMetadataForMember(out metadata); + _member.TryExportMetadataForMember(out IDictionary metadata); string typeIdentity = _exportAttribute.IsContractNameSameAsTypeIdentity() ? ContractName : diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs index d9271be4199..128550ac1cc 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs @@ -14,7 +14,7 @@ namespace System.ComponentModel.Composition.AttributedModel { internal static class AttributedModelDiscovery { - public static ComposablePartDefinition CreatePartDefinitionIfDiscoverable(Type type, ICompositionElement origin) + public static ComposablePartDefinition? CreatePartDefinitionIfDiscoverable(Type type, ICompositionElement? origin) { AttributedPartCreationInfo creationInfo = new AttributedPartCreationInfo(type, null, false, origin); if (!creationInfo.IsPartDiscoverable()) @@ -25,7 +25,7 @@ namespace System.ComponentModel.Composition.AttributedModel return new ReflectionComposablePartDefinition(creationInfo); } - public static ReflectionComposablePartDefinition CreatePartDefinition(Type type, PartCreationPolicyAttribute partCreationPolicy, bool ignoreConstructorImports, ICompositionElement origin) + public static ReflectionComposablePartDefinition CreatePartDefinition(Type type, PartCreationPolicyAttribute? partCreationPolicy, bool ignoreConstructorImports, ICompositionElement? origin) { if (type == null) { @@ -45,7 +45,7 @@ namespace System.ComponentModel.Composition.AttributedModel } // If given an instance then we want to pass the default composition options because we treat it as a shared part - ReflectionComposablePartDefinition definition = AttributedModelDiscovery.CreatePartDefinition(attributedPart.GetType(), PartCreationPolicyAttribute.Shared, true, (ICompositionElement)null); + ReflectionComposablePartDefinition definition = AttributedModelDiscovery.CreatePartDefinition(attributedPart.GetType(), PartCreationPolicyAttribute.Shared, true, (ICompositionElement?)null); return new ReflectionComposablePart(definition, attributedPart); } @@ -69,7 +69,7 @@ namespace System.ComponentModel.Composition.AttributedModel throw new ArgumentException(SR.Format(SR.Argument_ReflectionContextReturnsReflectionOnlyType, nameof(reflectionContext)), nameof(reflectionContext)); } - ReflectionComposablePartDefinition definition = AttributedModelDiscovery.CreatePartDefinition(mappedType, PartCreationPolicyAttribute.Shared, true, (ICompositionElement)null); + ReflectionComposablePartDefinition definition = AttributedModelDiscovery.CreatePartDefinition(mappedType, PartCreationPolicyAttribute.Shared, true, (ICompositionElement?)null); return CreatePart(definition, attributedPart); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs index f3686fc1da6..5ad1a4ec8c2 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs @@ -18,14 +18,14 @@ namespace System.ComponentModel.Composition.AttributedModel { private readonly Type _type; private readonly bool _ignoreConstructorImports = false; - private readonly ICompositionElement _origin; - private PartCreationPolicyAttribute _partCreationPolicy = null; - private ConstructorInfo _constructor; - private IEnumerable _exports; - private IEnumerable _imports; - private HashSet _contractNamesOnNonInterfaces; - - public AttributedPartCreationInfo(Type type, PartCreationPolicyAttribute partCreationPolicy, bool ignoreConstructorImports, ICompositionElement origin) + private readonly ICompositionElement? _origin; + private PartCreationPolicyAttribute? _partCreationPolicy = null; + private ConstructorInfo? _constructor; + private IEnumerable? _exports; + private IEnumerable? _imports; + private HashSet? _contractNamesOnNonInterfaces; + + public AttributedPartCreationInfo(Type type, PartCreationPolicyAttribute? partCreationPolicy, bool ignoreConstructorImports, ICompositionElement? origin) { if (type == null) { @@ -48,7 +48,7 @@ namespace System.ComponentModel.Composition.AttributedModel return new Lazy(GetPartType, LazyThreadSafetyMode.PublicationOnly); } - public ConstructorInfo GetConstructor() + public ConstructorInfo? GetConstructor() { if (_constructor == null && !_ignoreConstructorImports) { @@ -57,7 +57,7 @@ namespace System.ComponentModel.Composition.AttributedModel return _constructor; } - public IDictionary GetMetadata() + public IDictionary GetMetadata() { return _type.GetPartMetadataForType(CreationPolicy); } @@ -65,13 +65,13 @@ namespace System.ComponentModel.Composition.AttributedModel public IEnumerable GetExports() { DiscoverExportsAndImports(); - return _exports; + return _exports!; } public IEnumerable GetImports() { DiscoverExportsAndImports(); - return _imports; + return _imports!; } public bool IsDisposalRequired @@ -160,7 +160,7 @@ namespace System.ComponentModel.Composition.AttributedModel get { return GetDisplayName(); } } - ICompositionElement ICompositionElement.Origin + ICompositionElement? ICompositionElement.Origin { get { return _origin; } } @@ -188,7 +188,7 @@ namespace System.ComponentModel.Composition.AttributedModel } } - private static ConstructorInfo SelectPartConstructor(Type type) + private static ConstructorInfo? SelectPartConstructor(Type type) { if (type == null) { @@ -218,8 +218,8 @@ namespace System.ComponentModel.Composition.AttributedModel } // Select the marked constructor if there is exactly one marked - ConstructorInfo importingConstructor = null; - ConstructorInfo defaultConstructor = null; + ConstructorInfo? importingConstructor = null; + ConstructorInfo? defaultConstructor = null; foreach (ConstructorInfo constructor in constructors) { // an importing constructor found @@ -324,9 +324,7 @@ namespace System.ComponentModel.Composition.AttributedModel private AttributedExportDefinition CreateExportDefinition(MemberInfo member, ExportAttribute exportAttribute) { - string contractName = null; - Type typeIdentityType = null; - member.GetContractInfoFromExport(exportAttribute, out typeIdentityType, out contractName); + member.GetContractInfoFromExport(exportAttribute, out Type? typeIdentityType, out string contractName); return new AttributedExportDefinition(this, member, exportAttribute, typeIdentityType, contractName); } @@ -388,7 +386,7 @@ namespace System.ComponentModel.Composition.AttributedModel // in the hiearchy from most derived to the lowest base type, followed // by all the interfaces that this type implements. - Type currentType = type.BaseType; + Type? currentType = type.BaseType; if (currentType == null) { @@ -436,7 +434,7 @@ namespace System.ComponentModel.Composition.AttributedModel imports.Add(importDefinition); } - ConstructorInfo constructor = GetConstructor(); + ConstructorInfo? constructor = GetConstructor(); if (constructor != null) { @@ -465,7 +463,7 @@ namespace System.ComponentModel.Composition.AttributedModel // Walk up the type chain until you hit object. if (type.BaseType != null) { - Type baseType = type.BaseType; + Type? baseType = type.BaseType; // Stopping at object instead of null to help with performance. It is a noticable performance // gain (~5%) if we don't have to try and pull the attributes we know don't exist on object. diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModelServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModelServices.cs index 31a6dd0a8b8..c218156213f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModelServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModelServices.cs @@ -18,7 +18,7 @@ namespace System.ComponentModel.Composition public static class AttributedModelServices { [SuppressMessage("Microsoft.Design", "CA1004")] - public static TMetadataView GetMetadataView(IDictionary metadata) + public static TMetadataView GetMetadataView(IDictionary metadata) { Requires.NotNull(metadata, nameof(metadata)); @@ -54,19 +54,19 @@ namespace System.ComponentModel.Composition return AttributedModelDiscovery.CreatePart(reflectionComposablePartDefinition, attributedPart); } - public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin) + public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement? origin) { Requires.NotNull(type, nameof(type)); return AttributedModelServices.CreatePartDefinition(type, origin, false); } - public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin, bool ensureIsDiscoverable) + public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement? origin, bool ensureIsDiscoverable) { Requires.NotNull(type, nameof(type)); if (ensureIsDiscoverable) { - return AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(type, origin); + return AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(type, origin)!; } else { @@ -119,7 +119,7 @@ namespace System.ComponentModel.Composition string typeIdentity = AttributedModelServices.GetTypeIdentity(typeof(T)); - IDictionary metadata = new Dictionary(); + IDictionary metadata = new Dictionary(); metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, typeIdentity); return batch.AddExport(new Export(contractName, metadata, () => exportedValue)); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs index dbc9b3e947a..7328e03ddbb 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs @@ -31,10 +31,10 @@ namespace System.ComponentModel.Composition throw new ArgumentNullException(nameof(_reflectionContextType)); } - ReflectionContext reflectionContext = null; + ReflectionContext reflectionContext; try { - reflectionContext = (ReflectionContext)Activator.CreateInstance(_reflectionContextType); + reflectionContext = (ReflectionContext)Activator.CreateInstance(_reflectionContextType)!; } catch (InvalidCastException invalidCastException) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ChangeRejectedException.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ChangeRejectedException.cs index df8056ef3ae..4c4a41665cf 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ChangeRejectedException.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ChangeRejectedException.cs @@ -17,23 +17,23 @@ namespace System.ComponentModel.Composition /// Initializes a new instance of the class. /// public ChangeRejectedException() - : this((string)null, (Exception)null) + : this((string?)null, (Exception?)null) { } /// /// Initializes a new instance of the class. /// - public ChangeRejectedException(string message) - : this(message, (Exception)null) + public ChangeRejectedException(string? message) + : this(message, (Exception?)null) { } /// /// Initializes a new instance of the class. /// - public ChangeRejectedException(string message, Exception innerException) - : base(message, innerException, (IEnumerable)null) + public ChangeRejectedException(string? message, Exception? innerException) + : base(message, innerException, (IEnumerable?)null) { } @@ -41,8 +41,8 @@ namespace System.ComponentModel.Composition /// Initializes a new instance of the class. /// /// List of errors that occured while applying the changes. - public ChangeRejectedException(IEnumerable errors) - : base((string)null, (Exception)null, errors) + public ChangeRejectedException(IEnumerable? errors) + : base((string?)null, (Exception?)null, errors) { } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionContractMismatchException.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionContractMismatchException.cs index ff8aa11698e..14bf9d43f94 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionContractMismatchException.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionContractMismatchException.cs @@ -18,7 +18,7 @@ namespace System.ComponentModel.Composition /// Initializes a new instance of the class. /// public CompositionContractMismatchException() - : this((string)null, (Exception)null) + : this((string?)null, (Exception?)null) { } @@ -31,8 +31,8 @@ namespace System.ComponentModel.Composition /// ; or to set /// the property to its default value. /// - public CompositionContractMismatchException(string message) - : this(message, (Exception)null) + public CompositionContractMismatchException(string? message) + : this(message, (Exception?)null) { } @@ -51,7 +51,7 @@ namespace System.ComponentModel.Composition /// ; or to set /// the property to . /// - public CompositionContractMismatchException(string message, Exception innerException) + public CompositionContractMismatchException(string? message, Exception? innerException) : base(message, innerException) { } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionError.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionError.cs index 51887182907..051b491461f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionError.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionError.cs @@ -16,9 +16,9 @@ namespace System.ComponentModel.Composition { private readonly CompositionErrorId _id; private readonly string _description; - private readonly Exception _exception; + private readonly Exception? _exception; - private readonly ICompositionElement _element; + private readonly ICompositionElement? _element; /// /// Initializes a new instance of the class @@ -29,8 +29,8 @@ namespace System.ComponentModel.Composition /// ; or to set the /// property to an empty string (""). /// - public CompositionError(string message) - : this(CompositionErrorId.Unknown, message, (ICompositionElement)null, (Exception)null) + public CompositionError(string? message) + : this(CompositionErrorId.Unknown, message, (ICompositionElement?)null, (Exception?)null) { } @@ -50,8 +50,8 @@ namespace System.ComponentModel.Composition /// ; or to set the /// property to an empty string (""). /// - public CompositionError(string message, ICompositionElement element) - : this(CompositionErrorId.Unknown, message, element, (Exception)null) + public CompositionError(string? message, ICompositionElement? element) + : this(CompositionErrorId.Unknown, message, element, (Exception?)null) { } @@ -70,8 +70,8 @@ namespace System.ComponentModel.Composition /// ; or to set /// the property to . /// - public CompositionError(string message, Exception exception) - : this(CompositionErrorId.Unknown, message, (ICompositionElement)null, exception) + public CompositionError(string? message, Exception? exception) + : this(CompositionErrorId.Unknown, message, (ICompositionElement?)null, exception) { } @@ -96,12 +96,12 @@ namespace System.ComponentModel.Composition /// ; or to set /// the property to . /// - public CompositionError(string message, ICompositionElement element, Exception exception) + public CompositionError(string? message, ICompositionElement? element, Exception? exception) : this(CompositionErrorId.Unknown, message, element, exception) { } - internal CompositionError(CompositionErrorId id, string description, ICompositionElement element, Exception exception) + internal CompositionError(CompositionErrorId id, string? description, ICompositionElement? element, Exception? exception) { _id = id; _description = description ?? string.Empty; @@ -116,7 +116,7 @@ namespace System.ComponentModel.Composition /// The that is the cause of the /// . The default is . /// - public ICompositionElement Element + public ICompositionElement? Element { get { return _element; } } @@ -140,7 +140,7 @@ namespace System.ComponentModel.Composition /// The that is the underlying cause of the /// . The default is . /// - public Exception Exception + public Exception? Exception { get { return _exception; } } @@ -150,7 +150,7 @@ namespace System.ComponentModel.Composition get { return _id; } } - internal Exception InnerException + internal Exception? InnerException { get { return Exception; } } @@ -166,17 +166,17 @@ namespace System.ComponentModel.Composition return Description; } - internal static CompositionError Create(CompositionErrorId id, string format, params object[] parameters) + internal static CompositionError Create(CompositionErrorId id, string format, params object?[] parameters) { - return Create(id, (ICompositionElement)null, (Exception)null, format, parameters); + return Create(id, (ICompositionElement?)null, (Exception?)null, format, parameters); } - internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, string format, params object[] parameters) + internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, string format, params object?[] parameters) { - return Create(id, element, (Exception)null, format, parameters); + return Create(id, element, (Exception?)null, format, parameters); } - internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, Exception exception, string format, params object[] parameters) + internal static CompositionError Create(CompositionErrorId id, ICompositionElement? element, Exception? exception, string format, params object?[] parameters) { return new CompositionError(id, string.Format(CultureInfo.CurrentCulture, format, parameters), element, exception); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionErrorDebuggerProxy.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionErrorDebuggerProxy.cs index b88721db35e..66ff16fbdc3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionErrorDebuggerProxy.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionErrorDebuggerProxy.cs @@ -23,12 +23,12 @@ namespace System.ComponentModel.Composition get { return _error.Description; } } - public Exception Exception + public Exception? Exception { get { return _error.Exception; } } - public ICompositionElement Element + public ICompositionElement? Element { get { return _error.Element; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionException.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionException.cs index aef115d0d0b..e5341dd3fa3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionException.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionException.cs @@ -28,7 +28,7 @@ namespace System.ComponentModel.Composition /// Initializes a new instance of the class. /// public CompositionException() - : this((string)null, (Exception)null, (IEnumerable)null) + : this((string?)null, (Exception?)null, (IEnumerable?)null) { } @@ -41,8 +41,8 @@ namespace System.ComponentModel.Composition /// ; or to set /// the property to its default value. /// - public CompositionException(string message) - : this(message, (Exception)null, (IEnumerable)null) + public CompositionException(string? message) + : this(message, (Exception?)null, (IEnumerable?)null) { } @@ -61,8 +61,8 @@ namespace System.ComponentModel.Composition /// ; or to set /// the property to . /// - public CompositionException(string message, Exception innerException) - : this(message, innerException, (IEnumerable)null) + public CompositionException(string? message, Exception? innerException) + : this(message, innerException, (IEnumerable?)null) { } @@ -84,12 +84,12 @@ namespace System.ComponentModel.Composition /// /// contains an element that is . /// - public CompositionException(IEnumerable errors) - : this((string)null, (Exception)null, errors) + public CompositionException(IEnumerable? errors) + : this((string?)null, (Exception?)null, errors) { } - internal CompositionException(string message, Exception innerException, IEnumerable errors) + internal CompositionException(string? message, Exception? innerException, IEnumerable? errors) : base(message, innerException) { Requires.NullOrNotNullElements(errors, nameof(errors)); @@ -143,8 +143,7 @@ namespace System.ComponentModel.Composition { if (error.Exception != null) { - var ce = error.Exception as CompositionException; - if (ce != null) + if (error.Exception is CompositionException ce) { if (ce.RootCauses.Count > 0) { @@ -252,7 +251,7 @@ namespace System.ComponentModel.Composition writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_ElementPrefix, element.DisplayName); - while ((element = element.Origin) != null) + while ((element = element.Origin!) != null) { writer.AppendFormat(CultureInfo.CurrentCulture, SR.CompositionException_OriginFormat, SR.CompositionException_OriginSeparator, element.DisplayName); } @@ -310,8 +309,7 @@ namespace System.ComponentModel.Composition private static void VisitException(Exception exception, VisitContext context) { - CompositionException composition = exception as CompositionException; - if (composition != null) + if (exception is CompositionException composition) { VisitCompositionException(composition, context); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResult.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResult.cs index 7f06572f031..4b4859f1937 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResult.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResult.cs @@ -12,14 +12,14 @@ namespace System.ComponentModel.Composition internal struct CompositionResult { public static readonly CompositionResult SucceededResult; - private readonly IEnumerable _errors; + private readonly IEnumerable? _errors; public CompositionResult(params CompositionError[] errors) : this((IEnumerable)errors) { } - public CompositionResult(IEnumerable errors) + public CompositionResult(IEnumerable? errors) { _errors = errors; } @@ -52,7 +52,7 @@ namespace System.ComponentModel.Composition return MergeErrors(new CompositionError[] { error }); } - public CompositionResult MergeErrors(IEnumerable errors) + public CompositionResult MergeErrors(IEnumerable? errors) { return new CompositionResult(_errors.ConcatAllowingNull(errors)); } @@ -67,7 +67,7 @@ namespace System.ComponentModel.Composition ThrowOnErrors(null); } - public void ThrowOnErrors(AtomicComposition atomicComposition) + public void ThrowOnErrors(AtomicComposition? atomicComposition) { if (!Succeeded) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResultOfT.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResultOfT.cs index 7a9ece644c5..12c1339363d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResultOfT.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResultOfT.cs @@ -5,13 +5,14 @@ using System.Collections.Generic; using System.Linq; using Microsoft.Internal.Collections; +using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel.Composition { internal struct CompositionResult { - private readonly IEnumerable _errors; - private readonly T _value; + private readonly IEnumerable? _errors; + [AllowNull] private readonly T _value; public CompositionResult(T value) : this(value, null) @@ -23,12 +24,12 @@ namespace System.ComponentModel.Composition { } - public CompositionResult(IEnumerable errors) + public CompositionResult(IEnumerable? errors) : this(default, errors) { } - internal CompositionResult(T value, IEnumerable errors) + internal CompositionResult([AllowNull] T value, IEnumerable? errors) { _errors = errors; _value = value; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs index 3ee2140a5c0..84f0b978ef8 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs @@ -14,14 +14,14 @@ namespace System.ComponentModel.Composition { // NOTE : these are here as Reflection member search is pretty expensive, and we want that to be done once. // Also, making these static would cause this class to fail loading if we rename members of ExportDefinition. - private static readonly PropertyInfo _exportDefinitionContractNameProperty = typeof(ExportDefinition).GetProperty("ContractName"); - private static readonly PropertyInfo _exportDefinitionMetadataProperty = typeof(ExportDefinition).GetProperty("Metadata"); - private static readonly MethodInfo _metadataContainsKeyMethod = typeof(IDictionary).GetMethod("ContainsKey"); - private static readonly MethodInfo _metadataItemMethod = typeof(IDictionary).GetMethod("get_Item"); - private static readonly MethodInfo _metadataEqualsMethod = typeof(object).GetMethod("Equals", new Type[] { typeof(object) }); - private static readonly MethodInfo _typeIsInstanceOfTypeMethod = typeof(Type).GetMethod("IsInstanceOfType"); - - public static Expression> CreateConstraint(string contractName, string requiredTypeIdentity, IEnumerable> requiredMetadata, CreationPolicy requiredCreationPolicy) + private static readonly PropertyInfo _exportDefinitionContractNameProperty = typeof(ExportDefinition).GetProperty("ContractName")!; + private static readonly PropertyInfo _exportDefinitionMetadataProperty = typeof(ExportDefinition).GetProperty("Metadata")!; + private static readonly MethodInfo _metadataContainsKeyMethod = typeof(IDictionary).GetMethod("ContainsKey")!; + private static readonly MethodInfo _metadataItemMethod = typeof(IDictionary).GetMethod("get_Item")!; + private static readonly MethodInfo _metadataEqualsMethod = typeof(object).GetMethod("Equals", new Type[] { typeof(object) })!; + private static readonly MethodInfo _typeIsInstanceOfTypeMethod = typeof(Type).GetMethod("IsInstanceOfType")!; + + public static Expression> CreateConstraint(string contractName, string? requiredTypeIdentity, IEnumerable> requiredMetadata, CreationPolicy requiredCreationPolicy) { ParameterExpression parameter = Expression.Parameter(typeof(ExportDefinition), "exportDefinition"); @@ -36,7 +36,7 @@ namespace System.ComponentModel.Composition if (requiredMetadata != null) { - Expression metadataConstraintBody = ConstraintServices.CreateMetadataConstraintBody(requiredMetadata, parameter); + Expression? metadataConstraintBody = ConstraintServices.CreateMetadataConstraintBody(requiredMetadata, parameter); if (metadataConstraintBody != null) { constraintBody = Expression.AndAlso(constraintBody, metadataConstraintBody); @@ -67,7 +67,7 @@ namespace System.ComponentModel.Composition Expression.Constant(contractName ?? string.Empty, typeof(string))); } - private static Expression CreateMetadataConstraintBody(IEnumerable> requiredMetadata, ParameterExpression parameter) + private static Expression? CreateMetadataConstraintBody(IEnumerable> requiredMetadata, ParameterExpression parameter) { if (requiredMetadata == null) { @@ -79,7 +79,7 @@ namespace System.ComponentModel.Composition throw new ArgumentNullException(nameof(parameter)); } - Expression body = null; + Expression? body = null; foreach (KeyValuePair requiredMetadataItem in requiredMetadata) { // export.Metadata.ContainsKey() diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs index da738572e57..97bf2e6f06d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs @@ -27,7 +27,7 @@ namespace System.ComponentModel.Composition private const char GenericFormatClosingBracket = '}'; [ThreadStatic] - private static Dictionary typeIdentityCache; + private static Dictionary? typeIdentityCache; private static Dictionary TypeIdentityCache { @@ -49,13 +49,11 @@ namespace System.ComponentModel.Composition throw new ArgumentNullException(nameof(type)); } - string typeIdentity = null; - - if (!TypeIdentityCache.TryGetValue(type, out typeIdentity)) + if (!TypeIdentityCache.TryGetValue(type, out string? typeIdentity)) { if (!type.IsAbstract && type.HasBaseclassOf(typeof(Delegate))) { - MethodInfo method = type.GetMethod("Invoke"); + MethodInfo method = type.GetMethod("Invoke")!; typeIdentity = ContractNameServices.GetTypeIdentityFromMethod(method); } else if (type.IsGenericParameter) @@ -182,7 +180,7 @@ namespace System.ComponentModel.Composition // Type rootElementType = FindArrayElementType(type); WriteType(typeName, rootElementType, formatGenericName); - Type elementType = type; + Type? elementType = type; do { WriteArrayTypeDimensions(typeName, elementType); @@ -195,7 +193,7 @@ namespace System.ComponentModel.Composition // // Writes pointer type e.g * // - WriteType(typeName, type.GetElementType(), formatGenericName); + WriteType(typeName, type.GetElementType()!, formatGenericName); typeName.Append(PointerSymbol); } @@ -204,7 +202,7 @@ namespace System.ComponentModel.Composition // // Writes by ref type e.g & // - WriteType(typeName, type.GetElementType(), formatGenericName); + WriteType(typeName, type.GetElementType()!, formatGenericName); typeName.Append(ReferenceSymbol); } @@ -319,9 +317,9 @@ namespace System.ComponentModel.Composition // // Gets array element type by calling GetElementType() until the element is not an array // - Type elementType = type; + Type? elementType = type; while ((elementType = elementType.GetElementType()) != null && elementType.IsArray) { } - return elementType; + return elementType!; } private static string FindGenericTypeName(string genericName) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs index 315f0524fe7..970bb554bca 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs @@ -49,7 +49,7 @@ namespace System.ComponentModel.Composition CompositionErrorId.ImportEngine_ImportCardinalityMismatch, exception.Message, definition.ToElement(), - (Exception)null); + (Exception?)null); } public static CompositionError CreatePartCannotActivate(ComposablePart part, Exception innerException) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportAttribute.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportAttribute.cs index 6ffafd21b02..ef5cc34ccf9 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportAttribute.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportAttribute.cs @@ -30,7 +30,7 @@ namespace System.ComponentModel.Composition /// /// public ExportAttribute() - : this((string)null, (Type)null) + : this((string?)null, (Type?)null) { } @@ -60,8 +60,8 @@ namespace System.ComponentModel.Composition /// using . /// /// - public ExportAttribute(Type contractType) - : this((string)null, contractType) + public ExportAttribute(Type? contractType) + : this((string?)null, contractType) { } @@ -85,8 +85,8 @@ namespace System.ComponentModel.Composition /// using . /// /// - public ExportAttribute(string contractName) - : this(contractName, (Type)null) + public ExportAttribute(string? contractName) + : this(contractName, (Type?)null) { } @@ -115,7 +115,7 @@ namespace System.ComponentModel.Composition /// using . /// /// - public ExportAttribute(string contractName, Type contractType) + public ExportAttribute(string? contractName, Type? contractType) { ContractName = contractName; ContractType = contractType; @@ -128,7 +128,7 @@ namespace System.ComponentModel.Composition /// A containing the contract name to export the type or member /// marked with this attribute, under. The default value is an empty string (""). /// - public string ContractName { get; private set; } + public string? ContractName { get; private set; } /// /// Get the contract type that is exported by the member that this attribute is attached to. @@ -138,6 +138,6 @@ namespace System.ComponentModel.Composition /// which means that the type will be obtained by looking at the type on /// the member that this export is attached to. /// - public Type ContractType { get; private set; } + public Type? ContractType { get; private set; } } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportMetadataAttribute.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportMetadataAttribute.cs index 6cb62abdcde..e029f4d738b 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportMetadataAttribute.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportMetadataAttribute.cs @@ -25,7 +25,7 @@ namespace System.ComponentModel.Composition /// An containing the metadata value. This can be /// . /// - public ExportMetadataAttribute(string name, object value) + public ExportMetadataAttribute(string? name, object? value) { Name = name ?? string.Empty; Value = value; @@ -49,7 +49,7 @@ namespace System.ComponentModel.Composition /// /// An containing the metadata value. /// - public object Value + public object? Value { get; private set; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs index 254eadc59ca..f016f950cc4 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs @@ -17,9 +17,9 @@ namespace System.ComponentModel.Composition // Provides helpers for creating and dealing with Exports internal static partial class ExportServices { - private static readonly MethodInfo _createStronglyTypedLazyOfTM = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfTM", BindingFlags.NonPublic | BindingFlags.Static); - private static readonly MethodInfo _createStronglyTypedLazyOfT = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfT", BindingFlags.NonPublic | BindingFlags.Static); - private static readonly MethodInfo _createSemiStronglyTypedLazy = typeof(ExportServices).GetMethod("CreateSemiStronglyTypedLazy", BindingFlags.NonPublic | BindingFlags.Static); + private static readonly MethodInfo _createStronglyTypedLazyOfTM = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfTM", BindingFlags.NonPublic | BindingFlags.Static)!; + private static readonly MethodInfo _createStronglyTypedLazyOfT = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfT", BindingFlags.NonPublic | BindingFlags.Static)!; + private static readonly MethodInfo _createSemiStronglyTypedLazy = typeof(ExportServices).GetMethod("CreateSemiStronglyTypedLazy", BindingFlags.NonPublic | BindingFlags.Static)!; internal static readonly Type DefaultMetadataViewType = typeof(IDictionary); internal static readonly Type DefaultExportedValueType = typeof(object); @@ -51,9 +51,9 @@ namespace System.ComponentModel.Composition Array.Empty()) != null; } - internal static Func CreateStronglyTypedLazyFactory(Type exportType, Type metadataViewType) + internal static Func CreateStronglyTypedLazyFactory(Type? exportType, Type? metadataViewType) { - MethodInfo genericMethod = null; + MethodInfo genericMethod; if (metadataViewType != null) { genericMethod = _createStronglyTypedLazyOfTM.MakeGenericMethod(exportType ?? ExportServices.DefaultExportedValueType, metadataViewType); @@ -71,7 +71,7 @@ namespace System.ComponentModel.Composition return (Func)Delegate.CreateDelegate(typeof(Func), genericMethod); } - internal static Func> CreateSemiStronglyTypedLazyFactory(Type exportType, Type metadataViewType) + internal static Func> CreateSemiStronglyTypedLazyFactory(Type? exportType, Type? metadataViewType) { MethodInfo genericMethod = _createSemiStronglyTypedLazy.MakeGenericMethod( exportType ?? ExportServices.DefaultExportedValueType, @@ -86,8 +86,7 @@ namespace System.ComponentModel.Composition [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] internal static Lazy CreateStronglyTypedLazyOfTM(Export export) { - IDisposable disposable = export as IDisposable; - if (disposable != null) + if (export is IDisposable disposable) { return new DisposableLazy( () => ExportServices.GetCastedExportedValue(export), @@ -107,8 +106,7 @@ namespace System.ComponentModel.Composition [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] internal static Lazy CreateStronglyTypedLazyOfT(Export export) { - IDisposable disposable = export as IDisposable; - if (disposable != null) + if (export is IDisposable disposable) { return new DisposableLazy( () => ExportServices.GetCastedExportedValue(export), @@ -118,27 +116,25 @@ namespace System.ComponentModel.Composition else { return new Lazy(() => ExportServices.GetCastedExportedValue(export), LazyThreadSafetyMode.PublicationOnly); - } } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - internal static Lazy CreateSemiStronglyTypedLazy(Export export) + internal static Lazy CreateSemiStronglyTypedLazy(Export export) { - IDisposable disposable = export as IDisposable; - if (disposable != null) + if (export is IDisposable disposable) { - return new DisposableLazy( + return new DisposableLazy( () => ExportServices.GetCastedExportedValue(export), - AttributedModelServices.GetMetadataView(export.Metadata), + AttributedModelServices.GetMetadataView(export.Metadata)!, disposable, LazyThreadSafetyMode.PublicationOnly); } else { - return new Lazy( + return new Lazy( () => ExportServices.GetCastedExportedValue(export), - AttributedModelServices.GetMetadataView(export.Metadata), + AttributedModelServices.GetMetadataView(export.Metadata)!, LazyThreadSafetyMode.PublicationOnly); } } @@ -148,11 +144,9 @@ namespace System.ComponentModel.Composition return CastExportedValue(export.ToElement(), export.Value); } - internal static T CastExportedValue(ICompositionElement element, object exportedValue) + internal static T CastExportedValue(ICompositionElement element, object? exportedValue) { - object typedExportedValue = null; - - bool succeeded = ContractServices.TryCast(typeof(T), exportedValue, out typedExportedValue); + bool succeeded = ContractServices.TryCast(typeof(T), exportedValue, out object? typedExportedValue); if (!succeeded) { throw new CompositionContractMismatchException(SR.Format( @@ -161,10 +155,10 @@ namespace System.ComponentModel.Composition typeof(T))); } - return (T)typedExportedValue; + return (T)typedExportedValue!; } - internal static ExportCardinalityCheckResult CheckCardinality(ImportDefinition definition, IEnumerable enumerable) + internal static ExportCardinalityCheckResult CheckCardinality(ImportDefinition definition, IEnumerable? enumerable) { EnumerableCardinality actualCardinality = (enumerable != null) ? enumerable.GetCardinality() : EnumerableCardinality.Zero; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs index 03ee056f45d..0fe41332e93 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs @@ -19,14 +19,14 @@ namespace System.ComponentModel.Composition.Hosting /// public class AggregateCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged { - private readonly ComposablePartCatalogCollection _catalogs = null; + private readonly ComposablePartCatalogCollection _catalogs; private volatile int _isDisposed = 0; /// /// Initializes a new instance of the class. /// public AggregateCatalog() - : this((IEnumerable)null) + : this((IEnumerable?)null) { } @@ -44,8 +44,8 @@ namespace System.ComponentModel.Composition.Hosting /// /// contains an element that is . /// - public AggregateCatalog(params ComposablePartCatalog[] catalogs) - : this((IEnumerable)catalogs) + public AggregateCatalog(params ComposablePartCatalog[]? catalogs) + : this((IEnumerable?)catalogs) { } @@ -61,7 +61,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// contains an element that is . /// - public AggregateCatalog(IEnumerable catalogs) + public AggregateCatalog(IEnumerable? catalogs) { Requires.NullOrNotNullElements(catalogs, nameof(catalogs)); @@ -71,7 +71,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// Notify when the contents of the Catalog has changed. /// - public event EventHandler Changed + public event EventHandler? Changed { add { @@ -86,7 +86,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// Notify when the contents of the Catalog has changing. /// - public event EventHandler Changing + public event EventHandler? Changing { add { @@ -125,8 +125,8 @@ namespace System.ComponentModel.Composition.Hosting // We optimize for the case where the result is comparible with the requested cardinality, though we do remain correct in all cases. // We do so to avoid any unnecessary allocations - IEnumerable> result = null; - List> aggregateResult = null; + IEnumerable>? result = null; + List>? aggregateResult = null; foreach (var catalog in _catalogs) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs index 0e70ea9b3d1..84a4e48b75d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs @@ -35,11 +35,11 @@ namespace System.ComponentModel.Composition.Hosting /// That is, it will not try to dispose of any of them when it gets disposed. /// /// - public AggregateExportProvider(params ExportProvider[] providers) + public AggregateExportProvider(params ExportProvider[]? providers) { // NOTE : we optimize for the array case here, because the collection of providers is typically tiny // Arrays are much more compact to store and much faster to create and enumerate - ExportProvider[] copiedProviders = null; + ExportProvider[]? copiedProviders = null; if (providers != null) { copiedProviders = new ExportProvider[providers.Length]; @@ -80,7 +80,7 @@ namespace System.ComponentModel.Composition.Hosting /// That is, it will not try to dispose of any of them when it gets disposed. /// /// - public AggregateExportProvider(IEnumerable providers) + public AggregateExportProvider(IEnumerable? providers) : this((providers != null) ? providers.AsArray() : null) { } @@ -153,7 +153,7 @@ namespace System.ComponentModel.Composition.Hosting /// it should return an empty of . /// /// - protected override IEnumerable GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) + protected override IEnumerable GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition) { ThrowIfDisposed(); @@ -171,14 +171,14 @@ namespace System.ComponentModel.Composition.Hosting } else { - IEnumerable allExports = null; + IEnumerable? allExports = null; // if asked for "one or less", the prioriry is at play - the first provider that agrees to return the value // which best complies with the request, wins. foreach (ExportProvider provider in _providers) { - IEnumerable exports; - bool cardinalityCheckResult = provider.TryGetExports(definition, atomicComposition, out exports); + bool cardinalityCheckResult = provider.TryGetExports(definition, atomicComposition, out IEnumerable? exports); + Debug.Assert(exports != null); bool anyExports = exports.FastAny(); if (cardinalityCheckResult && anyExports) { @@ -200,16 +200,16 @@ namespace System.ComponentModel.Composition.Hosting } } - return allExports; + return allExports!; } } - private void OnExportChangedInternal(object sender, ExportsChangeEventArgs e) + private void OnExportChangedInternal(object? sender, ExportsChangeEventArgs e) { OnExportsChanged(e); } - private void OnExportChangingInternal(object sender, ExportsChangeEventArgs e) + private void OnExportChangingInternal(object? sender, ExportsChangeEventArgs e) { OnExportsChanging(e); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs index ed3e532a190..8f583bab2cb 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs @@ -16,10 +16,10 @@ namespace System.ComponentModel.Composition.Hosting public partial class ApplicationCatalog : ComposablePartCatalog, ICompositionElement { private bool _isDisposed = false; - private volatile AggregateCatalog _innerCatalog = null; + private volatile AggregateCatalog? _innerCatalog = null; private readonly object _thisLock = new object(); - private readonly ICompositionElement _definitionOrigin = null; - private readonly ReflectionContext _reflectionContext = null; + private readonly ICompositionElement? _definitionOrigin = null; + private readonly ReflectionContext? _reflectionContext = null; public ApplicationCatalog() { } @@ -82,7 +82,7 @@ namespace System.ComponentModel.Composition.Hosting catalogs.Add(CreateCatalog(location, "*.exe")); catalogs.Add(CreateCatalog(location, "*.dll")); - string relativeSearchPath = AppDomain.CurrentDomain.RelativeSearchPath; + string? relativeSearchPath = AppDomain.CurrentDomain.RelativeSearchPath; if (!string.IsNullOrEmpty(relativeSearchPath)) { string[] probingPaths = relativeSearchPath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); @@ -111,7 +111,7 @@ namespace System.ComponentModel.Composition.Hosting { if (!_isDisposed) { - IDisposable innerCatalog = null; + IDisposable? innerCatalog = null; lock (_thisLock) { innerCatalog = _innerCatalog as IDisposable; @@ -213,7 +213,7 @@ namespace System.ComponentModel.Composition.Hosting /// This property always returns . /// [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] - ICompositionElement ICompositionElement.Origin + ICompositionElement? ICompositionElement.Origin { get { return null; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs index c340378237b..4a9fe60e5f0 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs @@ -25,11 +25,11 @@ namespace System.ComponentModel.Composition.Hosting { private readonly object _thisLock = new object(); private readonly ICompositionElement _definitionOrigin; - private volatile Assembly _assembly = null; - private volatile ComposablePartCatalog _innerCatalog = null; + private volatile Assembly _assembly = null!; // Always initiialized with helper + private volatile ComposablePartCatalog? _innerCatalog = null; private int _isDisposed = 0; - private readonly ReflectionContext _reflectionContext = default(ReflectionContext); + private readonly ReflectionContext? _reflectionContext = default(ReflectionContext); /// /// Initializes a new instance of the class @@ -492,7 +492,7 @@ namespace System.ComponentModel.Composition.Hosting /// This property always returns . /// [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] - ICompositionElement ICompositionElement.Origin + ICompositionElement? ICompositionElement.Origin { get { return null; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs index 86cf668abef..b7e606ca65d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs @@ -35,11 +35,11 @@ namespace System.ComponentModel.Composition.Hosting /// public class AtomicComposition : IDisposable { - private readonly AtomicComposition _outerAtomicComposition; - private KeyValuePair[] _values; + private readonly AtomicComposition? _outerAtomicComposition; + private KeyValuePair[]? _values; private int _valueCount = 0; - private List _completeActionList; - private List _revertActionList; + private List? _completeActionList; + private List? _revertActionList; private bool _isDisposed = false; private bool _isCompleted = false; private bool _containsInnerAtomicComposition = false; @@ -49,7 +49,7 @@ namespace System.ComponentModel.Composition.Hosting { } - public AtomicComposition(AtomicComposition outerAtomicComposition) + public AtomicComposition(AtomicComposition? outerAtomicComposition) { // Lock the inner atomicComposition so that we can assume nothing changes except on // the innermost scope, and thereby optimize the query path @@ -60,7 +60,7 @@ namespace System.ComponentModel.Composition.Hosting } } - public void SetValue(object key, object value) + public void SetValue(object key, object? value) { ThrowIfDisposed(); ThrowIfCompleted(); @@ -71,13 +71,13 @@ namespace System.ComponentModel.Composition.Hosting SetValueInternal(key, value); } - public bool TryGetValue(object key, out T value) + public bool TryGetValue(object key, [MaybeNullWhen(false)] out T value) { return TryGetValue(key, false, out value); } [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters")] - public bool TryGetValue(object key, bool localAtomicCompositionOnly, out T value) + public bool TryGetValue(object key, bool localAtomicCompositionOnly, [MaybeNullWhen(false)] out T value) { ThrowIfDisposed(); ThrowIfCompleted(); @@ -156,7 +156,7 @@ namespace System.ComponentModel.Composition.Hosting { if (_revertActionList != null) { - List exceptions = null; + List? exceptions = null; // Execute the revert actions in reverse order to ensure // everything incrementally rollsback its state. @@ -198,7 +198,7 @@ namespace System.ComponentModel.Composition.Hosting // Completeting the outer most scope is easy, just execute all the actions if (_completeActionList != null) { - List exceptions = null; + List? exceptions = null; foreach (Action action in _completeActionList) { @@ -263,7 +263,7 @@ namespace System.ComponentModel.Composition.Hosting for (var index = 0; index < _valueCount; index++) { _outerAtomicComposition.SetValueInternal( - _values[index].Key, _values[index].Value); + _values![index].Key, _values[index].Value); } } @@ -279,13 +279,13 @@ namespace System.ComponentModel.Composition.Hosting } } - private bool TryGetValueInternal(object key, bool localAtomicCompositionOnly, out T value) + private bool TryGetValueInternal(object key, bool localAtomicCompositionOnly, [MaybeNullWhen(false)] out T value) { for (var index = 0; index < _valueCount; index++) { - if (_values[index].Key == key) + if (_values![index].Key == key) { - value = (T)_values[index].Value; + value = (T)_values[index].Value!; return true; } } @@ -297,18 +297,18 @@ namespace System.ComponentModel.Composition.Hosting return _outerAtomicComposition.TryGetValueInternal(key, localAtomicCompositionOnly, out value); } - value = default(T); + value = default(T)!; return false; } - private void SetValueInternal(object key, object value) + private void SetValueInternal(object key, object? value) { // Handle overwrites quickly for (var index = 0; index < _valueCount; index++) { - if (_values[index].Key == key) + if (_values![index].Key == key) { - _values[index] = new KeyValuePair(key, value); + _values[index] = new KeyValuePair(key, value); return; } } @@ -316,7 +316,7 @@ namespace System.ComponentModel.Composition.Hosting // Expand storage when needed if (_values == null || _valueCount == _values.Length) { - var newQueries = new KeyValuePair[_valueCount == 0 ? 5 : _valueCount * 2]; + var newQueries = new KeyValuePair[_valueCount == 0 ? 5 : _valueCount * 2]; if (_values != null) { Array.Copy(_values, newQueries, _valueCount); @@ -325,7 +325,7 @@ namespace System.ComponentModel.Composition.Hosting } // Store a new entry - _values[_valueCount] = new KeyValuePair(key, value); + _values[_valueCount] = new KeyValuePair(key, value); _valueCount++; return; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs index b22c8c2d7b0..d5b522c1d34 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs @@ -7,7 +7,7 @@ namespace System.ComponentModel.Composition.Hosting { internal static class AtomicCompositionExtensions { - internal static T GetValueAllowNull(this AtomicComposition atomicComposition, T defaultResultAndKey) where T : class + internal static T GetValueAllowNull(this AtomicComposition? atomicComposition, T defaultResultAndKey) where T : class { if (defaultResultAndKey == null) { @@ -17,7 +17,7 @@ namespace System.ComponentModel.Composition.Hosting return GetValueAllowNull(atomicComposition, defaultResultAndKey, defaultResultAndKey); } - internal static T GetValueAllowNull(this AtomicComposition atomicComposition, object key, T defaultResult) + internal static T GetValueAllowNull(this AtomicComposition? atomicComposition, object key, T defaultResult) { T result; if (atomicComposition != null && atomicComposition.TryGetValue(key, out result)) @@ -28,7 +28,7 @@ namespace System.ComponentModel.Composition.Hosting return defaultResult; } - internal static void AddRevertActionAllowNull(this AtomicComposition atomicComposition, Action action) + internal static void AddRevertActionAllowNull(this AtomicComposition? atomicComposition, Action action) { if (action == null) { @@ -45,7 +45,7 @@ namespace System.ComponentModel.Composition.Hosting } } - internal static void AddCompleteActionAllowNull(this AtomicComposition atomicComposition, Action action) + internal static void AddCompleteActionAllowNull(this AtomicComposition? atomicComposition, Action action) { if (action == null) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs index fda7e109d21..3fe89135b7c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs @@ -45,7 +45,7 @@ namespace System.ComponentModel.Composition.Hosting return _catalogExportProvider.GetComposablePart(_partDefinition, IsSharedPart); } - protected void DisposePartCore(CatalogPart part, object value) + protected void DisposePartCore(CatalogPart part, object? value) { _catalogExportProvider.DisposePart(value, part, null); } @@ -55,7 +55,7 @@ namespace System.ComponentModel.Composition.Hosting return GetPartCore(); } - protected override object GetExportedValueCore() + protected override object? GetExportedValueCore() { return _catalogExportProvider.GetExportedValue(GetPart(), _definition, IsSharedPart); } @@ -120,7 +120,7 @@ namespace System.ComponentModel.Composition.Hosting private sealed class NonSharedCatalogExport : CatalogExport, IDisposable { - private CatalogPart _part; + private CatalogPart? _part; private readonly object _lock = new object(); public NonSharedCatalogExport(CatalogExportProvider catalogExportProvider, @@ -134,7 +134,7 @@ namespace System.ComponentModel.Composition.Hosting // we need to ensure that the part gets created only once, as the export contract requires that the same value be returned on subsequent calls if (_part == null) { - CatalogPart part = GetPartCore(); + CatalogPart? part = GetPartCore(); lock (_lock) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs index 83777e7dde5..61f506ef588 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs @@ -16,7 +16,7 @@ namespace System.ComponentModel.Composition.Hosting private readonly ComposablePartDefinition _partDefinition; private readonly ExportDefinition _exportDefinition; private readonly ExportDefinition _factoryExportDefinition; - private FactoryExportPartDefinition _factoryExportPartDefinition; + private FactoryExportPartDefinition? _factoryExportPartDefinition; public FactoryExport(ComposablePartDefinition partDefinition, ExportDefinition exportDefinition) { @@ -113,7 +113,7 @@ namespace System.ComponentModel.Composition.Hosting get { return _definition.ImportDefinitions; } } - public override object GetExportedValue(ExportDefinition definition) + public override object? GetExportedValue(ExportDefinition definition) { if (definition != _definition.FactoryExportDefinition) { @@ -130,9 +130,7 @@ namespace System.ComponentModel.Composition.Hosting public void Dispose() { - IDisposable disposable = _export as IDisposable; - - if (disposable != null) + if (_export is IDisposable disposable) { disposable.Dispose(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs index 78f294f223e..47361bee8bc 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs @@ -4,6 +4,7 @@ using System.ComponentModel.Composition.Primitives; using System.Threading; +using System.Diagnostics; namespace System.ComponentModel.Composition.Hosting { @@ -29,8 +30,8 @@ namespace System.ComponentModel.Composition.Hosting private sealed class ScopeCatalogExport : Export, IDisposable { private readonly ScopeFactoryExport _scopeFactoryExport; - private CompositionContainer _childContainer; - private Export _export; + private CompositionContainer? _childContainer; + private Export? _export; private readonly object _lock = new object(); public ScopeCatalogExport(ScopeFactoryExport scopeFactoryExport) @@ -46,13 +47,14 @@ namespace System.ComponentModel.Composition.Hosting } } - protected override object GetExportedValueCore() + protected override object? GetExportedValueCore() { if (_export == null) { - var childContainer = _scopeFactoryExport._scopeManager.CreateChildContainer(_scopeFactoryExport._catalog); + CompositionContainer? childContainer = _scopeFactoryExport._scopeManager.CreateChildContainer(_scopeFactoryExport._catalog); - var export = childContainer.CatalogExportProvider.CreateExport(_scopeFactoryExport.UnderlyingPartDefinition, _scopeFactoryExport.UnderlyingExportDefinition, false, CreationPolicy.Any); + Debug.Assert(childContainer.CatalogExportProvider != null); + Export? export = childContainer.CatalogExportProvider.CreateExport(_scopeFactoryExport.UnderlyingPartDefinition, _scopeFactoryExport.UnderlyingExportDefinition, false, CreationPolicy.Any); lock (_lock) { if (_export == null) @@ -76,8 +78,8 @@ namespace System.ComponentModel.Composition.Hosting public void Dispose() { - CompositionContainer childContainer = null; - Export export = null; + CompositionContainer? childContainer = null; + Export? export = null; if (_export != null) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs index e10352861cd..848c5c275d8 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs @@ -29,11 +29,11 @@ namespace System.ComponentModel.Composition.Hosting _catalogExportProvider = catalogExportProvider; } - protected override IEnumerable GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) + protected override IEnumerable GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition) { List exports = new List(); - ImportDefinition queryImport = TranslateImport(definition); + ImportDefinition? queryImport = TranslateImport(definition); if (queryImport == null) { return exports; @@ -56,7 +56,7 @@ namespace System.ComponentModel.Composition.Hosting // the RevertActions need to operate before we Dispose the child container using (var localAtomicComposition = new AtomicComposition(atomicComposition)) { - isChildPartRejected = container.CatalogExportProvider.DetermineRejection(partDefinitionAndExportDefinition.Item1, localAtomicComposition); + isChildPartRejected = container.CatalogExportProvider!.DetermineRejection(partDefinitionAndExportDefinition.Item1, localAtomicComposition); } } } @@ -79,12 +79,12 @@ namespace System.ComponentModel.Composition.Hosting internal CompositionContainer CreateChildContainer(ComposablePartCatalog childCatalog) { - return new CompositionContainer(childCatalog, _catalogExportProvider._compositionOptions, _catalogExportProvider._sourceProvider); + return new CompositionContainer(childCatalog, _catalogExportProvider._compositionOptions, _catalogExportProvider._sourceProvider!); } - private static ImportDefinition TranslateImport(ImportDefinition definition) + private static ImportDefinition? TranslateImport(ImportDefinition definition) { - IPartCreatorImportDefinition factoryDefinition = definition as IPartCreatorImportDefinition; + IPartCreatorImportDefinition? factoryDefinition = definition as IPartCreatorImportDefinition; if (factoryDefinition == null) { return null; @@ -94,7 +94,7 @@ namespace System.ComponentModel.Composition.Hosting // We will always create a new child CatalogEP to satsify the request, so from the perspecitive of the caller, the policy should // always be NonShared (or Any). From teh perspective of the callee, it's the otehr way around. ContractBasedImportDefinition productImportDefinition = factoryDefinition.ProductImportDefinition; - ImportDefinition result = null; + ImportDefinition? result = null; switch (productImportDefinition.RequiredCreationPolicy) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs index c00f0b001d9..9c06b883654 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs @@ -32,7 +32,7 @@ namespace System.ComponentModel.Composition.Hosting _outerExportProvider = outerExportProvider; } - protected override IEnumerable GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) + protected override IEnumerable GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition) { return _outerExportProvider.InternalGetExportsCore(definition, atomicComposition); } @@ -41,16 +41,16 @@ namespace System.ComponentModel.Composition.Hosting private readonly CompositionLock _lock; private readonly Dictionary _activatedParts = new Dictionary(); private readonly HashSet _rejectedParts = new HashSet(); - private ConditionalWeakTable> _gcRoots; + private ConditionalWeakTable>? _gcRoots; private readonly HashSet _partsToDispose = new HashSet(); private ComposablePartCatalog _catalog; private volatile bool _isDisposed = false; private volatile bool _isRunning = false; private readonly bool _disableSilentRejection = false; - private ExportProvider _sourceProvider; - private ImportEngine _importEngine; + private ExportProvider? _sourceProvider; + private ImportEngine? _importEngine; private readonly CompositionOptions _compositionOptions; - private ExportProvider _innerExportProvider; + private ExportProvider? _innerExportProvider; /// /// Initializes a new instance of the class. @@ -82,14 +82,12 @@ namespace System.ComponentModel.Composition.Hosting _catalog = catalog; _compositionOptions = compositionOptions; - var notifyCatalogChanged = _catalog as INotifyComposablePartCatalogChanged; - if (notifyCatalogChanged != null) + if (_catalog is INotifyComposablePartCatalogChanged notifyCatalogChanged) { notifyCatalogChanged.Changing += OnCatalogChanging; } - CompositionScopeDefinition scopeDefinition = _catalog as CompositionScopeDefinition; - if (scopeDefinition != null) + if (_catalog is CompositionScopeDefinition scopeDefinition) { _innerExportProvider = new AggregateExportProvider(new ScopeManager(this, scopeDefinition), new InnerCatalogExportProvider(this)); } @@ -152,7 +150,8 @@ namespace System.ComponentModel.Composition.Hosting /// . /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "EnsureCanSet ensures that the property is set only once, Dispose is not required")] - public ExportProvider SourceProvider + [DisallowNull] + public ExportProvider? SourceProvider { get { @@ -166,11 +165,11 @@ namespace System.ComponentModel.Composition.Hosting { ThrowIfDisposed(); - Requires.NotNull(value, nameof(value)); + Requires.NotNull(value!, nameof(value)); - ImportEngine newImportEngine = null; - AggregateExportProvider aggregateExportProvider = null; - ExportProvider sourceProvider = value; + ImportEngine? newImportEngine = null; + AggregateExportProvider? aggregateExportProvider = null; + ExportProvider sourceProvider = value!; bool isThrowing = true; try @@ -194,7 +193,7 @@ namespace System.ComponentModel.Composition.Hosting if (isThrowing) { sourceProvider.ExportsChanging -= OnExportsChangingInternal; - newImportEngine.Dispose(); + newImportEngine!.Dispose(); if (aggregateExportProvider != null) { aggregateExportProvider.Dispose(); @@ -225,11 +224,11 @@ namespace System.ComponentModel.Composition.Hosting { //Note: We do not dispose _lock on dispose because DisposePart needs it to check isDisposed state // to eliminate race conditions between it and Dispose - INotifyComposablePartCatalogChanged catalogToUnsubscribeFrom = null; - HashSet partsToDispose = null; - ImportEngine importEngine = null; - ExportProvider sourceProvider = null; - AggregateExportProvider aggregateExportProvider = null; + INotifyComposablePartCatalogChanged? catalogToUnsubscribeFrom = null; + HashSet? partsToDispose = null; + ImportEngine? importEngine = null; + ExportProvider? sourceProvider = null; + AggregateExportProvider? aggregateExportProvider = null; try { using (_lock.LockStateForWrite()) @@ -237,7 +236,7 @@ namespace System.ComponentModel.Composition.Hosting if (!_isDisposed) { catalogToUnsubscribeFrom = _catalog as INotifyComposablePartCatalogChanged; - _catalog = null; + _catalog = null!; aggregateExportProvider = _innerExportProvider as AggregateExportProvider; _innerExportProvider = null; @@ -307,7 +306,7 @@ namespace System.ComponentModel.Composition.Hosting /// it should return an empty of . /// /// - protected override IEnumerable GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) + protected override IEnumerable GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition) { ThrowIfDisposed(); EnsureRunning(); @@ -317,12 +316,11 @@ namespace System.ComponentModel.Composition.Hosting throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - IEnumerable exports; - _innerExportProvider.TryGetExports(definition, atomicComposition, out exports); - return exports; + _innerExportProvider.TryGetExports(definition, atomicComposition, out IEnumerable? exports); + return exports!; } - private IEnumerable InternalGetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) + private IEnumerable InternalGetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition) { ThrowIfDisposed(); EnsureRunning(); @@ -330,10 +328,9 @@ namespace System.ComponentModel.Composition.Hosting // Use the version of the catalog appropriate to this atomicComposition ComposablePartCatalog currentCatalog = atomicComposition.GetValueAllowNull(_catalog); - IPartCreatorImportDefinition partCreatorDefinition = definition as IPartCreatorImportDefinition; bool isExportFactory = false; - if (partCreatorDefinition != null) + if (definition is IPartCreatorImportDefinition partCreatorDefinition) { definition = partCreatorDefinition.ProductImportDefinition; isExportFactory = true; @@ -372,7 +369,7 @@ namespace System.ComponentModel.Composition.Hosting } } - private void OnExportsChangingInternal(object sender, ExportsChangeEventArgs e) + private void OnExportsChangingInternal(object? sender, ExportsChangeEventArgs e) { UpdateRejections(e.AddedExports.Concat(e.RemovedExports), e.AtomicComposition); } @@ -401,7 +398,7 @@ namespace System.ComponentModel.Composition.Hosting } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] - private void OnCatalogChanging(object sender, ComposablePartCatalogChangeEventArgs e) + private void OnCatalogChanging(object? sender, ComposablePartCatalogChangeEventArgs e) { using (var atomicComposition = new AtomicComposition(e.AtomicComposition)) { @@ -417,7 +414,7 @@ namespace System.ComponentModel.Composition.Hosting // fashion) foreach (var definition in e.RemovedDefinitions) { - CatalogPart removedPart = null; + CatalogPart? removedPart = null; bool removed = false; using (_lock.LockStateForRead()) @@ -428,7 +425,7 @@ namespace System.ComponentModel.Composition.Hosting if (removed) { var capturedDefinition = definition; - DisposePart(null, removedPart, atomicComposition); + DisposePart(null, removedPart!, atomicComposition); atomicComposition.AddCompleteActionAllowNull(() => { using (_lock.LockStateForWrite()) @@ -439,7 +436,7 @@ namespace System.ComponentModel.Composition.Hosting } } - UpdateRejections(addedExports.ConcatAllowingNull(removedExports), atomicComposition); + UpdateRejections(addedExports.ConcatAllowingNull(removedExports)!, atomicComposition); OnExportsChanging( new ExportsChangeEventArgs(addedExports, removedExports, atomicComposition)); @@ -456,7 +453,7 @@ namespace System.ComponentModel.Composition.Hosting ThrowIfDisposed(); EnsureRunning(); - CatalogPart catalogPart = null; + CatalogPart catalogPart; if (isSharedPart) { @@ -467,8 +464,7 @@ namespace System.ComponentModel.Composition.Hosting ComposablePart part = partDefinition.CreatePart(); catalogPart = new CatalogPart(part); - IDisposable disposablePart = part as IDisposable; - if (disposablePart != null) + if (part is IDisposable disposablePart) { using (_lock.LockStateForWrite()) { @@ -482,7 +478,7 @@ namespace System.ComponentModel.Composition.Hosting private CatalogPart GetSharedPart(ComposablePartDefinition partDefinition) { - CatalogPart catalogPart = null; + CatalogPart? catalogPart = null; // look up the part using (_lock.LockStateForRead()) @@ -494,8 +490,8 @@ namespace System.ComponentModel.Composition.Hosting } // create a part outside of the lock - ComposablePart newPart = partDefinition.CreatePart(); - IDisposable disposableNewPart = newPart as IDisposable; + ComposablePart? newPart = partDefinition.CreatePart(); + IDisposable? disposableNewPart = newPart as IDisposable; using (_lock.LockStateForWrite()) { @@ -525,7 +521,7 @@ namespace System.ComponentModel.Composition.Hosting return catalogPart; } - private object GetExportedValue(CatalogPart part, ExportDefinition export, bool isSharedPart) + private object? GetExportedValue(CatalogPart part, ExportDefinition export, bool isSharedPart) { ThrowIfDisposed(); EnsureRunning(); @@ -543,9 +539,9 @@ namespace System.ComponentModel.Composition.Hosting // if two threads satisfy imports twice, the results is the same, just the perf hit is heavier. bool importsSatisfied = part.ImportsSatisfied; - ImportEngine importEngine = importsSatisfied ? null : _importEngine; + ImportEngine? importEngine = importsSatisfied ? null : _importEngine; - object exportedValue = CompositionServices.GetExportedValueFromComposedPart( + object? exportedValue = CompositionServices.GetExportedValueFromComposedPart( importEngine, part.Part, export); if (!importsSatisfied) @@ -572,7 +568,7 @@ namespace System.ComponentModel.Composition.Hosting DisposePart(exportedValue, catalogPart, atomicComposition); } - private void DisposePart(object exportedValue, CatalogPart catalogPart, AtomicComposition atomicComposition) + private void DisposePart(object? exportedValue, CatalogPart catalogPart, AtomicComposition? atomicComposition) { if (catalogPart == null) { @@ -582,7 +578,7 @@ namespace System.ComponentModel.Composition.Hosting if (_isDisposed) return; - ImportEngine importEngine = null; + ImportEngine? importEngine = null; using (_lock.LockStateForWrite()) { if (_isDisposed) @@ -602,8 +598,7 @@ namespace System.ComponentModel.Composition.Hosting }); } - IDisposable diposablePart = catalogPart.Part as IDisposable; - if (diposablePart != null) + if (catalogPart.Part is IDisposable diposablePart) { atomicComposition.AddCompleteActionAllowNull(() => { @@ -641,9 +636,9 @@ namespace System.ComponentModel.Composition.Hosting using (_lock.LockStateForWrite()) { - List partList; + List? partList; - ConditionalWeakTable> gcRoots = _gcRoots; + ConditionalWeakTable>? gcRoots = _gcRoots; if (gcRoots == null) { gcRoots = new ConditionalWeakTable>(); @@ -676,7 +671,7 @@ namespace System.ComponentModel.Composition.Hosting } } - private bool IsRejected(ComposablePartDefinition definition, AtomicComposition atomicComposition) + private bool IsRejected(ComposablePartDefinition definition, AtomicComposition? atomicComposition) { // Check to see if we're currently working on the definition in question. // Recursive queries always answer optimistically, as if the definition hasn't @@ -727,14 +722,14 @@ namespace System.ComponentModel.Composition.Hosting return DetermineRejection(definition, atomicComposition); } - private bool EnsureRejection(AtomicComposition atomicComposition) + private bool EnsureRejection(AtomicComposition? atomicComposition) { return !(_disableSilentRejection && (atomicComposition == null)); } - private bool DetermineRejection(ComposablePartDefinition definition, AtomicComposition parentAtomicComposition) + private bool DetermineRejection(ComposablePartDefinition definition, AtomicComposition? parentAtomicComposition) { - ChangeRejectedException exception = null; + ChangeRejectedException? exception = null; // if there is no active atomic composition and rejection is disabled, there's no need to do any of the below if (!EnsureRejection(parentAtomicComposition)) @@ -761,6 +756,7 @@ namespace System.ComponentModel.Composition.Hosting var newPart = definition.CreatePart(); try { + Debug.Assert(_importEngine != null); _importEngine.PreviewImports(newPart, localAtomicComposition); // Reuse the partially-fleshed out part the next time we need a shared @@ -776,8 +772,7 @@ namespace System.ComponentModel.Composition.Hosting if (!_activatedParts.ContainsKey(definition)) { _activatedParts.Add(definition, new CatalogPart(newPart)); - IDisposable newDisposablePart = newPart as IDisposable; - if (newDisposablePart != null) + if (newPart is IDisposable newDisposablePart) { _partsToDispose.Add(newDisposablePart); } @@ -818,7 +813,7 @@ namespace System.ComponentModel.Composition.Hosting return true; } - private void UpdateRejections(IEnumerable changedExports, AtomicComposition atomicComposition) + private void UpdateRejections(IEnumerable changedExports, AtomicComposition? atomicComposition) { using (var localAtomicComposition = new AtomicComposition(atomicComposition)) { @@ -934,7 +929,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// [DebuggerStepThrough] - private void EnsureCanSet(T currentValue) + private void EnsureCanSet(T? currentValue) where T : class { if ((_isRunning) || (currentValue != null)) @@ -945,7 +940,7 @@ namespace System.ComponentModel.Composition.Hosting private AtomicCompositionQueryState QueryPartState(AtomicComposition atomicComposition, ComposablePartDefinition definition) { - PartQueryStateNode node = GetPartQueryStateNode(atomicComposition); + PartQueryStateNode? node = GetPartQueryStateNode(atomicComposition); if (node == null) { return AtomicCompositionQueryState.Unknown; @@ -956,10 +951,9 @@ namespace System.ComponentModel.Composition.Hosting } } - private PartQueryStateNode GetPartQueryStateNode(AtomicComposition atomicComposition) + private PartQueryStateNode? GetPartQueryStateNode(AtomicComposition atomicComposition) { - PartQueryStateNode node; - atomicComposition.TryGetValue(this, out node); + atomicComposition.TryGetValue(this, out PartQueryStateNode? node); return node; } @@ -968,7 +962,7 @@ namespace System.ComponentModel.Composition.Hosting ComposablePartDefinition part, AtomicCompositionQueryState state) { - PartQueryStateNode previousNode = GetPartQueryStateNode(atomicComposition); + PartQueryStateNode? previousNode = GetPartQueryStateNode(atomicComposition); atomicComposition.SetValue(this, new PartEqualsQueryStateNode(part, previousNode, state)); } @@ -977,7 +971,7 @@ namespace System.ComponentModel.Composition.Hosting HashSet hashset, AtomicCompositionQueryState state) { - PartQueryStateNode previousNode = GetPartQueryStateNode(atomicComposition); + PartQueryStateNode? previousNode = GetPartQueryStateNode(atomicComposition); atomicComposition.SetValue(this, new PartInHashSetQueryStateNode(hashset, previousNode, state)); } @@ -991,10 +985,10 @@ namespace System.ComponentModel.Composition.Hosting private abstract class PartQueryStateNode { - private readonly PartQueryStateNode _previousNode; + private readonly PartQueryStateNode? _previousNode; private readonly AtomicCompositionQueryState _state; - protected PartQueryStateNode(PartQueryStateNode previousNode, AtomicCompositionQueryState state) + protected PartQueryStateNode(PartQueryStateNode? previousNode, AtomicCompositionQueryState state) { _previousNode = previousNode; _state = state; @@ -1005,7 +999,7 @@ namespace System.ComponentModel.Composition.Hosting public AtomicCompositionQueryState GetQueryState(ComposablePartDefinition definition) { int hashCode = definition.GetHashCode(); - PartQueryStateNode node = this; + PartQueryStateNode? node = this; do { if (node.IsMatchingDefinition(definition, hashCode)) @@ -1024,7 +1018,7 @@ namespace System.ComponentModel.Composition.Hosting { private readonly ComposablePartDefinition _part; private readonly int _hashCode; - public PartEqualsQueryStateNode(ComposablePartDefinition part, PartQueryStateNode previousNode, AtomicCompositionQueryState state) : + public PartEqualsQueryStateNode(ComposablePartDefinition part, PartQueryStateNode? previousNode, AtomicCompositionQueryState state) : base(previousNode, state) { _part = part; @@ -1044,7 +1038,7 @@ namespace System.ComponentModel.Composition.Hosting private class PartInHashSetQueryStateNode : PartQueryStateNode { private readonly HashSet _parts; - public PartInHashSetQueryStateNode(HashSet parts, PartQueryStateNode previousNode, AtomicCompositionQueryState state) : + public PartInHashSetQueryStateNode(HashSet parts, PartQueryStateNode? previousNode, AtomicCompositionQueryState state) : base(previousNode, state) { _parts = parts; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs index b92e48860fe..06b46c753a4 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs @@ -40,7 +40,7 @@ namespace System.ComponentModel.Composition.Hosting /// or is . /// public ComposablePartCatalogChangeEventArgs(IEnumerable addedDefinitions, - IEnumerable removedDefinitions, AtomicComposition atomicComposition) + IEnumerable removedDefinitions, AtomicComposition? atomicComposition) { Requires.NotNull(addedDefinitions, nameof(addedDefinitions)); Requires.NotNull(removedDefinitions, nameof(removedDefinitions)); @@ -96,6 +96,6 @@ namespace System.ComponentModel.Composition.Hosting /// When the value is non-null it should be used to record temporary changed state /// and actions that will be executed when the atomicComposition is completeed. /// - public AtomicComposition AtomicComposition { get; private set; } + public AtomicComposition? AtomicComposition { get; private set; } } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs index c623733c545..ff38779414d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs @@ -21,17 +21,17 @@ namespace System.ComponentModel.Composition.Hosting internal class ComposablePartCatalogCollection : ICollection, INotifyComposablePartCatalogChanged, IDisposable { private readonly Lock _lock = new Lock(); - private readonly Action _onChanged; - private readonly Action _onChanging; + private readonly Action? _onChanged; + private readonly Action? _onChanging; private List _catalogs = new List(); private volatile bool _isCopyNeeded = false; private volatile bool _isDisposed = false; private bool _hasChanged = false; public ComposablePartCatalogCollection( - IEnumerable catalogs, - Action onChanged, - Action onChanging) + IEnumerable? catalogs, + Action? onChanged, + Action? onChanging) { catalogs = catalogs ?? Enumerable.Empty(); _catalogs = new List(catalogs); @@ -76,19 +76,19 @@ namespace System.ComponentModel.Composition.Hosting /// /// Notify when the contents of the Catalog has changed. /// - public event EventHandler Changed; + public event EventHandler? Changed; /// /// Notify when the contents of the Catalog has changing. /// - public event EventHandler Changing; + public event EventHandler? Changing; public void Clear() { ThrowIfDisposed(); // No action is required if we are already empty - ComposablePartCatalog[] catalogs = null; + ComposablePartCatalog[]? catalogs = null; using (new ReadLock(_lock)) { if (_catalogs.Count == 0) @@ -259,7 +259,7 @@ namespace System.ComponentModel.Composition.Hosting if (!_isDisposed) { bool disposeLock = false; - IEnumerable catalogs = null; + IEnumerable? catalogs = null; try { using (new WriteLock(_lock)) @@ -269,7 +269,7 @@ namespace System.ComponentModel.Composition.Hosting disposeLock = true; catalogs = _catalogs; - _catalogs = null; + _catalogs = null!; _isDisposed = true; } @@ -293,8 +293,8 @@ namespace System.ComponentModel.Composition.Hosting } private void RaiseChangedEvent( - Lazy> addedDefinitions, - Lazy> removedDefinitions) + Lazy>? addedDefinitions, + Lazy>? removedDefinitions) { if (_onChanged == null || Changed == null) { @@ -317,9 +317,9 @@ namespace System.ComponentModel.Composition.Hosting } private void RaiseChangingEvent( - Lazy> addedDefinitions, - Lazy> removedDefinitions, - AtomicComposition atomicComposition) + Lazy>? addedDefinitions, + Lazy>? removedDefinitions, + AtomicComposition? atomicComposition) { if (_onChanging == null || Changing == null) { @@ -340,7 +340,7 @@ namespace System.ComponentModel.Composition.Hosting } } - private void OnContainedCatalogChanged(object sender, ComposablePartCatalogChangeEventArgs e) + private void OnContainedCatalogChanged(object? sender, ComposablePartCatalogChangeEventArgs e) { if (_onChanged == null || Changed == null) { @@ -350,7 +350,7 @@ namespace System.ComponentModel.Composition.Hosting _onChanged.Invoke(e); } - private void OnContainedCatalogChanging(object sender, ComposablePartCatalogChangeEventArgs e) + private void OnContainedCatalogChanging(object? sender, ComposablePartCatalogChangeEventArgs e) { if (_onChanging == null || Changing == null) { @@ -362,8 +362,7 @@ namespace System.ComponentModel.Composition.Hosting private void SubscribeToCatalogNotifications(ComposablePartCatalog catalog) { - INotifyComposablePartCatalogChanged notifyCatalog = catalog as INotifyComposablePartCatalogChanged; - if (notifyCatalog != null) + if (catalog is INotifyComposablePartCatalogChanged notifyCatalog) { notifyCatalog.Changed += OnContainedCatalogChanged; notifyCatalog.Changing += OnContainedCatalogChanging; @@ -380,8 +379,7 @@ namespace System.ComponentModel.Composition.Hosting private void UnsubscribeFromCatalogNotifications(ComposablePartCatalog catalog) { - INotifyComposablePartCatalogChanged notifyCatalog = catalog as INotifyComposablePartCatalogChanged; - if (notifyCatalog != null) + if (catalog is INotifyComposablePartCatalogChanged notifyCatalog) { notifyCatalog.Changed -= OnContainedCatalogChanged; notifyCatalog.Changing -= OnContainedCatalogChanging; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs index 35ddb1452d6..537865fd2c4 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading; @@ -17,9 +18,9 @@ namespace System.ComponentModel.Composition.Hosting private List _parts = new List(); private volatile bool _isDisposed = false; private volatile bool _isRunning = false; - private readonly CompositionLock _lock = null; - private ExportProvider _sourceProvider; - private ImportEngine _importEngine; + private readonly CompositionLock _lock; + private ExportProvider? _sourceProvider; + private ImportEngine? _importEngine; private volatile bool _currentlyComposing; private readonly CompositionOptions _compositionOptions; @@ -67,7 +68,7 @@ namespace System.ComponentModel.Composition.Hosting if (!_isDisposed) { bool disposeLock = false; - ImportEngine importEngine = null; + ImportEngine? importEngine = null; try { using (_lock.LockStateForWrite()) @@ -127,7 +128,8 @@ namespace System.ComponentModel.Composition.Hosting /// . /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "EnsureCanSet ensures that the property is set only once, Dispose is not required")] - public ExportProvider SourceProvider + [DisallowNull] + public ExportProvider? SourceProvider { get { @@ -139,7 +141,7 @@ namespace System.ComponentModel.Composition.Hosting { ThrowIfDisposed(); - Requires.NotNull(value, nameof(value)); + Requires.NotNull(value!, nameof(value)); using (_lock.LockStateForWrite()) { EnsureCanSet(_sourceProvider); @@ -158,7 +160,7 @@ namespace System.ComponentModel.Composition.Hosting { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - ImportEngine importEngine = new ImportEngine(_sourceProvider, _compositionOptions); + ImportEngine? importEngine = new ImportEngine(_sourceProvider, _compositionOptions); using (_lock.LockStateForWrite()) { if (_importEngine == null) @@ -199,7 +201,7 @@ namespace System.ComponentModel.Composition.Hosting /// it should return an empty of . /// /// - protected override IEnumerable GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) + protected override IEnumerable? GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition) { ThrowIfDisposed(); EnsureRunning(); @@ -208,7 +210,7 @@ namespace System.ComponentModel.Composition.Hosting // failing that use the usual list. We never change the list of parts in place, // but rather copy, change and write a new list atomically. Therefore all we need // to do here is to read the _parts member. - List parts = null; + List? parts = null; using (_lock.LockStateForRead()) { parts = atomicComposition.GetValueAllowNull(this, _parts); @@ -327,7 +329,7 @@ namespace System.ComponentModel.Composition.Hosting // Copy the current list of parts - we are about to modify it // This is an OK thing to do as this is the only method that can modify the List AND Compose can // only be executed on one thread at a time - thus two different threads cannot tramp over each other - List parts = null; + List? parts = null; using (_lock.LockStateForRead()) { parts = _parts.ToList(); // this copies the list @@ -338,7 +340,7 @@ namespace System.ComponentModel.Composition.Hosting parts.Add(part); } - List partsToRemove = null; + List? partsToRemove = null; foreach (ComposablePart part in batch.PartsToRemove) { @@ -396,7 +398,7 @@ namespace System.ComponentModel.Composition.Hosting return new Export(export, () => GetExportedValue(part, export)); } - private object GetExportedValue(ComposablePart part, ExportDefinition export) + private object? GetExportedValue(ComposablePart part, ExportDefinition export) { ThrowIfDisposed(); EnsureRunning(); @@ -439,7 +441,7 @@ namespace System.ComponentModel.Composition.Hosting } [DebuggerStepThrough] - private void EnsureCanSet(T currentValue) + private void EnsureCanSet(T? currentValue) where T : class { if ((_isRunning) || (currentValue != null)) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs index 913f10d4f8c..5c81dc0441c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs @@ -26,7 +26,7 @@ namespace System.ComponentModel.Composition.Hosting _export = export; } - public override IDictionary Metadata + public override IDictionary Metadata { get { return MetadataServices.EmptyMetadata; } } @@ -41,7 +41,7 @@ namespace System.ComponentModel.Composition.Hosting get { return Enumerable.Empty(); } } - public override object GetExportedValue(ExportDefinition definition) + public override object? GetExportedValue(ExportDefinition definition) { Requires.NotNull(definition, nameof(definition)); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.cs index 4aeb28c7362..77fce3bc335 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.cs @@ -33,7 +33,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// The parts to add. /// The parts to remove. - public CompositionBatch(IEnumerable partsToAdd, IEnumerable partsToRemove) + public CompositionBatch(IEnumerable? partsToAdd, IEnumerable? partsToRemove) { _partsToAdd = new List(); if (partsToAdd != null) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs index 6c176112e24..f6d4785ee6d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs @@ -10,7 +10,7 @@ namespace System.ComponentModel.Composition.Hosting { private class CompositionServiceShim : ICompositionService { - private readonly CompositionContainer _innerContainer = null; + private readonly CompositionContainer _innerContainer; public CompositionServiceShim(CompositionContainer innerContainer) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs index b37bf6b7a35..17ac42c5569 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs @@ -15,15 +15,15 @@ namespace System.ComponentModel.Composition.Hosting public partial class CompositionContainer : ExportProvider, ICompositionService, IDisposable { private readonly CompositionOptions _compositionOptions; - private ImportEngine _importEngine; + private ImportEngine? _importEngine; private ComposablePartExportProvider _partExportProvider; private ExportProvider _rootProvider; - private IDisposable _disposableRootProvider; - private CatalogExportProvider _catalogExportProvider; + private IDisposable? _disposableRootProvider; + private CatalogExportProvider? _catalogExportProvider; private ExportProvider _localExportProvider; - private IDisposable _disposableLocalExportProvider; - private ExportProvider _ancestorExportProvider; - private IDisposable _disposableAncestorExportProvider; + private IDisposable? _disposableLocalExportProvider; + private ExportProvider? _ancestorExportProvider; + private IDisposable? _disposableAncestorExportProvider; private readonly ReadOnlyCollection _providers; private volatile bool _isDisposed = false; @@ -34,7 +34,7 @@ namespace System.ComponentModel.Composition.Hosting /// Initializes a new instance of the class. /// public CompositionContainer() - : this((ComposablePartCatalog)null) + : this((ComposablePartCatalog?)null) { } @@ -51,8 +51,8 @@ namespace System.ComponentModel.Composition.Hosting /// /// contains an element that is . /// - public CompositionContainer(params ExportProvider[] providers) : - this((ComposablePartCatalog)null, providers) + public CompositionContainer(params ExportProvider[]? providers) : + this((ComposablePartCatalog?)null, providers) { } @@ -72,8 +72,8 @@ namespace System.ComponentModel.Composition.Hosting /// /// contains an element that is . /// - public CompositionContainer(CompositionOptions compositionOptions, params ExportProvider[] providers) : - this((ComposablePartCatalog)null, compositionOptions, providers) + public CompositionContainer(CompositionOptions compositionOptions, params ExportProvider[]? providers) : + this((ComposablePartCatalog?)null, compositionOptions, providers) { } @@ -90,7 +90,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// contains an element that is . /// - public CompositionContainer(ComposablePartCatalog catalog, params ExportProvider[] providers) : + public CompositionContainer(ComposablePartCatalog? catalog, params ExportProvider[]? providers) : this(catalog, false, providers) { } @@ -111,7 +111,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// contains an element that is . /// - public CompositionContainer(ComposablePartCatalog catalog, bool isThreadSafe, params ExportProvider[] providers) + public CompositionContainer(ComposablePartCatalog? catalog, bool isThreadSafe, params ExportProvider[]? providers) : this(catalog, isThreadSafe ? CompositionOptions.IsThreadSafe : CompositionOptions.Default, providers) { } @@ -132,7 +132,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// contains an element that is . /// - public CompositionContainer(ComposablePartCatalog catalog, CompositionOptions compositionOptions, params ExportProvider[] providers) + public CompositionContainer(ComposablePartCatalog? catalog, CompositionOptions compositionOptions, params ExportProvider[]? providers) { if (compositionOptions > (CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe | CompositionOptions.ExportCompositionService)) { @@ -196,7 +196,7 @@ namespace System.ComponentModel.Composition.Hosting int customProviderStartIndex = 1; if (catalog != null) { - rootProviders[1] = _catalogExportProvider; + rootProviders[1] = _catalogExportProvider!; customProviderStartIndex = 2; } @@ -245,7 +245,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// The has been disposed of. /// - public ComposablePartCatalog Catalog + public ComposablePartCatalog? Catalog { get { @@ -255,7 +255,7 @@ namespace System.ComponentModel.Composition.Hosting } } - internal CatalogExportProvider CatalogExportProvider + internal CatalogExportProvider? CatalogExportProvider { get { @@ -307,34 +307,34 @@ namespace System.ComponentModel.Composition.Hosting { if (!_isDisposed) { - ExportProvider rootProvider = null; - IDisposable disposableAncestorExportProvider = null; - IDisposable disposableLocalExportProvider = null; - IDisposable disposableRootProvider = null; - ComposablePartExportProvider partExportProvider = null; - CatalogExportProvider catalogExportProvider = null; - ImportEngine importEngine = null; + ExportProvider? rootProvider = null; + IDisposable? disposableAncestorExportProvider = null; + IDisposable? disposableLocalExportProvider = null; + IDisposable? disposableRootProvider = null; + ComposablePartExportProvider? partExportProvider = null; + CatalogExportProvider? catalogExportProvider = null; + ImportEngine? importEngine = null; lock (_lock) { if (!_isDisposed) { rootProvider = _rootProvider; - _rootProvider = null; + _rootProvider = null!; disposableRootProvider = _disposableRootProvider; _disposableRootProvider = null; disposableLocalExportProvider = _disposableLocalExportProvider; _disposableLocalExportProvider = null; - _localExportProvider = null; + _localExportProvider = null!; disposableAncestorExportProvider = _disposableAncestorExportProvider; _disposableAncestorExportProvider = null; _ancestorExportProvider = null; partExportProvider = _partExportProvider; - _partExportProvider = null; + _partExportProvider = null!; catalogExportProvider = _catalogExportProvider; _catalogExportProvider = null; @@ -418,9 +418,7 @@ namespace System.ComponentModel.Composition.Hosting { Requires.NotNull(export, nameof(export)); - IDisposable dependency = export as IDisposable; - - if (dependency != null) + if (export is IDisposable dependency) { dependency.Dispose(); } @@ -450,9 +448,7 @@ namespace System.ComponentModel.Composition.Hosting { Requires.NotNull(export, nameof(export)); - IDisposable dependency = export as IDisposable; - - if (dependency != null) + if (export is IDisposable dependency) { dependency.Dispose(); } @@ -546,7 +542,7 @@ namespace System.ComponentModel.Composition.Hosting if (_importEngine == null) { - ImportEngine importEngine = new ImportEngine(this, _compositionOptions); + ImportEngine? importEngine = new ImportEngine(this, _compositionOptions); lock (_lock) { @@ -565,12 +561,12 @@ namespace System.ComponentModel.Composition.Hosting _importEngine.SatisfyImportsOnce(part); } - internal void OnExportsChangedInternal(object sender, ExportsChangeEventArgs e) + internal void OnExportsChangedInternal(object? sender, ExportsChangeEventArgs e) { OnExportsChanged(e); } - internal void OnExportsChangingInternal(object sender, ExportsChangeEventArgs e) + internal void OnExportsChangingInternal(object? sender, ExportsChangeEventArgs e) { OnExportsChanging(e); } @@ -594,19 +590,18 @@ namespace System.ComponentModel.Composition.Hosting /// it should return an empty of . /// /// - protected override IEnumerable GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) + protected override IEnumerable? GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition) { ThrowIfDisposed(); - IEnumerable exports = null; + IEnumerable? exports = null; - object source; - if (!definition.Metadata.TryGetValue(CompositionConstants.ImportSourceMetadataName, out source)) + if (!definition.Metadata.TryGetValue(CompositionConstants.ImportSourceMetadataName, out object? source)) { source = ImportSource.Any; } - switch ((ImportSource)source) + switch ((ImportSource)source!) { case ImportSource.Any: if (_rootProvider == null) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionLock.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionLock.cs index db82fdee1c2..0bf6c62d79b 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionLock.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionLock.cs @@ -23,7 +23,7 @@ namespace System.ComponentModel.Composition.Hosting internal sealed class CompositionLock : IDisposable { // narrow lock - private readonly Lock _stateLock = null; + private readonly Lock? _stateLock = null; // wide lock private static readonly object _compositionLock = new object(); @@ -47,7 +47,7 @@ namespace System.ComponentModel.Composition.Hosting { if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0) { - _stateLock.Dispose(); + _stateLock!.Dispose(); } } } @@ -94,7 +94,7 @@ namespace System.ComponentModel.Composition.Hosting { if (_isThreadSafe) { - return new ReadLock(_stateLock); + return new ReadLock(_stateLock!); } else { @@ -106,7 +106,7 @@ namespace System.ComponentModel.Composition.Hosting { if (_isThreadSafe) { - return new WriteLock(_stateLock); + return new WriteLock(_stateLock!); } else { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs index e4cef2e85c7..48631831d73 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs @@ -14,8 +14,8 @@ namespace System.ComponentModel.Composition.Hosting [DebuggerTypeProxy(typeof(CompositionScopeDefinitionDebuggerProxy))] public class CompositionScopeDefinition : ComposablePartCatalog, INotifyComposablePartCatalogChanged { - private ComposablePartCatalog _catalog; - private IEnumerable _publicSurface = null; + private ComposablePartCatalog? _catalog; + private IEnumerable? _publicSurface = null; private IEnumerable _children = Enumerable.Empty(); private volatile int _isDisposed = 0; @@ -57,7 +57,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// The catalog. /// The children. - private void InitializeCompositionScopeDefinition(ComposablePartCatalog catalog, IEnumerable children, IEnumerable publicSurface) + private void InitializeCompositionScopeDefinition(ComposablePartCatalog catalog, IEnumerable? children, IEnumerable? publicSurface) { _catalog = catalog; if (children != null) @@ -69,8 +69,7 @@ namespace System.ComponentModel.Composition.Hosting _publicSurface = publicSurface; } - INotifyComposablePartCatalogChanged notifyCatalog = _catalog as INotifyComposablePartCatalogChanged; - if (notifyCatalog != null) + if (_catalog is INotifyComposablePartCatalogChanged notifyCatalog) { notifyCatalog.Changed += OnChangedInternal; notifyCatalog.Changing += OnChangingInternal; @@ -89,8 +88,7 @@ namespace System.ComponentModel.Composition.Hosting { if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0) { - INotifyComposablePartCatalogChanged notifyCatalog = _catalog as INotifyComposablePartCatalogChanged; - if (notifyCatalog != null) + if (_catalog is INotifyComposablePartCatalogChanged notifyCatalog) { notifyCatalog.Changed -= OnChangedInternal; notifyCatalog.Changing -= OnChangingInternal; @@ -150,6 +148,7 @@ namespace System.ComponentModel.Composition.Hosting /// The children. public override IEnumerator GetEnumerator() { + Debug.Assert(_catalog != null); return _catalog.GetEnumerator(); } @@ -181,6 +180,7 @@ namespace System.ComponentModel.Composition.Hosting { ThrowIfDisposed(); + Debug.Assert(_catalog != null); return _catalog.GetExports(definition); } @@ -213,12 +213,12 @@ namespace System.ComponentModel.Composition.Hosting /// /// Notify when the contents of the Catalog has changed. /// - public event EventHandler Changed; + public event EventHandler? Changed; /// /// Notify when the contents of the Catalog is changing. /// - public event EventHandler Changing; + public event EventHandler? Changing; /// /// Raises the event. @@ -226,7 +226,7 @@ namespace System.ComponentModel.Composition.Hosting /// The instance containing the event data. protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) { - EventHandler changedEvent = Changed; + EventHandler? changedEvent = Changed; if (changedEvent != null) { changedEvent.Invoke(this, e); @@ -239,19 +239,19 @@ namespace System.ComponentModel.Composition.Hosting /// The instance containing the event data. protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) { - EventHandler changingEvent = Changing; + EventHandler? changingEvent = Changing; if (changingEvent != null) { changingEvent.Invoke(this, e); } } - private void OnChangedInternal(object sender, ComposablePartCatalogChangeEventArgs e) + private void OnChangedInternal(object? sender, ComposablePartCatalogChangeEventArgs e) { OnChanged(e); } - private void OnChangingInternal(object sender, ComposablePartCatalogChangeEventArgs e) + private void OnChangingInternal(object? sender, ComposablePartCatalogChangeEventArgs e) { OnChanging(e); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs index 8b02b5c5e79..08b2a7bd0be 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs @@ -15,8 +15,8 @@ namespace System.ComponentModel.Composition.Hosting /// public class CompositionService : ICompositionService, IDisposable { - private readonly CompositionContainer _compositionContainer = null; - private readonly INotifyComposablePartCatalogChanged _notifyCatalog = null; + private readonly CompositionContainer? _compositionContainer = null; + private readonly INotifyComposablePartCatalogChanged? _notifyCatalog = null; internal CompositionService(ComposablePartCatalog composablePartCatalog) { @@ -73,7 +73,7 @@ namespace System.ComponentModel.Composition.Hosting _compositionContainer.Dispose(); } - private void OnCatalogChanging(object sender, ComposablePartCatalogChangeEventArgs e) + private void OnCatalogChanging(object? sender, ComposablePartCatalogChangeEventArgs e) { throw new ChangeRejectedException(SR.NotSupportedCatalogChanges); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs index 93cf9ace32b..8c3046711ac 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs @@ -62,7 +62,7 @@ namespace System.ComponentModel.Composition.Hosting } } - internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContractType, Type memberType) + internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContractType, Type? memberType) { if (specifiedContractType == null) { @@ -102,7 +102,7 @@ namespace System.ComponentModel.Composition.Hosting return GenericServices.GetGenericName(originalTypeIdentity, GenericServices.GetGenericParametersOrder(typeIdentityType), GenericServices.GetPureGenericArity(typeIdentityType)); } - internal static void GetContractInfoFromExport(this MemberInfo member, ExportAttribute export, out Type typeIdentityType, out string contractName) + internal static void GetContractInfoFromExport(this MemberInfo member, ExportAttribute export, out Type? typeIdentityType, out string contractName) { typeIdentityType = member.GetTypeIdentityTypeFromExport(export); if (!string.IsNullOrEmpty(export.ContractName)) @@ -115,7 +115,7 @@ namespace System.ComponentModel.Composition.Hosting } } - internal static string GetTypeIdentityFromExport(this MemberInfo member, Type typeIdentityType) + internal static string GetTypeIdentityFromExport(this MemberInfo member, Type? typeIdentityType) { if (typeIdentityType != null) { @@ -128,7 +128,7 @@ namespace System.ComponentModel.Composition.Hosting } else { - MethodInfo method = member as MethodInfo; + MethodInfo? method = member as MethodInfo; if (method == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); @@ -137,7 +137,7 @@ namespace System.ComponentModel.Composition.Hosting } } - private static Type GetTypeIdentityTypeFromExport(this MemberInfo member, ExportAttribute export) + private static Type? GetTypeIdentityTypeFromExport(this MemberInfo member, ExportAttribute export) { if (export.ContractType != null) { @@ -176,7 +176,7 @@ namespace System.ComponentModel.Composition.Hosting return AttributedModelServices.GetContractName(contractType); } - internal static string GetTypeIdentityFromImport(this IAttributedImport import, ImportType importType) + internal static string? GetTypeIdentityFromImport(this IAttributedImport import, ImportType importType) { Type contractType = import.GetContractTypeFromImport(importType); @@ -189,9 +189,9 @@ namespace System.ComponentModel.Composition.Hosting return AttributedModelServices.GetTypeIdentity(contractType); } - internal static IDictionary GetPartMetadataForType(this Type type, CreationPolicy creationPolicy) + internal static IDictionary GetPartMetadataForType(this Type type, CreationPolicy creationPolicy) { - IDictionary dictionary = new Dictionary(StringComparers.MetadataKeyNames); + IDictionary dictionary = new Dictionary(StringComparers.MetadataKeyNames); if (creationPolicy != CreationPolicy.Any) { @@ -222,13 +222,13 @@ namespace System.ComponentModel.Composition.Hosting // add constraints bool hasConstraints = false; - object[] genericParameterConstraints = new object[genericArguments.Length]; + object?[] genericParameterConstraints = new object?[genericArguments.Length]; GenericParameterAttributes[] genericParameterAttributes = new GenericParameterAttributes[genericArguments.Length]; for (int i = 0; i < genericArguments.Length; i++) { Type genericArgument = genericArguments[i]; - Type[] constraints = genericArgument.GetGenericParameterConstraints(); + Type[]? constraints = genericArgument.GetGenericParameterConstraints(); if (constraints.Length == 0) { constraints = null; @@ -261,9 +261,9 @@ namespace System.ComponentModel.Composition.Hosting } } - internal static void TryExportMetadataForMember(this MemberInfo member, out IDictionary dictionary) + internal static void TryExportMetadataForMember(this MemberInfo member, out IDictionary dictionary) { - dictionary = new Dictionary(); + dictionary = new Dictionary(); foreach (var attr in member.GetAttributes()) { @@ -290,7 +290,7 @@ namespace System.ComponentModel.Composition.Hosting if ((attrType != CompositionServices.ExportAttributeType) && attrType.IsAttributeDefined(true)) { bool allowsMultiple = false; - AttributeUsageAttribute usage = attrType.GetFirstAttribute(true); + AttributeUsageAttribute? usage = attrType.GetFirstAttribute(true); if (usage != null) { @@ -307,10 +307,10 @@ namespace System.ComponentModel.Composition.Hosting if (reservedMetadataNames.Contains(pi.Name, StringComparers.MetadataKeyNames)) { - throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_ReservedMetadataNameUsed, member.GetDisplayName(), provider.Name); + throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_ReservedMetadataNameUsed, pi.GetDisplayName(), pi.Name); } - object value = pi.GetValue(attr, null); + object? value = pi.GetValue(attr, null); if (value != null && !IsValidAttributeType(value.GetType())) { @@ -339,10 +339,9 @@ namespace System.ComponentModel.Composition.Hosting return; } - private static bool TryContributeMetadataValue(this IDictionary dictionary, string name, object value, Type valueType, bool allowsMultiple) + private static bool TryContributeMetadataValue(this IDictionary dictionary, string name, object? value, Type? valueType, bool allowsMultiple) { - object metadataValue; - if (!dictionary.TryGetValue(name, out metadataValue)) + if (!dictionary.TryGetValue(name, out object? metadataValue)) { if (allowsMultiple) { @@ -371,13 +370,13 @@ namespace System.ComponentModel.Composition.Hosting private class MetadataList { - private Type _arrayType = null; + private Type? _arrayType = null; private bool _containsNulls = false; private static readonly Type ObjectType = typeof(object); private static readonly Type TypeType = typeof(Type); - private readonly Collection _innerList = new Collection(); + private readonly Collection _innerList = new Collection(); - public void Add(object item, Type itemType) + public void Add(object? item, Type? itemType) { _containsNulls |= (item == null); @@ -477,7 +476,7 @@ namespace System.ComponentModel.Composition.Hosting // return result; //} - internal static IEnumerable> GetRequiredMetadata(Type metadataViewType) + internal static IEnumerable> GetRequiredMetadata(Type? metadataViewType) { if ((metadataViewType == null) || ExportServices.IsDefaultMetadataViewType(metadataViewType) || @@ -498,19 +497,19 @@ namespace System.ComponentModel.Composition.Hosting return properties.Select(property => new KeyValuePair(property.Name, property.PropertyType)); } - internal static IDictionary GetImportMetadata(ImportType importType, IAttributedImport attributedImport) + internal static IDictionary GetImportMetadata(ImportType importType, IAttributedImport attributedImport) { return GetImportMetadata(importType.ContractType, attributedImport); } - internal static IDictionary GetImportMetadata(Type type, IAttributedImport attributedImport) + internal static IDictionary GetImportMetadata(Type type, IAttributedImport? attributedImport) { - Dictionary metadata = null; + Dictionary? metadata = null; //Prior to V4.5 MEF did not support ImportMetadata if (type.IsGenericType) { - metadata = new Dictionary(); + metadata = new Dictionary(); if (type.ContainsGenericParameters) { @@ -528,7 +527,7 @@ namespace System.ComponentModel.Composition.Hosting { if (metadata == null) { - metadata = new Dictionary(); + metadata = new Dictionary(); } metadata[CompositionConstants.ImportSourceMetadataName] = attributedImport.Source; } @@ -543,7 +542,7 @@ namespace System.ComponentModel.Composition.Hosting } } - internal static object GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition) + internal static object? GetExportedValueFromComposedPart(ImportEngine? engine, ComposablePart part, ExportDefinition definition) { if (engine != null) { @@ -585,7 +584,7 @@ namespace System.ComponentModel.Composition.Hosting } } - internal static CompositionResult TryFire(EventHandler _delegate, object sender, TEventArgs e) + internal static CompositionResult TryFire(EventHandler _delegate, object? sender, TEventArgs e) where TEventArgs : EventArgs { CompositionResult result = CompositionResult.SucceededResult; @@ -606,9 +605,7 @@ namespace System.ComponentModel.Composition.Hosting internal static CreationPolicy GetRequiredCreationPolicy(this ImportDefinition definition) { - ContractBasedImportDefinition contractDefinition = definition as ContractBasedImportDefinition; - - if (contractDefinition != null) + if (definition is ContractBasedImportDefinition contractDefinition) { return contractDefinition.RequiredCreationPolicy; } @@ -665,7 +662,7 @@ namespace System.ComponentModel.Composition.Hosting // Single-dimensional arrays of the above types. if (arrayAllowed && type.IsArray && type.GetArrayRank() == 1 && - IsValidAttributeType(type.GetElementType(), false)) + IsValidAttributeType(type.GetElementType()!, false)) { return true; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.DirectoryCatalogDebuggerProxy.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.DirectoryCatalogDebuggerProxy.cs index ddaaee68313..6432b6aa0a4 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.DirectoryCatalogDebuggerProxy.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.DirectoryCatalogDebuggerProxy.cs @@ -33,7 +33,7 @@ namespace System.ComponentModel.Composition.Hosting } } - public ReflectionContext ReflectionContext + public ReflectionContext? ReflectionContext { get { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs index fd5aa01297c..a6937445c3a 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs @@ -23,16 +23,16 @@ namespace System.ComponentModel.Composition.Hosting public partial class DirectoryCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged, ICompositionElement { private readonly Lock _thisLock = new Lock(); - private readonly ICompositionElement _definitionOrigin = null; - private ComposablePartCatalogCollection _catalogCollection; - private Dictionary _assemblyCatalogs; + private readonly ICompositionElement? _definitionOrigin = null; + private ComposablePartCatalogCollection _catalogCollection = null!; // Always initialized with Initialize() + private Dictionary _assemblyCatalogs = null!; private volatile bool _isDisposed = false; - private string _path; - private string _fullPath; - private string _searchPattern; - private ReadOnlyCollection _loadedFiles; + private string _path = null!; + private string _fullPath = null!; + private string _searchPattern = null!; + private ReadOnlyCollection _loadedFiles = null!; - private readonly ReflectionContext _reflectionContext = null; + private readonly ReflectionContext? _reflectionContext = null; /// /// Creates a catalog of s based on all the *.dll files @@ -434,12 +434,12 @@ namespace System.ComponentModel.Composition.Hosting /// /// Notify when the contents of the Catalog has changed. /// - public event EventHandler Changed; + public event EventHandler? Changed; /// /// Notify when the contents of the Catalog has changing. /// - public event EventHandler Changing; + public event EventHandler? Changing; /// /// Releases unmanaged and - optionally - managed resources @@ -454,7 +454,7 @@ namespace System.ComponentModel.Composition.Hosting if (!_isDisposed) { bool disposeLock = false; - ComposablePartCatalogCollection catalogs = null; + ComposablePartCatalogCollection? catalogs = null; try { @@ -464,8 +464,8 @@ namespace System.ComponentModel.Composition.Hosting { disposeLock = true; catalogs = _catalogCollection; - _catalogCollection = null; - _assemblyCatalogs = null; + _catalogCollection = null!; + _assemblyCatalogs = null!; _isDisposed = true; } } @@ -532,7 +532,7 @@ namespace System.ComponentModel.Composition.Hosting /// protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) { - EventHandler changedEvent = Changed; + EventHandler? changedEvent = Changed; if (changedEvent != null) { changedEvent(this, e); @@ -547,7 +547,7 @@ namespace System.ComponentModel.Composition.Hosting /// protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) { - EventHandler changingEvent = Changing; + EventHandler? changingEvent = Changing; if (changingEvent != null) { changingEvent(this, e); @@ -662,9 +662,9 @@ namespace System.ComponentModel.Composition.Hosting return GetDisplayName(); } - private AssemblyCatalog CreateAssemblyCatalogGuarded(string assemblyFilePath) + private AssemblyCatalog? CreateAssemblyCatalogGuarded(string assemblyFilePath) { - Exception exception = null; + Exception? exception = null; try { @@ -704,7 +704,7 @@ namespace System.ComponentModel.Composition.Hosting IEnumerable filesToAdd = afterFiles.Except(beforeFiles); foreach (string file in filesToAdd) { - AssemblyCatalog catalog = CreateAssemblyCatalogGuarded(file); + AssemblyCatalog? catalog = CreateAssemblyCatalogGuarded(file); if (catalog != null) { @@ -717,8 +717,7 @@ namespace System.ComponentModel.Composition.Hosting { foreach (string file in filesToRemove) { - AssemblyCatalog catalog; - if (_assemblyCatalogs.TryGetValue(file, out catalog)) + if (_assemblyCatalogs.TryGetValue(file, out AssemblyCatalog? catalog)) { catalogsToRemove.Add(new Tuple(file, catalog)); } @@ -758,8 +757,7 @@ namespace System.ComponentModel.Composition.Hosting foreach (string file in _loadedFiles) { - AssemblyCatalog assemblyCatalog = null; - assemblyCatalog = CreateAssemblyCatalogGuarded(file); + AssemblyCatalog? assemblyCatalog = CreateAssemblyCatalogGuarded(file); if (assemblyCatalog != null) { @@ -797,7 +795,7 @@ namespace System.ComponentModel.Composition.Hosting /// This property always returns . /// [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] - ICompositionElement ICompositionElement.Origin + ICompositionElement? ICompositionElement.Origin { get { return null; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs index 3e38009b78c..c986f2fdf89 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs @@ -57,9 +57,9 @@ namespace System.ComponentModel.Composition.Hosting /// /// The has been disposed of. /// - public Lazy GetExport() + public Lazy? GetExport() { - return GetExport((string)null); + return GetExport((string?)null); } /// @@ -108,7 +108,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// The has been disposed of. /// - public Lazy GetExport(string contractName) + public Lazy? GetExport(string? contractName) { return GetExportCore(contractName); } @@ -158,9 +158,9 @@ namespace System.ComponentModel.Composition.Hosting /// /// The has been disposed of. /// - public Lazy GetExport() + public Lazy? GetExport() { - return GetExport((string)null); + return GetExport((string?)null); } /// @@ -209,7 +209,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// The has been disposed of. /// - public Lazy GetExport(string contractName) + public Lazy? GetExport(string? contractName) { return GetExportCore(contractName); } @@ -260,7 +260,7 @@ namespace System.ComponentModel.Composition.Hosting /// The has been disposed of. /// [SuppressMessage("Microsoft.Design", "CA1006")] - public IEnumerable> GetExports(Type type, Type metadataViewType, string contractName) + public IEnumerable> GetExports(Type type, Type? metadataViewType, string? contractName) { IEnumerable exports = GetExportsCore(type, metadataViewType, contractName, ImportCardinality.ZeroOrMore); Collection> result = new Collection>(); @@ -309,7 +309,7 @@ namespace System.ComponentModel.Composition.Hosting [SuppressMessage("Microsoft.Design", "CA1006")] public IEnumerable> GetExports() { - return GetExports((string)null); + return GetExports((string?)null); } /// @@ -349,7 +349,7 @@ namespace System.ComponentModel.Composition.Hosting /// The has been disposed of. /// [SuppressMessage("Microsoft.Design", "CA1006")] - public IEnumerable> GetExports(string contractName) + public IEnumerable> GetExports(string? contractName) { return GetExportsCore(contractName); } @@ -390,7 +390,7 @@ namespace System.ComponentModel.Composition.Hosting [SuppressMessage("Microsoft.Design", "CA1006")] public IEnumerable> GetExports() { - return GetExports((string)null); + return GetExports((string?)null); } /// @@ -431,7 +431,7 @@ namespace System.ComponentModel.Composition.Hosting /// The has been disposed of. /// [SuppressMessage("Microsoft.Design", "CA1006")] - public IEnumerable> GetExports(string contractName) + public IEnumerable> GetExports(string? contractName) { return GetExportsCore(contractName); } @@ -479,9 +479,10 @@ namespace System.ComponentModel.Composition.Hosting /// An error occurred during composition. will /// contain a collection of errors that occurred. /// + [return: MaybeNull] public T GetExportedValue() { - return GetExportedValue((string)null); + return GetExportedValue((string?)null); } /// @@ -529,7 +530,8 @@ namespace System.ComponentModel.Composition.Hosting /// An error occurred during composition. will /// contain a collection of errors that occurred. /// - public T GetExportedValue(string contractName) + [return: MaybeNull] + public T GetExportedValue(string? contractName) { return GetExportedValueCore(contractName, ImportCardinality.ExactlyOne); } @@ -579,9 +581,10 @@ namespace System.ComponentModel.Composition.Hosting /// An error occurred during composition. will /// contain a collection of errors that occurred. /// + [return: MaybeNull] public T GetExportedValueOrDefault() { - return GetExportedValueOrDefault((string)null); + return GetExportedValueOrDefault((string?)null); } /// @@ -629,7 +632,8 @@ namespace System.ComponentModel.Composition.Hosting /// An error occurred during composition. will /// contain a collection of errors that occurred. /// - public T GetExportedValueOrDefault(string contractName) + [return: MaybeNull] + public T GetExportedValueOrDefault(string? contractName) { return GetExportedValueCore(contractName, ImportCardinality.ZeroOrOne); } @@ -670,7 +674,7 @@ namespace System.ComponentModel.Composition.Hosting /// public IEnumerable GetExportedValues() { - return GetExportedValues((string)null); + return GetExportedValues((string?)null); } /// @@ -709,14 +713,14 @@ namespace System.ComponentModel.Composition.Hosting /// An error occurred during composition. will /// contain a collection of errors that occurred. /// - public IEnumerable GetExportedValues(string contractName) + public IEnumerable GetExportedValues(string? contractName) { return GetExportedValuesCore(contractName); } - private IEnumerable GetExportedValuesCore(string contractName) + private IEnumerable GetExportedValuesCore(string? contractName) { - IEnumerable exports = GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore); + IEnumerable exports = GetExportsCore(typeof(T), (Type?)null, contractName, ImportCardinality.ZeroOrMore); Collection result = new Collection(); foreach (Export export in exports) @@ -726,21 +730,22 @@ namespace System.ComponentModel.Composition.Hosting return result; } - private T GetExportedValueCore(string contractName, ImportCardinality cardinality) + [return: MaybeNull] + private T GetExportedValueCore(string? contractName, ImportCardinality cardinality) { if (!cardinality.IsAtMostOne()) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - Export export = GetExportsCore(typeof(T), (Type)null, contractName, cardinality).SingleOrDefault(); + Export? export = GetExportsCore(typeof(T), (Type?)null, contractName, cardinality).SingleOrDefault(); - return (export != null) ? ExportServices.GetCastedExportedValue(export) : default(T); + return (export != null) ? ExportServices.GetCastedExportedValue(export) : default(T)!; } - private IEnumerable> GetExportsCore(string contractName) + private IEnumerable> GetExportsCore(string? contractName) { - IEnumerable exports = GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore); + IEnumerable exports = GetExportsCore(typeof(T), (Type?)null, contractName, ImportCardinality.ZeroOrMore); Collection> result = new Collection>(); foreach (Export export in exports) @@ -750,7 +755,7 @@ namespace System.ComponentModel.Composition.Hosting return result; } - private IEnumerable> GetExportsCore(string contractName) + private IEnumerable> GetExportsCore(string? contractName) { IEnumerable exports = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ZeroOrMore); @@ -762,21 +767,21 @@ namespace System.ComponentModel.Composition.Hosting return result; } - private Lazy GetExportCore(string contractName) + private Lazy? GetExportCore(string? contractName) { - Export export = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ExactlyOne).SingleOrDefault(); + Export? export = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ExactlyOne).SingleOrDefault(); return (export != null) ? ExportServices.CreateStronglyTypedLazyOfTM(export) : null; } - private Lazy GetExportCore(string contractName) + private Lazy? GetExportCore(string? contractName) { - Export export = GetExportsCore(typeof(T), null, contractName, ImportCardinality.ExactlyOne).SingleOrDefault(); + Export? export = GetExportsCore(typeof(T), null, contractName, ImportCardinality.ExactlyOne).SingleOrDefault(); return (export != null) ? ExportServices.CreateStronglyTypedLazyOfT(export) : null; } - private IEnumerable GetExportsCore(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality) + private IEnumerable GetExportsCore(Type type, Type? metadataViewType, string? contractName, ImportCardinality cardinality) { // Only 'type' cannot be null - the other parameters have sensible defaults. Requires.NotNull(type, nameof(type)); @@ -818,9 +823,9 @@ namespace System.ComponentModel.Composition.Hosting } IEnumerable> requiredMetadata = CompositionServices.GetRequiredMetadata(metadataViewType); - IDictionary metadata = CompositionServices.GetImportMetadata(type, null); + IDictionary metadata = CompositionServices.GetImportMetadata(type, null); - string requiredTypeIdentity = null; + string? requiredTypeIdentity = null; if (type != typeof(object)) { requiredTypeIdentity = AttributedModelServices.GetTypeIdentity(type); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs index bc9fc3d8dc1..e583cd5c791 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs @@ -26,12 +26,12 @@ namespace System.ComponentModel.Composition.Hosting /// /// Occurs when the exports in the have changed. /// - public event EventHandler ExportsChanged; + public event EventHandler? ExportsChanged; /// /// Occurs when the exports in the are changing. /// - public event EventHandler ExportsChanging; + public event EventHandler? ExportsChanging; /// /// Returns all exports that match the conditions of the specified import. @@ -94,12 +94,11 @@ namespace System.ComponentModel.Composition.Hosting /// objects that match the conditions of the specified . /// /// - public IEnumerable GetExports(ImportDefinition definition, AtomicComposition atomicComposition) + public IEnumerable GetExports(ImportDefinition definition, AtomicComposition? atomicComposition) { Requires.NotNull(definition, nameof(definition)); - IEnumerable exports; - ExportCardinalityCheckResult result = TryGetExportsCore(definition, atomicComposition, out exports); + ExportCardinalityCheckResult result = TryGetExportsCore(definition, atomicComposition, out IEnumerable? exports); switch (result) { case ExportCardinalityCheckResult.Match: @@ -141,11 +140,10 @@ namespace System.ComponentModel.Composition.Hosting /// /// is . /// - public bool TryGetExports(ImportDefinition definition, AtomicComposition atomicComposition, out IEnumerable exports) + public bool TryGetExports(ImportDefinition definition, AtomicComposition? atomicComposition, out IEnumerable? exports) { Requires.NotNull(definition, nameof(definition)); - exports = null; ExportCardinalityCheckResult result = TryGetExportsCore(definition, atomicComposition, out exports); return (result == ExportCardinalityCheckResult.Match); } @@ -171,7 +169,7 @@ namespace System.ComponentModel.Composition.Hosting /// specified , an should be returned. /// /// - protected abstract IEnumerable GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition); + protected abstract IEnumerable? GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition); /// /// Raises the event. @@ -181,7 +179,7 @@ namespace System.ComponentModel.Composition.Hosting /// protected virtual void OnExportsChanged(ExportsChangeEventArgs e) { - EventHandler changedEvent = ExportsChanged; + EventHandler? changedEvent = ExportsChanged; if (changedEvent != null) { CompositionResult result = CompositionServices.TryFire(changedEvent, this, e); @@ -197,7 +195,7 @@ namespace System.ComponentModel.Composition.Hosting /// protected virtual void OnExportsChanging(ExportsChangeEventArgs e) { - EventHandler changingEvent = ExportsChanging; + EventHandler? changingEvent = ExportsChanging; if (changingEvent != null) { CompositionResult result = CompositionServices.TryFire(changingEvent, this, e); @@ -205,7 +203,7 @@ namespace System.ComponentModel.Composition.Hosting } } - private ExportCardinalityCheckResult TryGetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition, out IEnumerable exports) + private ExportCardinalityCheckResult TryGetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition, out IEnumerable? exports) { if (definition == null) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs index e4300f2f895..f57c618287a 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs @@ -19,7 +19,7 @@ namespace System.ComponentModel.Composition.Hosting { private readonly IEnumerable _addedExports; private readonly IEnumerable _removedExports; - private IEnumerable _changedContractNames = null; + private IEnumerable? _changedContractNames = null; /// /// Initializes a new instance of the class with @@ -43,7 +43,7 @@ namespace System.ComponentModel.Composition.Hosting /// or is . /// public ExportsChangeEventArgs(IEnumerable addedExports, - IEnumerable removedExports, AtomicComposition atomicComposition) + IEnumerable removedExports, AtomicComposition? atomicComposition) { Requires.NotNull(addedExports, nameof(addedExports)); Requires.NotNull(removedExports, nameof(removedExports)); @@ -123,6 +123,6 @@ namespace System.ComponentModel.Composition.Hosting /// When the value is non-null it should be used to record temporary changed state /// and actions that will be executed when the atomicComposition is completeed. /// - public AtomicComposition AtomicComposition { get; private set; } + public AtomicComposition? AtomicComposition { get; private set; } } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs index 70416330a36..2b4f0e40993 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs @@ -5,6 +5,8 @@ using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Linq; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics; namespace System.ComponentModel.Composition.Hosting { @@ -14,7 +16,7 @@ namespace System.ComponentModel.Composition.Hosting { private readonly IEnumerable _parts; private readonly Func _importFilter; - private Dictionary> _exportersIndex; + private Dictionary>? _exportersIndex; public DependenciesTraversal(FilteredCatalog catalog, Func importFilter) { @@ -50,8 +52,7 @@ namespace System.ComponentModel.Composition.Hosting private void AddToExportersIndex(string contractName, ComposablePartDefinition part) { - List parts = null; - if (!_exportersIndex.TryGetValue(contractName, out parts)) + if (!_exportersIndex!.TryGetValue(contractName, out List? parts)) { parts = new List(); _exportersIndex.Add(contractName, parts); @@ -59,16 +60,17 @@ namespace System.ComponentModel.Composition.Hosting parts.Add(part); } - public bool TryTraverse(ComposablePartDefinition part, out IEnumerable reachableParts) + public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out IEnumerable? reachableParts) { reachableParts = null; - List reachablePartList = null; + List? reachablePartList = null; // Go through all part imports foreach (ImportDefinition import in part.ImportDefinitions.Where(_importFilter)) { // Find all parts that we know will import each export - List candidateReachableParts = null; + List? candidateReachableParts = null; + Debug.Assert(_exportersIndex != null); foreach (var contractName in import.GetCandidateContractNames(part)) { if (_exportersIndex.TryGetValue(contractName, out candidateReachableParts)) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs index f4d39cae340..b9355b5dc97 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs @@ -5,6 +5,8 @@ using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Linq; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel.Composition.Hosting { @@ -20,7 +22,7 @@ namespace System.ComponentModel.Composition.Hosting { private readonly IEnumerable _parts; private readonly Func _importFilter; - private Dictionary> _importersIndex; + private Dictionary>? _importersIndex; public DependentsTraversal(FilteredCatalog catalog, Func importFilter) { @@ -59,8 +61,7 @@ namespace System.ComponentModel.Composition.Hosting private void AddToImportersIndex(string contractName, ComposablePartDefinition part) { - List parts = null; - if (!_importersIndex.TryGetValue(contractName, out parts)) + if (!_importersIndex!.TryGetValue(contractName, out List? parts)) { parts = new List(); _importersIndex.Add(contractName, parts); @@ -68,16 +69,17 @@ namespace System.ComponentModel.Composition.Hosting parts.Add(part); } - public bool TryTraverse(ComposablePartDefinition part, out IEnumerable reachableParts) + public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out IEnumerable? reachableParts) { reachableParts = null; - List reachablePartList = null; + List? reachablePartList = null; + Debug.Assert(_importersIndex != null); // Go through all part exports foreach (ExportDefinition export in part.ExportDefinitions) { // Find all parts that we know will import each export - List candidateReachableParts = null; + List? candidateReachableParts = null; if (_importersIndex.TryGetValue(export.ContractName, out candidateReachableParts)) { // find if they actually match diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.IComposablePartCatalogTraversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.IComposablePartCatalogTraversal.cs index 578544551fd..7cc17dd2cd8 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.IComposablePartCatalogTraversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.IComposablePartCatalogTraversal.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; +using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel.Composition.Hosting { @@ -19,7 +20,7 @@ namespace System.ComponentModel.Composition.Hosting internal interface IComposablePartCatalogTraversal { void Initialize(); - bool TryTraverse(ComposablePartDefinition part, out IEnumerable reachableParts); + bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out IEnumerable? reachableParts); } } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs index ff3ed478c29..a2829929379 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs @@ -98,8 +98,7 @@ namespace System.ComponentModel.Composition.Hosting { if (traversedParts.Add(part)) { - IEnumerable partsToTraverse = null; - if (traversal.TryTraverse(part, out partsToTraverse)) + if (traversal.TryTraverse(part, out IEnumerable? partsToTraverse)) { GetTraversalClosure(partsToTraverse, traversedParts, traversal); } @@ -109,8 +108,7 @@ namespace System.ComponentModel.Composition.Hosting private void FreezeInnerCatalog() { - INotifyComposablePartCatalogChanged innerNotifyCatalog = _innerCatalog as INotifyComposablePartCatalogChanged; - if (innerNotifyCatalog != null) + if (_innerCatalog is INotifyComposablePartCatalogChanged innerNotifyCatalog) { innerNotifyCatalog.Changing += ThrowOnRecomposition; } @@ -118,14 +116,13 @@ namespace System.ComponentModel.Composition.Hosting private void UnfreezeInnerCatalog() { - INotifyComposablePartCatalogChanged innerNotifyCatalog = _innerCatalog as INotifyComposablePartCatalogChanged; - if (innerNotifyCatalog != null) + if (_innerCatalog is INotifyComposablePartCatalogChanged innerNotifyCatalog) { innerNotifyCatalog.Changing -= ThrowOnRecomposition; } } - private static void ThrowOnRecomposition(object sender, ComposablePartCatalogChangeEventArgs e) + private static void ThrowOnRecomposition(object? sender, ComposablePartCatalogChangeEventArgs e) { throw new ChangeRejectedException(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs index 1270460d380..6b39064e59d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs @@ -16,7 +16,7 @@ namespace System.ComponentModel.Composition.Hosting { private readonly Func _filter; private ComposablePartCatalog _innerCatalog; - private FilteredCatalog _complement; + private FilteredCatalog? _complement; private readonly object _lock = new object(); private volatile bool _isDisposed = false; @@ -30,7 +30,7 @@ namespace System.ComponentModel.Composition.Hosting { } - internal FilteredCatalog(ComposablePartCatalog catalog, Func filter, FilteredCatalog complement) + internal FilteredCatalog(ComposablePartCatalog catalog, Func filter, FilteredCatalog? complement) { Requires.NotNull(catalog, nameof(catalog)); Requires.NotNull(filter, nameof(filter)); @@ -39,8 +39,7 @@ namespace System.ComponentModel.Composition.Hosting _filter = (p) => filter.Invoke(p.GetGenericPartDefinition() ?? p); _complement = complement; - INotifyComposablePartCatalogChanged notifyCatalog = _innerCatalog as INotifyComposablePartCatalogChanged; - if (notifyCatalog != null) + if (_innerCatalog is INotifyComposablePartCatalogChanged notifyCatalog) { notifyCatalog.Changed += OnChangedInternal; notifyCatalog.Changing += OnChangingInternal; @@ -59,7 +58,7 @@ namespace System.ComponentModel.Composition.Hosting { if (!_isDisposed) { - INotifyComposablePartCatalogChanged notifyCatalog = null; + INotifyComposablePartCatalogChanged? notifyCatalog = null; try { lock (_lock) @@ -68,7 +67,7 @@ namespace System.ComponentModel.Composition.Hosting { _isDisposed = true; notifyCatalog = _innerCatalog as INotifyComposablePartCatalogChanged; - _innerCatalog = null; + _innerCatalog = null!; } } } @@ -106,7 +105,7 @@ namespace System.ComponentModel.Composition.Hosting if (_complement == null) { - FilteredCatalog complement = new FilteredCatalog(_innerCatalog, p => !_filter(p), this); + FilteredCatalog? complement = new FilteredCatalog(_innerCatalog, p => !_filter(p), this); lock (_lock) { if (_complement == null) @@ -171,12 +170,12 @@ namespace System.ComponentModel.Composition.Hosting /// /// Notify when the contents of the Catalog has changed. /// - public event EventHandler Changed; + public event EventHandler? Changed; /// /// Notify when the contents of the Catalog is changing. /// - public event EventHandler Changing; + public event EventHandler? Changing; /// /// Raises the event. @@ -184,7 +183,7 @@ namespace System.ComponentModel.Composition.Hosting /// The instance containing the event data. protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) { - EventHandler changedEvent = Changed; + EventHandler? changedEvent = Changed; if (changedEvent != null) { changedEvent.Invoke(this, e); @@ -197,32 +196,32 @@ namespace System.ComponentModel.Composition.Hosting /// The instance containing the event data. protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) { - EventHandler changingEvent = Changing; + EventHandler? changingEvent = Changing; if (changingEvent != null) { changingEvent.Invoke(this, e); } } - private void OnChangedInternal(object sender, ComposablePartCatalogChangeEventArgs e) + private void OnChangedInternal(object? sender, ComposablePartCatalogChangeEventArgs e) { var processedArgs = ProcessEventArgs(e); if (processedArgs != null) { - OnChanged(ProcessEventArgs(processedArgs)); + OnChanged(ProcessEventArgs(processedArgs)!); } } - private void OnChangingInternal(object sender, ComposablePartCatalogChangeEventArgs e) + private void OnChangingInternal(object? sender, ComposablePartCatalogChangeEventArgs e) { var processedArgs = ProcessEventArgs(e); if (processedArgs != null) { - OnChanging(ProcessEventArgs(processedArgs)); + OnChanging(ProcessEventArgs(processedArgs)!); } } - private ComposablePartCatalogChangeEventArgs ProcessEventArgs(ComposablePartCatalogChangeEventArgs e) + private ComposablePartCatalogChangeEventArgs? ProcessEventArgs(ComposablePartCatalogChangeEventArgs e) { // the constructor for ComposablePartCatalogChangeEventArgs takes a snapshot of the arguments, so we don't have to var result = new ComposablePartCatalogChangeEventArgs( diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/INotifyComposablePartCatalogChanged.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/INotifyComposablePartCatalogChanged.cs index d827af22fbf..6f803205675 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/INotifyComposablePartCatalogChanged.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/INotifyComposablePartCatalogChanged.cs @@ -9,7 +9,7 @@ namespace System.ComponentModel.Composition.Hosting /// public interface INotifyComposablePartCatalogChanged { - event EventHandler Changed; - event EventHandler Changing; + event EventHandler? Changed; + event EventHandler? Changing; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs index 4628d7359c2..bd6d870a485 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs @@ -18,9 +18,9 @@ namespace System.ComponentModel.Composition.Hosting private readonly ImportEngine _importEngine; private readonly List _addedPartManagers = new List(); private readonly List _removedPartManagers = new List(); - private readonly EngineContext _parentEngineContext; + private readonly EngineContext? _parentEngineContext; - public EngineContext(ImportEngine importEngine, EngineContext parentEngineContext) + public EngineContext(ImportEngine importEngine, EngineContext? parentEngineContext) { _importEngine = importEngine; _parentEngineContext = parentEngineContext; @@ -52,7 +52,7 @@ namespace System.ComponentModel.Composition.Hosting } } - public IEnumerable GetAddedPartManagers() + public IEnumerable? GetAddedPartManagers() { if (_parentEngineContext != null) { @@ -61,7 +61,7 @@ namespace System.ComponentModel.Composition.Hosting return _addedPartManagers; } - public IEnumerable GetRemovedPartManagers() + public IEnumerable? GetRemovedPartManagers() { if (_parentEngineContext != null) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs index e3e8999343a..9adc214c1c2 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs @@ -18,9 +18,9 @@ namespace System.ComponentModel.Composition.Hosting /// private class PartManager { - private Dictionary> _importedDisposableExports; - private Dictionary _importCache; - private string[] _importedContractNames; + private Dictionary>? _importedDisposableExports; + private Dictionary? _importCache; + private string[]? _importedContractNames; private readonly ComposablePart _part; private ImportState _state = ImportState.NoImportsSatisfied; private readonly ImportEngine _importEngine; @@ -95,7 +95,7 @@ namespace System.ComponentModel.Composition.Hosting } } - public void SetSavedImport(ImportDefinition import, Export[] exports, AtomicComposition atomicComposition) + public void SetSavedImport(ImportDefinition import, Export[]? exports, AtomicComposition? atomicComposition) { if (atomicComposition != null) { @@ -109,15 +109,15 @@ namespace System.ComponentModel.Composition.Hosting if (_importCache == null) { - _importCache = new Dictionary(); + _importCache = new Dictionary(); } _importCache[import] = exports; } - public Export[] GetSavedImport(ImportDefinition import) + public Export[]? GetSavedImport(ImportDefinition import) { - Export[] exports = null; + Export[]? exports = null; if (_importCache != null) { // We don't care about the return value we just want the exports @@ -150,11 +150,10 @@ namespace System.ComponentModel.Composition.Hosting { // Determine if there are any new disposable exports, optimizing for the most // likely case, which is that there aren't any - List disposableExports = null; + List? disposableExports = null; foreach (var export in exports) { - IDisposable disposableExport = export as IDisposable; - if (disposableExport != null) + if (export is IDisposable disposableExport) { if (disposableExports == null) { @@ -165,7 +164,7 @@ namespace System.ComponentModel.Composition.Hosting } // Dispose any existing references previously set on this import - List oldDisposableExports = null; + List? oldDisposableExports = null; if (_importedDisposableExports != null && _importedDisposableExports.TryGetValue(import, out oldDisposableExports)) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs index 78da869bc80..ba2095ad3f8 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs @@ -70,8 +70,7 @@ namespace System.ComponentModel.Composition.Hosting public IEnumerable GetPartsImporting(string contractName) { - WeakReferenceCollection partManagerList; - if (!_partManagerIndex.TryGetValue(contractName, out partManagerList)) + if (!_partManagerIndex.TryGetValue(contractName, out WeakReferenceCollection? partManagerList)) { return Enumerable.Empty(); } @@ -83,8 +82,7 @@ namespace System.ComponentModel.Composition.Hosting { foreach (string contractName in partManager.GetImportedContractNames()) { - WeakReferenceCollection indexEntries; - if (!_partManagerIndex.TryGetValue(contractName, out indexEntries)) + if (!_partManagerIndex.TryGetValue(contractName, out WeakReferenceCollection? indexEntries)) { indexEntries = new WeakReferenceCollection(); _partManagerIndex.Add(contractName, indexEntries); @@ -101,8 +99,7 @@ namespace System.ComponentModel.Composition.Hosting { foreach (string contractName in partManager.GetImportedContractNames()) { - WeakReferenceCollection indexEntries; - if (_partManagerIndex.TryGetValue(contractName, out indexEntries)) + if (_partManagerIndex.TryGetValue(contractName, out WeakReferenceCollection? indexEntries)) { indexEntries.Remove(partManager); var aliveItems = indexEntries.AliveItemsToList(); @@ -120,7 +117,7 @@ namespace System.ComponentModel.Composition.Hosting var partsToIndex = _partsToIndex.AliveItemsToList(); _partsToIndex.Clear(); - var partsToUnindex = _partsToUnindex.AliveItemsToList(); + List partsToUnindex = _partsToUnindex.AliveItemsToList()!; _partsToUnindex.Clear(); if (partsToIndex.Count == 0 && partsToUnindex.Count == 0) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs index 6d1863a228a..5937de72229 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs @@ -21,11 +21,11 @@ namespace System.ComponentModel.Composition.Hosting private const int MaximumNumberOfCompositionIterations = 100; private volatile bool _isDisposed; - private ExportProvider _sourceProvider; + private ExportProvider? _sourceProvider; private readonly Stack _recursionStateStack = new Stack(); private ConditionalWeakTable _partManagers = new ConditionalWeakTable(); private RecompositionManager _recompositionManager = new RecompositionManager(); - private readonly CompositionLock _lock = null; + private readonly CompositionLock _lock; private readonly CompositionOptions _compositionOptions; /// @@ -81,7 +81,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// The has been disposed of. /// - public void PreviewImports(ComposablePart part, AtomicComposition atomicComposition) + public void PreviewImports(ComposablePart part, AtomicComposition? atomicComposition) { ThrowIfDisposed(); @@ -102,17 +102,17 @@ namespace System.ComponentModel.Composition.Hosting // We add the "release" lock to BOTH Commit and Revert queues, because they are mutually exclusive, and we need to release the lock regardless. // This will take the lock, if necesary - IDisposable compositionLockHolder = _lock.IsThreadSafe ? _lock.LockComposition() : null; + IDisposable? compositionLockHolder = _lock.IsThreadSafe ? _lock.LockComposition() : null; bool compositionLockTaken = (compositionLockHolder != null); try { // revert actions are processed in the reverse order, so we have to add the "release lock" action now if (compositionLockTaken && (atomicComposition != null)) { - atomicComposition.AddRevertAction(() => compositionLockHolder.Dispose()); + atomicComposition.AddRevertAction(() => compositionLockHolder!.Dispose()); } - var partManager = GetPartManager(part, true); + var partManager = GetPartManager(part, true)!; var result = TryPreviewImportsStateMachine(partManager, part, atomicComposition); result.ThrowOnErrors(atomicComposition); @@ -121,7 +121,7 @@ namespace System.ComponentModel.Composition.Hosting // Add the "release lock" to the commit actions if (compositionLockTaken && (atomicComposition != null)) { - atomicComposition.AddCompleteAction(() => compositionLockHolder.Dispose()); + atomicComposition.AddCompleteAction(() => compositionLockHolder!.Dispose()); } } finally @@ -129,7 +129,7 @@ namespace System.ComponentModel.Composition.Hosting // We haven't updated the queues, so we can release the lock now if (compositionLockTaken && (atomicComposition == null)) { - compositionLockHolder.Dispose(); + compositionLockHolder!.Dispose(); } } } @@ -161,7 +161,7 @@ namespace System.ComponentModel.Composition.Hosting Requires.NotNull(part, nameof(part)); // NOTE : the following two calls use the state lock - PartManager partManager = GetPartManager(part, true); + PartManager partManager = GetPartManager(part, true)!; if (partManager.State == ImportState.Composed) { return; @@ -198,7 +198,7 @@ namespace System.ComponentModel.Composition.Hosting Requires.NotNull(part, nameof(part)); // NOTE : the following two calls use the state lock - PartManager partManager = GetPartManager(part, true); + PartManager partManager = GetPartManager(part, true)!; if (partManager.State == ImportState.Composed) { return; @@ -225,7 +225,7 @@ namespace System.ComponentModel.Composition.Hosting /// /// The that the release imports is running under. /// - public void ReleaseImports(ComposablePart part, AtomicComposition atomicComposition) + public void ReleaseImports(ComposablePart part, AtomicComposition? atomicComposition) { ThrowIfDisposed(); @@ -233,7 +233,7 @@ namespace System.ComponentModel.Composition.Hosting using (_lock.LockComposition()) { - PartManager partManager = GetPartManager(part, false); + PartManager? partManager = GetPartManager(part, false); if (partManager != null) { StopSatisfyingImports(partManager, atomicComposition); @@ -261,15 +261,15 @@ namespace System.ComponentModel.Composition.Hosting if (!_isDisposed) { bool disposeLock = false; - ExportProvider sourceProviderToUnsubscribeFrom = null; + ExportProvider? sourceProviderToUnsubscribeFrom = null; using (_lock.LockStateForWrite()) { if (!_isDisposed) { sourceProviderToUnsubscribeFrom = _sourceProvider; _sourceProvider = null; - _recompositionManager = null; - _partManagers = null; + _recompositionManager = null!; + _partManagers = null!; _isDisposed = true; disposeLock = true; } @@ -289,7 +289,7 @@ namespace System.ComponentModel.Composition.Hosting } private CompositionResult TryPreviewImportsStateMachine(PartManager partManager, - ComposablePart part, AtomicComposition atomicComposition) + ComposablePart part, AtomicComposition? atomicComposition) { var result = CompositionResult.SucceededResult; @@ -451,7 +451,7 @@ namespace System.ComponentModel.Composition.Hosting } private CompositionResult TrySatisfyImportSubset(PartManager partManager, - IEnumerable imports, AtomicComposition atomicComposition) + IEnumerable imports, AtomicComposition? atomicComposition) { CompositionResult result = CompositionResult.SucceededResult; @@ -486,12 +486,12 @@ namespace System.ComponentModel.Composition.Hosting return result; } - private void OnExportsChanging(object sender, ExportsChangeEventArgs e) + private void OnExportsChanging(object? sender, ExportsChangeEventArgs e) { CompositionResult result = CompositionResult.SucceededResult; // Prepare for the recomposition effort by minimizing the amount of work we'll have to do later - AtomicComposition atomicComposition = e.AtomicComposition; + AtomicComposition? atomicComposition = e.AtomicComposition; IEnumerable affectedParts = _recompositionManager.GetAffectedParts(e.ChangedContractNames); @@ -499,13 +499,12 @@ namespace System.ComponentModel.Composition.Hosting // index if (atomicComposition != null) { - EngineContext engineContext; - if (atomicComposition.TryGetValue(this, out engineContext)) + if (atomicComposition.TryGetValue(this, out EngineContext? engineContext)) { // always added the new part managers to see if they will also be // affected by these changes - affectedParts = affectedParts.ConcatAllowingNull(engineContext.GetAddedPartManagers()) - .Except(engineContext.GetRemovedPartManagers()); + affectedParts = affectedParts.ConcatAllowingNull(engineContext!.GetAddedPartManagers())! + .Except(engineContext.GetRemovedPartManagers()!); } } @@ -513,14 +512,14 @@ namespace System.ComponentModel.Composition.Hosting foreach (var partManager in affectedParts) { - result = result.MergeResult(TryRecomposeImports(partManager, changedExports, atomicComposition)); + result = result.MergeResult(TryRecomposeImports(partManager, changedExports!, atomicComposition)); } result.ThrowOnErrors(atomicComposition); } private CompositionResult TryRecomposeImports(PartManager partManager, - IEnumerable changedExports, AtomicComposition atomicComposition) + IEnumerable changedExports, AtomicComposition? atomicComposition) { var result = CompositionResult.SucceededResult; @@ -569,7 +568,7 @@ namespace System.ComponentModel.Composition.Hosting } private CompositionResult TryRecomposeImport(PartManager partManager, bool partComposed, - ImportDefinition import, AtomicComposition atomicComposition) + ImportDefinition import, AtomicComposition? atomicComposition) { if (partComposed && !import.IsRecomposable) { @@ -607,7 +606,7 @@ namespace System.ComponentModel.Composition.Hosting return CompositionResult.SucceededResult; } - private void StartSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition) + private void StartSatisfyingImports(PartManager partManager, AtomicComposition? atomicComposition) { // When not running in a atomicCompositional state, schedule reindexing after ensuring // that this isn't a redundant addition @@ -627,14 +626,14 @@ namespace System.ComponentModel.Composition.Hosting } } - private void StopSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition) + private void StopSatisfyingImports(PartManager partManager, AtomicComposition? atomicComposition) { // When not running in a atomicCompositional state, schedule reindexing after ensuring // that this isn't a redundant removal if (atomicComposition == null) { - ConditionalWeakTable partManagers = null; - RecompositionManager recompositionManager = null; + ConditionalWeakTable? partManagers = null; + RecompositionManager? recompositionManager = null; using (_lock.LockStateForRead()) { @@ -663,9 +662,9 @@ namespace System.ComponentModel.Composition.Hosting } } - private PartManager GetPartManager(ComposablePart part, bool createIfNotpresent) + private PartManager? GetPartManager(ComposablePart part, bool createIfNotpresent) { - PartManager partManager = null; + PartManager? partManager = null; using (_lock.LockStateForRead()) { if (_partManagers.TryGetValue(part, out partManager)) @@ -695,22 +694,20 @@ namespace System.ComponentModel.Composition.Hosting throw new ArgumentNullException(nameof(atomicComposition)); } - EngineContext engineContext; - if (!atomicComposition.TryGetValue(this, true, out engineContext)) + if (!atomicComposition.TryGetValue(this, true, out EngineContext? engineContext)) { - EngineContext parentContext; - atomicComposition.TryGetValue(this, false, out parentContext); + atomicComposition.TryGetValue(this, false, out EngineContext? parentContext); engineContext = new EngineContext(this, parentContext); atomicComposition.SetValue(this, engineContext); atomicComposition.AddCompleteAction(engineContext.Complete); } - return engineContext; + return engineContext!; } private bool InPrerequisiteLoop() { PartManager firstPart = _recursionStateStack.First(); - PartManager lastPart = null; + PartManager? lastPart = null; foreach (PartManager testPart in _recursionStateStack.Skip(1)) { @@ -743,17 +740,17 @@ namespace System.ComponentModel.Composition.Hosting } } - private static CompositionResult> TryGetExports(ExportProvider provider, - ComposablePart part, ImportDefinition definition, AtomicComposition atomicComposition) + private static CompositionResult> TryGetExports(ExportProvider? provider, + ComposablePart part, ImportDefinition definition, AtomicComposition? atomicComposition) { try { - IEnumerable exports = null; + IEnumerable? exports = null; if (provider != null) { exports = provider.GetExports(definition, atomicComposition).AsArray(); } - return new CompositionResult>(exports); + return new CompositionResult>(exports!); } catch (ImportCardinalityMismatchException ex) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs index ed0c221051f..12e8f9789dc 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs @@ -29,7 +29,7 @@ namespace System.ComponentModel.Composition.Hosting internal class NonImportSourceImportDefinition : ContractBasedImportDefinition { private readonly ContractBasedImportDefinition _sourceDefinition; - private IDictionary _metadata; + private IDictionary? _metadata; public NonImportSourceImportDefinition(ContractBasedImportDefinition sourceDefinition) { @@ -46,14 +46,14 @@ namespace System.ComponentModel.Composition.Hosting get { return _sourceDefinition.ContractName; } } - public override IDictionary Metadata + public override IDictionary Metadata { get { var reply = _metadata; if (reply == null) { - reply = new Dictionary(_sourceDefinition.Metadata); + reply = new Dictionary(_sourceDefinition.Metadata); reply.Remove(CompositionConstants.ImportSourceMetadataName); _metadata = reply; } @@ -95,7 +95,7 @@ namespace System.ComponentModel.Composition.Hosting return _sourceDefinition.ToString(); } - public override string RequiredTypeIdentity + public override string? RequiredTypeIdentity { get { return _sourceDefinition.RequiredTypeIdentity; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ScopingExtensions.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ScopingExtensions.cs index 57f8d8c3dca..41623db4f37 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ScopingExtensions.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ScopingExtensions.cs @@ -112,8 +112,7 @@ namespace System.ComponentModel.Composition.Hosting Requires.NotNull(part, nameof(part)); Requires.NotNull(key, nameof(key)); - object untypedValue = null; - if (part.Metadata.TryGetValue(key, out untypedValue)) + if (part.Metadata.TryGetValue(key, out object? untypedValue)) { if (value == null) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs index 0e60ac6b105..a2723843544 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs @@ -26,8 +26,8 @@ namespace System.ComponentModel.Composition.Hosting public class TypeCatalog : ComposablePartCatalog, ICompositionElement { private readonly object _thisLock = new object(); - private Type[] _types = null; - private volatile List _parts; + private Type[]? _types = null; + private volatile List? _parts; private volatile bool _isDisposed = false; private readonly ICompositionElement _definitionOrigin; private readonly Lazy>> _contractPartIndex; @@ -243,7 +243,7 @@ namespace System.ComponentModel.Composition.Hosting /// This property always returns . /// [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] - ICompositionElement ICompositionElement.Origin + ICompositionElement? ICompositionElement.Origin { get { return null; } } @@ -284,7 +284,7 @@ namespace System.ComponentModel.Composition.Hosting } } - internal override IEnumerable GetCandidateParts(ImportDefinition definition) + internal override IEnumerable? GetCandidateParts(ImportDefinition definition) { if (definition == null) { @@ -297,23 +297,22 @@ namespace System.ComponentModel.Composition.Hosting return PartsInternal; } - string genericContractName = definition.Metadata.GetValue(CompositionConstants.GenericContractMetadataName); + string? genericContractName = definition.Metadata.GetValue(CompositionConstants.GenericContractMetadataName); - List nonGenericMatches = GetCandidateParts(contractName); - List genericMatches = GetCandidateParts(genericContractName); + List? nonGenericMatches = GetCandidateParts(contractName); + List? genericMatches = GetCandidateParts(genericContractName); return nonGenericMatches.ConcatAllowingNull(genericMatches); } - private List GetCandidateParts(string contractName) + private List? GetCandidateParts(string? contractName) { if (contractName == null) { return null; } - List contractCandidateParts = null; - _contractPartIndex.Value.TryGetValue(contractName, out contractCandidateParts); + _contractPartIndex.Value.TryGetValue(contractName, out List? contractCandidateParts); return contractCandidateParts; } @@ -325,7 +324,7 @@ namespace System.ComponentModel.Composition.Hosting { foreach (string contractName in part.ExportDefinitions.Select(export => export.ContractName).Distinct()) { - List contractParts = null; + List? contractParts = null; if (!index.TryGetValue(contractName, out contractParts)) { contractParts = new List(); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/IAttributedImport.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/IAttributedImport.cs index b44c13f542e..65e38a753c4 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/IAttributedImport.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/IAttributedImport.cs @@ -8,8 +8,8 @@ namespace System.ComponentModel.Composition { internal interface IAttributedImport { - string ContractName { get; } - Type ContractType { get; } + string? ContractName { get; } + Type? ContractType { get; } bool AllowRecomposition { get; } CreationPolicy RequiredCreationPolicy { get; } ImportCardinality Cardinality { get; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportAttribute.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportAttribute.cs index e30a96489d5..73d0d6573c8 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportAttribute.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportAttribute.cs @@ -31,7 +31,7 @@ namespace System.ComponentModel.Composition /// /// public ImportAttribute() - : this((string)null) + : this((string?)null) { } @@ -59,8 +59,8 @@ namespace System.ComponentModel.Composition /// using . /// /// - public ImportAttribute(Type contractType) - : this((string)null, contractType) + public ImportAttribute(Type? contractType) + : this((string?)null, contractType) { } @@ -83,12 +83,12 @@ namespace System.ComponentModel.Composition /// using . /// /// - public ImportAttribute(string contractName) - : this(contractName, (Type)null) + public ImportAttribute(string? contractName) + : this(contractName, (Type?)null) { } - public ImportAttribute(string contractName, Type contractType) + public ImportAttribute(string? contractName, Type? contractType) { ContractName = contractName; ContractType = contractType; @@ -101,7 +101,7 @@ namespace System.ComponentModel.Composition /// A containing the contract name of the export to import. The /// default value is an empty string (""). /// - public string ContractName { get; private set; } + public string? ContractName { get; private set; } /// /// Get the contract type of the export to import. @@ -112,7 +112,7 @@ namespace System.ComponentModel.Composition /// the member that this import is attached to. If the type is then the /// importer is delaring they can accept any exported type. /// - public Type ContractType { get; private set; } + public Type? ContractType { get; private set; } /// /// Gets or sets a value indicating whether the property, field or parameter will be set diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportCardinalityMismatchException.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportCardinalityMismatchException.cs index 0fe2041f604..0e49855c5ba 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportCardinalityMismatchException.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportCardinalityMismatchException.cs @@ -21,7 +21,7 @@ namespace System.ComponentModel.Composition /// Initializes a new instance of the class. /// public ImportCardinalityMismatchException() - : this((string)null, (Exception)null) + : this((string?)null, (Exception?)null) { } @@ -34,8 +34,8 @@ namespace System.ComponentModel.Composition /// ; or to set /// the property to its default value. /// - public ImportCardinalityMismatchException(string message) - : this(message, (Exception)null) + public ImportCardinalityMismatchException(string? message) + : this(message, (Exception?)null) { } @@ -54,7 +54,7 @@ namespace System.ComponentModel.Composition /// ; or to set /// the property to . /// - public ImportCardinalityMismatchException(string message, Exception innerException) + public ImportCardinalityMismatchException(string? message, Exception? innerException) : base(message, innerException) { } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportCardinalityMismatchExceptionDebuggerProxy.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportCardinalityMismatchExceptionDebuggerProxy.cs index 49c1506cd81..4878cc1c8a4 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportCardinalityMismatchExceptionDebuggerProxy.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportCardinalityMismatchExceptionDebuggerProxy.cs @@ -17,7 +17,7 @@ namespace System.ComponentModel.Composition _exception = exception; } - public Exception InnerException + public Exception? InnerException { get { return _exception.InnerException; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportManyAttribute.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportManyAttribute.cs index 383e18dfcf5..16530479dd6 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportManyAttribute.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportManyAttribute.cs @@ -31,7 +31,7 @@ namespace System.ComponentModel.Composition /// /// public ImportManyAttribute() - : this((string)null) + : this((string?)null) { } @@ -59,8 +59,8 @@ namespace System.ComponentModel.Composition /// using . /// /// - public ImportManyAttribute(Type contractType) - : this((string)null, contractType) + public ImportManyAttribute(Type? contractType) + : this((string?)null, contractType) { } @@ -83,12 +83,12 @@ namespace System.ComponentModel.Composition /// using . /// /// - public ImportManyAttribute(string contractName) - : this(contractName, (Type)null) + public ImportManyAttribute(string? contractName) + : this(contractName, (Type?)null) { } - public ImportManyAttribute(string contractName, Type contractType) + public ImportManyAttribute(string? contractName, Type? contractType) { ContractName = contractName; ContractType = contractType; @@ -101,7 +101,7 @@ namespace System.ComponentModel.Composition /// A containing the contract name of the exports to import. The /// default value is an empty string (""). /// - public string ContractName { get; private set; } + public string? ContractName { get; private set; } /// /// Get the contract type of the export to import. @@ -112,7 +112,7 @@ namespace System.ComponentModel.Composition /// the member that this import is attached to. If the type is then the /// importer is delaring they can accept any exported type. /// - public Type ContractType { get; private set; } + public Type? ContractType { get; private set; } /// /// Gets or sets a value indicating whether the property or field will be recomposed diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/InheritedExportAttribute.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/InheritedExportAttribute.cs index 826afb6f866..f28cb990970 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/InheritedExportAttribute.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/InheritedExportAttribute.cs @@ -29,7 +29,7 @@ namespace System.ComponentModel.Composition /// /// public InheritedExportAttribute() - : this((string)null, (Type)null) + : this((string?)null, (Type?)null) { } @@ -58,8 +58,8 @@ namespace System.ComponentModel.Composition /// using . /// /// - public InheritedExportAttribute(Type contractType) - : this((string)null, contractType) + public InheritedExportAttribute(Type? contractType) + : this((string?)null, contractType) { } @@ -83,8 +83,8 @@ namespace System.ComponentModel.Composition /// using . /// /// - public InheritedExportAttribute(string contractName) - : this(contractName, (Type)null) + public InheritedExportAttribute(string? contractName) + : this(contractName, (Type?)null) { } @@ -113,7 +113,7 @@ namespace System.ComponentModel.Composition /// using . /// /// - public InheritedExportAttribute(string contractName, Type contractType) + public InheritedExportAttribute(string? contractName, Type? contractType) : base(contractName, contractType) { } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs index 61958bf3fda..5906e2cae30 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs @@ -4,39 +4,40 @@ using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel.Composition { internal static class MetadataServices { - public static readonly IDictionary EmptyMetadata = new ReadOnlyDictionary(new Dictionary(0)); + public static readonly IDictionary EmptyMetadata = new ReadOnlyDictionary(new Dictionary(0)); - public static IDictionary AsReadOnly(this IDictionary metadata) + public static IDictionary AsReadOnly(this IDictionary? metadata) { if (metadata == null) { return EmptyMetadata; } - if (metadata is ReadOnlyDictionary) + if (metadata is ReadOnlyDictionary) { return metadata; } - return new ReadOnlyDictionary(metadata); + return new ReadOnlyDictionary(metadata); } - public static T GetValue(this IDictionary metadata, string key) + [return: MaybeNull] + public static T GetValue(this IDictionary metadata, string key) { if (metadata == null) { throw new ArgumentNullException(nameof(metadata)); } - object untypedValue = null; - if (!metadata.TryGetValue(key, out untypedValue)) + if (!metadata.TryGetValue(key, out object? untypedValue)) { - return default(T); + return default(T)!; } if (untypedValue is T) @@ -45,7 +46,7 @@ namespace System.ComponentModel.Composition } else { - return default(T); + return default(T)!; } } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs index 84853dd3351..d66409b8c9a 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs @@ -57,7 +57,7 @@ namespace System.ComponentModel.Composition // } internal static class MetadataViewGenerator { - public delegate object MetadataViewFactory(IDictionary metadata); + public delegate object MetadataViewFactory(IDictionary metadata); public const string MetadataViewType = "MetadataViewType"; public const string MetadataItemKey = "MetadataItemKey"; @@ -69,12 +69,12 @@ namespace System.ComponentModel.Composition private static readonly Lock _lock = new Lock(); private static readonly Dictionary _metadataViewFactories = new Dictionary(); private static readonly AssemblyName ProxyAssemblyName = new AssemblyName(string.Format(CultureInfo.InvariantCulture, "MetadataViewProxies_{0}", Guid.NewGuid())); - private static ModuleBuilder transparentProxyModuleBuilder; + private static ModuleBuilder? transparentProxyModuleBuilder; private static readonly Type[] CtorArgumentTypes = new Type[] { typeof(IDictionary) }; - private static readonly MethodInfo _mdvDictionaryTryGet = CtorArgumentTypes[0].GetMethod("TryGetValue"); - private static readonly MethodInfo ObjectGetType = typeof(object).GetMethod("GetType", Type.EmptyTypes); - private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes); + private static readonly MethodInfo _mdvDictionaryTryGet = CtorArgumentTypes[0].GetMethod("TryGetValue")!; + private static readonly MethodInfo ObjectGetType = typeof(object).GetMethod("GetType", Type.EmptyTypes)!; + private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes)!; // Must be called with _lock held private static ModuleBuilder GetProxyModuleBuilder(bool requiresCritical) @@ -101,7 +101,7 @@ namespace System.ComponentModel.Composition throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - MetadataViewFactory metadataViewFactory; + MetadataViewFactory? metadataViewFactory; bool foundMetadataViewFactory; using (new ReadLock(_lock)) @@ -113,14 +113,14 @@ namespace System.ComponentModel.Composition if (!foundMetadataViewFactory) { // Try again under a write lock if still none generate the proxy - Type generatedProxyType = GenerateInterfaceViewProxyType(viewType); + Type? generatedProxyType = GenerateInterfaceViewProxyType(viewType); if (generatedProxyType == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } MetadataViewFactory generatedMetadataViewFactory = (MetadataViewFactory)Delegate.CreateDelegate( - typeof(MetadataViewFactory), generatedProxyType.GetMethod(MetadataViewGenerator.MetadataViewFactoryName, BindingFlags.Public | BindingFlags.Static)); + typeof(MetadataViewFactory), generatedProxyType.GetMethod(MetadataViewGenerator.MetadataViewFactoryName, BindingFlags.Public | BindingFlags.Static)!); if (generatedMetadataViewFactory == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); @@ -135,10 +135,10 @@ namespace System.ComponentModel.Composition } } } - return metadataViewFactory; + return metadataViewFactory!; } - public static TMetadataView CreateMetadataView(MetadataViewFactory metadataViewFactory, IDictionary metadata) + public static TMetadataView CreateMetadataView(MetadataViewFactory metadataViewFactory, IDictionary metadata) { if (metadataViewFactory == null) { @@ -184,10 +184,10 @@ namespace System.ComponentModel.Composition } // This must be called with _readerWriterLock held for Write - private static Type GenerateInterfaceViewProxyType(Type viewType) + private static Type? GenerateInterfaceViewProxyType(Type viewType) { // View type is an interface let's cook an implementation - Type proxyType; + Type? proxyType; TypeBuilder proxyTypeBuilder; Type[] interfaces = { viewType }; bool requiresCritical = false; @@ -221,8 +221,8 @@ namespace System.ComponentModel.Composition string propertyName = propertyInfo.Name; Type[] propertyTypeArguments = new Type[] { propertyInfo.PropertyType }; - Type[] optionalModifiers = null; - Type[] requiredModifiers = null; + Type[]? optionalModifiers = null; + Type[]? requiredModifiers = null; // PropertyInfo does not support GetOptionalCustomModifiers and GetRequiredCustomModifiers on Silverlight optionalModifiers = propertyInfo.GetOptionalCustomModifiers(); @@ -329,7 +329,7 @@ namespace System.ComponentModel.Composition optionalModifiers, Type.EmptyTypes, null, null); - proxyTypeBuilder.DefineMethodOverride(getMethodBuilder, propertyInfo.GetGetMethod()); + proxyTypeBuilder.DefineMethodOverride(getMethodBuilder, propertyInfo.GetGetMethod()!); ILGenerator getMethodIL = getMethodBuilder.GetILGenerator(); getMethodIL.Emit(OpCodes.Ldarg_0); getMethodIL.Emit(OpCodes.Ldfld, proxyFieldBuilder); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewImplementationAttribute.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewImplementationAttribute.cs index 4eeca115271..ae03992271c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewImplementationAttribute.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewImplementationAttribute.cs @@ -24,7 +24,7 @@ namespace System.ComponentModel.Composition /// using a generated type. /// /// - public MetadataViewImplementationAttribute(Type implementationType) + public MetadataViewImplementationAttribute(Type? implementationType) { ImplementationType = implementationType; } @@ -37,6 +37,6 @@ namespace System.ComponentModel.Composition /// which means that the type will be obtained by looking at the type on /// the member that this export is attached to. /// - public Type ImplementationType { get; private set; } + public Type? ImplementationType { get; private set; } } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs index 31c82c4ddf5..ac61aa5dc1b 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs @@ -7,13 +7,14 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using Microsoft.Internal; +using System.Diagnostics; namespace System.ComponentModel.Composition { internal static class MetadataViewProvider { [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - public static TMetadataView GetMetadataView(IDictionary metadata) + public static TMetadataView GetMetadataView(IDictionary metadata) { if (metadata == null) { @@ -23,15 +24,15 @@ namespace System.ComponentModel.Composition Type metadataViewType = typeof(TMetadataView); // If the Metadata dictionary is cast compatible with the passed in type - if (metadataViewType.IsAssignableFrom(typeof(IDictionary))) + if (metadataViewType.IsAssignableFrom(typeof(IDictionary))) { return (TMetadataView)metadata; } // otherwise is it a metadata view else { - Type proxyType = null; - MetadataViewGenerator.MetadataViewFactory metadataViewFactory = null; + Type? proxyType = null; + MetadataViewGenerator.MetadataViewFactory? metadataViewFactory = null; if (metadataViewType.IsInterface) { if (!metadataViewType.IsAttributeDefined()) @@ -48,13 +49,13 @@ namespace System.ComponentModel.Composition else { var implementationAttribute = metadataViewType.GetFirstAttribute(); + Debug.Assert(implementationAttribute != null); proxyType = implementationAttribute.ImplementationType; if (proxyType == null) { throw new CompositionContractMismatchException(SR.Format( SR.ContractMismatch_MetadataViewImplementationCanNotBeNull, - metadataViewType.FullName, - proxyType.FullName)); + metadataViewType.FullName)); } else { @@ -86,7 +87,7 @@ namespace System.ComponentModel.Composition { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - return (TMetadataView)proxyType.SafeCreateInstance(metadata); + return (TMetadataView)proxyType.SafeCreateInstance(metadata)!; } } catch (MissingMethodException ex) @@ -94,14 +95,14 @@ namespace System.ComponentModel.Composition // Unable to create an Instance of the Metadata view '{0}' because a constructor could not be selected. Ensure that the type implements a constructor which takes an argument of type IDictionary. throw new CompositionContractMismatchException(SR.Format( SR.CompositionException_MetadataViewInvalidConstructor, - proxyType.AssemblyQualifiedName), ex); + proxyType!.AssemblyQualifiedName), ex); } catch (TargetInvocationException ex) { //Unwrap known failures that we want to present as CompositionContractMismatchException if (metadataViewType.IsInterface) { - if (ex.InnerException.GetType() == typeof(InvalidCastException)) + if (ex.InnerException!.GetType() == typeof(InvalidCastException)) { // Unable to create an Instance of the Metadata view {0} because the exporter exported the metadata for the item {1} with the value {2} as type {3} but the view imports it as type {4}. throw new CompositionContractMismatchException(SR.Format( diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/PartMetadataAttribute.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/PartMetadataAttribute.cs index f8d8167b408..5758dda9c5d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/PartMetadataAttribute.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/PartMetadataAttribute.cs @@ -23,7 +23,7 @@ namespace System.ComponentModel.Composition /// An containing the metadata value. This can be /// . /// - public PartMetadataAttribute(string name, object value) + public PartMetadataAttribute(string? name, object? value) { Name = name ?? string.Empty; Value = value; @@ -47,7 +47,7 @@ namespace System.ComponentModel.Composition /// /// An containing the metadata value. /// - public object Value + public object? Value { get; private set; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePart.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePart.cs index 516a5ac2443..a9f9ee86b40 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePart.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePart.cs @@ -105,7 +105,7 @@ namespace System.ComponentModel.Composition.Primitives /// /// /// - public virtual IDictionary Metadata + public virtual IDictionary Metadata { get { @@ -155,7 +155,7 @@ namespace System.ComponentModel.Composition.Primitives /// /// An error occurred getting the exported value described by the . /// - public abstract object GetExportedValue(ExportDefinition definition); + public abstract object? GetExportedValue(ExportDefinition definition); /// /// Sets the import described by the specified definition with the specified exports. diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartCatalog.cs index b08dc2930bd..2e3a3c7c129 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartCatalog.cs @@ -23,7 +23,7 @@ namespace System.ComponentModel.Composition.Primitives public abstract class ComposablePartCatalog : IEnumerable, IDisposable { private bool _isDisposed; - private volatile IQueryable _queryableParts = null; + private volatile IQueryable? _queryableParts = null; internal static readonly List> _EmptyExportsList = new List>(); @@ -102,16 +102,13 @@ namespace System.ComponentModel.Composition.Primitives Requires.NotNull(definition, nameof(definition)); - List> exports = null; + List>? exports = null; var candidateParts = GetCandidateParts(definition); if (candidateParts != null) { foreach (var part in candidateParts) { - Tuple singleMatch; - IEnumerable> multipleMatches; - - if (part.TryGetExports(definition, out singleMatch, out multipleMatches)) + if (part.TryGetExports(definition, out Tuple? singleMatch, out IEnumerable>? multipleMatches)) { exports = exports.FastAppendToListAllowNulls(singleMatch, multipleMatches); } @@ -122,7 +119,7 @@ namespace System.ComponentModel.Composition.Primitives return exports ?? _EmptyExportsList; } - internal virtual IEnumerable GetCandidateParts(ImportDefinition definition) + internal virtual IEnumerable? GetCandidateParts(ImportDefinition definition) { return this; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs index 565858b8a35..039e4642888 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; +using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel.Composition.Primitives { @@ -80,7 +81,7 @@ namespace System.ComponentModel.Composition.Primitives /// /// /// - public virtual IDictionary Metadata + public virtual IDictionary Metadata { get { return MetadataServices.EmptyMetadata; } } @@ -102,13 +103,13 @@ namespace System.ComponentModel.Composition.Primitives /// public abstract ComposablePart CreatePart(); - internal virtual bool TryGetExports(ImportDefinition definition, out Tuple singleMatch, out IEnumerable> multipleMatches) + internal virtual bool TryGetExports(ImportDefinition definition, [NotNullWhen(true)] out Tuple? singleMatch, out IEnumerable>? multipleMatches) { singleMatch = null; multipleMatches = null; - List> multipleExports = null; - Tuple singleExport = null; + List>? multipleExports = null; + Tuple? singleExport = null; bool matchesFound = false; foreach (var export in ExportDefinitions) { @@ -147,7 +148,7 @@ namespace System.ComponentModel.Composition.Primitives return true; } - internal virtual ComposablePartDefinition GetGenericPartDefinition() + internal virtual ComposablePartDefinition? GetGenericPartDefinition() { return null; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartException.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartException.cs index 5d542a8f2bc..e47ad1dac5d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartException.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartException.cs @@ -16,13 +16,13 @@ namespace System.ComponentModel.Composition.Primitives [Serializable] public class ComposablePartException : Exception { - private readonly ICompositionElement _element; + private readonly ICompositionElement? _element; /// /// Initializes a new instance of the class. /// public ComposablePartException() - : this((string)null, (ICompositionElement)null, (Exception)null) + : this((string?)null, (ICompositionElement?)null, (Exception?)null) { } @@ -49,7 +49,7 @@ namespace System.ComponentModel.Composition.Primitives /// protected ComposablePartException(SerializationInfo info, StreamingContext context) : base(info, context) { - _element = (ICompositionElement)info.GetValue("Element", typeof(ICompositionElement)); + _element = (ICompositionElement?)info.GetValue("Element", typeof(ICompositionElement)); } /// @@ -61,8 +61,8 @@ namespace System.ComponentModel.Composition.Primitives /// ; or to set /// the property to its default value. /// - public ComposablePartException(string message) - : this(message, (ICompositionElement)null, (Exception)null) + public ComposablePartException(string? message) + : this(message, (ICompositionElement?)null, (Exception?)null) { } @@ -82,8 +82,8 @@ namespace System.ComponentModel.Composition.Primitives /// the property to /// . /// - public ComposablePartException(string message, ICompositionElement element) - : this(message, element, (Exception)null) + public ComposablePartException(string? message, ICompositionElement? element) + : this(message, element, (Exception?)null) { } @@ -102,8 +102,8 @@ namespace System.ComponentModel.Composition.Primitives /// ; or to set /// the property to . /// - public ComposablePartException(string message, Exception innerException) - : this(message, (ICompositionElement)null, innerException) + public ComposablePartException(string? message, Exception? innerException) + : this(message, (ICompositionElement?)null, innerException) { } @@ -128,7 +128,7 @@ namespace System.ComponentModel.Composition.Primitives /// ; or to set /// the property to . /// - public ComposablePartException(string message, ICompositionElement element, Exception innerException) + public ComposablePartException(string? message, ICompositionElement? element, Exception? innerException) : base(message, innerException) { _element = element; @@ -141,7 +141,7 @@ namespace System.ComponentModel.Composition.Primitives /// The that is the cause of the /// . The default is . /// - public ICompositionElement Element + public ICompositionElement? Element { get { return _element; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartExceptionDebuggerProxy.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartExceptionDebuggerProxy.cs index 9cd179ee8c1..05ecb85e798 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartExceptionDebuggerProxy.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartExceptionDebuggerProxy.cs @@ -17,12 +17,12 @@ namespace System.ComponentModel.Composition.Primitives _exception = exception; } - public ICompositionElement Element + public ICompositionElement? Element { get { return _exception.Element; } } - public Exception InnerException + public Exception? InnerException { get { return _exception.InnerException; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElement.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElement.cs index c4bedd871c8..9f61c68d133 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElement.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElement.cs @@ -12,9 +12,9 @@ namespace System.ComponentModel.Composition.Primitives internal class CompositionElement : ICompositionElement { private readonly string _displayName; - private readonly ICompositionElement _origin; - private readonly object _underlyingObject; - private static readonly ICompositionElement UnknownOrigin = new CompositionElement(SR.CompositionElement_UnknownOrigin, (ICompositionElement)null); + private readonly ICompositionElement? _origin; + private readonly object? _underlyingObject; + private static readonly ICompositionElement UnknownOrigin = new CompositionElement(SR.CompositionElement_UnknownOrigin, (ICompositionElement?)null); public CompositionElement(object underlyingObject) : this(underlyingObject.ToString(), UnknownOrigin) @@ -22,7 +22,7 @@ namespace System.ComponentModel.Composition.Primitives _underlyingObject = underlyingObject; } - public CompositionElement(string displayName, ICompositionElement origin) + public CompositionElement(string? displayName, ICompositionElement? origin) { _displayName = displayName ?? string.Empty; _origin = origin; @@ -33,7 +33,7 @@ namespace System.ComponentModel.Composition.Primitives get { return _displayName; } } - public ICompositionElement Origin + public ICompositionElement? Origin { get { return _origin; } } @@ -43,7 +43,7 @@ namespace System.ComponentModel.Composition.Primitives return DisplayName; } - public object UnderlyingObject + public object? UnderlyingObject { get { return _underlyingObject; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElementDebuggerProxy.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElementDebuggerProxy.cs index 5ee12209425..cab7ca716f6 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElementDebuggerProxy.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElementDebuggerProxy.cs @@ -26,12 +26,12 @@ namespace System.ComponentModel.Composition.Primitives get { return _element.DisplayName; } } - public ICompositionElement Origin + public ICompositionElement? Origin { get { return _element.Origin; } } - public object UnderlyingObject + public object? UnderlyingObject { get { return _element.UnderlyingObject; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElementExtensions.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElementExtensions.cs index 4706b52563d..8cfdaf67fda 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElementExtensions.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElementExtensions.cs @@ -6,7 +6,7 @@ namespace System.ComponentModel.Composition.Primitives { internal static class CompositionElementExtensions { - public static ICompositionElement ToSerializableElement(this ICompositionElement element) + public static ICompositionElement? ToSerializableElement(this ICompositionElement? element) { return SerializableCompositionElement.FromICompositionElement(element); } @@ -14,8 +14,7 @@ namespace System.ComponentModel.Composition.Primitives public static ICompositionElement ToElement(this Export export) { // First try the export - ICompositionElement element = export as ICompositionElement; - if (element != null) + if (export is ICompositionElement element) { return element; } @@ -56,19 +55,17 @@ namespace System.ComponentModel.Composition.Primitives private static string GetDisplayNameCore(object value) { - ICompositionElement element = value as ICompositionElement; - if (element != null) + if (value is ICompositionElement element) { return element.DisplayName; } - return value.ToString(); + return value.ToString()!; } private static ICompositionElement ToElementCore(object value) { - ICompositionElement element = value as ICompositionElement; - if (element != null) + if (value is ICompositionElement element) { return element; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs index 7316c223b45..b8a57d69650 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs @@ -23,9 +23,9 @@ namespace System.ComponentModel.Composition.Primitives // Unlike contract name, both metadata and required metadata has a sensible default; set it to an empty // enumerable, so that derived definitions only need to override ContractName by default. private readonly IEnumerable> _requiredMetadata = Enumerable.Empty>(); - private Expression> _constraint; + private Expression>? _constraint; private readonly CreationPolicy _requiredCreationPolicy = CreationPolicy.Any; - private readonly string _requiredTypeIdentity = null; + private readonly string? _requiredTypeIdentity = null; private bool _isRequiredMetadataValidated = false; /// @@ -100,7 +100,7 @@ namespace System.ComponentModel.Composition.Primitives /// values. /// [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] - public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable> requiredMetadata, + public ContractBasedImportDefinition(string contractName, string? requiredTypeIdentity, IEnumerable>? requiredMetadata, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy) : this(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, MetadataServices.EmptyMetadata) { @@ -162,8 +162,8 @@ namespace System.ComponentModel.Composition.Primitives /// values. /// [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] - public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable> requiredMetadata, - ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy, IDictionary metadata) + public ContractBasedImportDefinition(string contractName, string? requiredTypeIdentity, IEnumerable>? requiredMetadata, + ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy, IDictionary metadata) : base(contractName, cardinality, isRecomposable, isPrerequisite, metadata) { Requires.NotNullOrEmpty(contractName, nameof(contractName)); @@ -186,7 +186,7 @@ namespace System.ComponentModel.Composition.Primitives /// on the type that this import expects. If the value is then this import /// doesn't expect a particular type. /// - public virtual string RequiredTypeIdentity + public virtual string? RequiredTypeIdentity { get { return _requiredTypeIdentity; } } @@ -321,7 +321,7 @@ namespace System.ComponentModel.Composition.Primitives { if (!string.IsNullOrEmpty(RequiredTypeIdentity)) { - string exportTypeIdentity = definition.Metadata.GetValue(CompositionConstants.ExportTypeIdentityMetadataName); + string? exportTypeIdentity = definition.Metadata.GetValue(CompositionConstants.ExportTypeIdentityMetadataName); if (!StringComparers.ContractName.Equals(RequiredTypeIdentity, exportTypeIdentity)) { @@ -334,8 +334,7 @@ namespace System.ComponentModel.Composition.Primitives string metadataKey = metadataItem.Key; Type metadataValueType = metadataItem.Value; - object metadataValue = null; - if (!definition.Metadata.TryGetValue(metadataKey, out metadataValue)) + if (!definition.Metadata.TryGetValue(metadataKey, out object? metadataValue)) { return false; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/Export.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/Export.cs index a79c23ccba3..d8a7e312782 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/Export.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/Export.cs @@ -16,10 +16,10 @@ namespace System.ComponentModel.Composition.Primitives /// public class Export { - private readonly ExportDefinition _definition; - private readonly Func _exportedValueGetter; + private readonly ExportDefinition? _definition; + private readonly Func? _exportedValueGetter; private static readonly object _EmptyValue = new object(); - private volatile object _exportedValue = Export._EmptyValue; + private volatile object? _exportedValue = Export._EmptyValue; /// /// Initializes a new instance of the class. @@ -56,8 +56,8 @@ namespace System.ComponentModel.Composition.Primitives /// /// is an empty string (""). /// - public Export(string contractName, Func exportedValueGetter) - : this(new ExportDefinition(contractName, (IDictionary)null), exportedValueGetter) + public Export(string contractName, Func exportedValueGetter) + : this(new ExportDefinition(contractName, (IDictionary?)null), exportedValueGetter) { } @@ -89,7 +89,7 @@ namespace System.ComponentModel.Composition.Primitives /// /// is an empty string (""). /// - public Export(string contractName, IDictionary metadata, Func exportedValueGetter) + public Export(string contractName, IDictionary? metadata, Func exportedValueGetter) : this(new ExportDefinition(contractName, metadata), exportedValueGetter) { } @@ -113,7 +113,7 @@ namespace System.ComponentModel.Composition.Primitives /// /// is . /// - public Export(ExportDefinition definition, Func exportedValueGetter) + public Export(ExportDefinition definition, Func exportedValueGetter) { Requires.NotNull(definition, nameof(definition)); Requires.NotNull(exportedValueGetter, nameof(exportedValueGetter)); @@ -167,7 +167,7 @@ namespace System.ComponentModel.Composition.Primitives /// of the property. /// /// - public IDictionary Metadata + public IDictionary Metadata { get { @@ -194,7 +194,7 @@ namespace System.ComponentModel.Composition.Primitives /// /// The method was not overridden by a derived class. /// - public object Value + public object? Value { get { @@ -202,7 +202,7 @@ namespace System.ComponentModel.Composition.Primitives // more than once, as locking would be required for that. The said locking is problematic, as we can't reliable call 3rd party code under a lock. if (_exportedValue == Export._EmptyValue) { - object exportedValue = GetExportedValueCore(); + object? exportedValue = GetExportedValueCore(); Interlocked.CompareExchange(ref _exportedValue, exportedValue, Export._EmptyValue); } @@ -234,7 +234,7 @@ namespace System.ComponentModel.Composition.Primitives /// /// [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] - protected virtual object GetExportedValueCore() + protected virtual object? GetExportedValueCore() { if (_exportedValueGetter != null) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportDefinition.cs index 6256a028160..bee7b947c76 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportDefinition.cs @@ -15,8 +15,8 @@ namespace System.ComponentModel.Composition.Primitives { // Unlike contract name, metadata has a sensible default; set it to an empty bag, // so that derived definitions only need to override ContractName by default. - private readonly IDictionary _metadata = MetadataServices.EmptyMetadata; - private readonly string _contractName; + private readonly IDictionary _metadata = MetadataServices.EmptyMetadata; + private readonly string? _contractName; /// /// Initializes a new instance of the class. @@ -52,7 +52,7 @@ namespace System.ComponentModel.Composition.Primitives /// /// is an empty string (""). /// - public ExportDefinition(string contractName, IDictionary metadata) + public ExportDefinition(string contractName, IDictionary? metadata) { Requires.NotNullOrEmpty(contractName, nameof(contractName)); @@ -113,7 +113,7 @@ namespace System.ComponentModel.Composition.Primitives /// /// /// - public virtual IDictionary Metadata + public virtual IDictionary Metadata { get { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportedDelegate.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportedDelegate.cs index f37d88b7abd..abc22014379 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportedDelegate.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportedDelegate.cs @@ -12,12 +12,12 @@ namespace System.ComponentModel.Composition.Primitives [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public class ExportedDelegate { - private readonly object _instance; - private readonly MethodInfo _method; + private readonly object? _instance; + private readonly MethodInfo _method = null!; protected ExportedDelegate() { } - public ExportedDelegate(object instance, MethodInfo method) + public ExportedDelegate(object? instance, MethodInfo method) { Requires.NotNull(method, nameof(method)); @@ -25,7 +25,7 @@ namespace System.ComponentModel.Composition.Primitives _method = method; } - public virtual Delegate CreateDelegate(Type delegateType) + public virtual Delegate? CreateDelegate(Type delegateType) { Requires.NotNull(delegateType, nameof(delegateType)); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ICompositionElement.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ICompositionElement.cs index 1e3ae6ebfb4..e2e13a2281a 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ICompositionElement.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ICompositionElement.cs @@ -35,7 +35,7 @@ namespace System.ComponentModel.Composition.Primitives /// originated, or /// if the is the root composition element. /// - ICompositionElement Origin + ICompositionElement? Origin { get; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs index 6d9120daf9d..83ddadfe486 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs @@ -17,13 +17,13 @@ namespace System.ComponentModel.Composition.Primitives public class ImportDefinition { internal static readonly string EmptyContractName = string.Empty; - private readonly Expression> _constraint; + private readonly Expression>? _constraint; private readonly ImportCardinality _cardinality = ImportCardinality.ExactlyOne; private readonly string _contractName = EmptyContractName; private readonly bool _isRecomposable; private readonly bool _isPrerequisite = true; - private Func _compiledConstraint; - private readonly IDictionary _metadata = MetadataServices.EmptyMetadata; + private Func? _compiledConstraint; + private readonly IDictionary _metadata = MetadataServices.EmptyMetadata; /// /// Initializes a new instance of the class. @@ -80,7 +80,7 @@ namespace System.ComponentModel.Composition.Primitives /// values. /// [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] - public ImportDefinition(Expression> constraint, string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) + public ImportDefinition(Expression> constraint, string? contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) : this(contractName, cardinality, isRecomposable, isPrerequisite, MetadataServices.EmptyMetadata) { Requires.NotNull(constraint, nameof(constraint)); @@ -89,7 +89,7 @@ namespace System.ComponentModel.Composition.Primitives } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] - public ImportDefinition(Expression> constraint, string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary metadata) + public ImportDefinition(Expression> constraint, string? contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary? metadata) : this(contractName, cardinality, isRecomposable, isPrerequisite, metadata) { Requires.NotNull(constraint, nameof(constraint)); @@ -97,7 +97,7 @@ namespace System.ComponentModel.Composition.Primitives _constraint = constraint; } - internal ImportDefinition(string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary metadata) + internal ImportDefinition(string? contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary? metadata) { if ( (cardinality != ImportCardinality.ExactlyOne) && @@ -159,7 +159,7 @@ namespace System.ComponentModel.Composition.Primitives /// /// /// - public virtual IDictionary Metadata + public virtual IDictionary Metadata { get { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs index 1085c176c62..4e0fcbed1d6 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs @@ -17,9 +17,7 @@ namespace System.ComponentModel.Composition.Primitives public static ImportDefinition GetProductImportDefinition(this ImportDefinition import) { - IPartCreatorImportDefinition partCreatorDefinition = import as IPartCreatorImportDefinition; - - if (partCreatorDefinition != null) + if (import is IPartCreatorImportDefinition partCreatorDefinition) { return partCreatorDefinition.ProductImportDefinition; } @@ -33,8 +31,8 @@ namespace System.ComponentModel.Composition.Primitives { import = import.GetProductImportDefinition(); string contractName = import.ContractName; - string genericContractName = import.Metadata.GetValue(CompositionConstants.GenericContractMetadataName); - int[] importParametersOrder = import.Metadata.GetValue(CompositionConstants.GenericImportParametersOrderMetadataName); + string? genericContractName = import.Metadata.GetValue(CompositionConstants.GenericContractMetadataName); + int[]? importParametersOrder = import.Metadata.GetValue(CompositionConstants.GenericImportParametersOrderMetadataName); if (importParametersOrder != null) { int partArity = part.Metadata.GetValue(CompositionConstants.GenericPartArityMetadataName); @@ -56,9 +54,7 @@ namespace System.ComponentModel.Composition.Primitives import = import.GetProductImportDefinition(); if (expandGenerics) { - Tuple singleMatch; - IEnumerable> multipleMatches; - return part.TryGetExports(import, out singleMatch, out multipleMatches); + return part.TryGetExports(import, out Tuple? singleMatch, out IEnumerable>? multipleMatches); } else { @@ -68,13 +64,13 @@ namespace System.ComponentModel.Composition.Primitives private static ImportDefinition TranslateImport(ImportDefinition import, ComposablePartDefinition part) { - ContractBasedImportDefinition contractBasedImport = import as ContractBasedImportDefinition; + ContractBasedImportDefinition? contractBasedImport = import as ContractBasedImportDefinition; if (contractBasedImport == null) { return import; } - int[] importParametersOrder = contractBasedImport.Metadata.GetValue(CompositionConstants.GenericImportParametersOrderMetadataName); + int[]? importParametersOrder = contractBasedImport.Metadata.GetValue(CompositionConstants.GenericImportParametersOrderMetadataName); if (importParametersOrder == null) { return import; @@ -87,7 +83,7 @@ namespace System.ComponentModel.Composition.Primitives } string contractName = GenericServices.GetGenericName(contractBasedImport.ContractName, importParametersOrder, partArity); - string requiredTypeIdentity = GenericServices.GetGenericName(contractBasedImport.RequiredTypeIdentity, importParametersOrder, partArity); + string requiredTypeIdentity = GenericServices.GetGenericName(contractBasedImport.RequiredTypeIdentity!, importParametersOrder, partArity); return new ContractBasedImportDefinition( contractName, requiredTypeIdentity, diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs index 96ac6a22d8c..9e53b49a7d8 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; +using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel.Composition.Primitives { @@ -13,9 +14,9 @@ namespace System.ComponentModel.Composition.Primitives internal class SerializableCompositionElement : ICompositionElement { private readonly string _displayName; - private readonly ICompositionElement _origin; + private readonly ICompositionElement? _origin; - public SerializableCompositionElement(string displayName, ICompositionElement origin) + public SerializableCompositionElement(string displayName, ICompositionElement? origin) { _displayName = displayName; _origin = origin; @@ -25,16 +26,17 @@ namespace System.ComponentModel.Composition.Primitives public string DisplayName => _displayName; - public ICompositionElement Origin => _origin; + public ICompositionElement? Origin => _origin; - public static ICompositionElement FromICompositionElement(ICompositionElement element) + [return: NotNullIfNotNull("element")] + public static ICompositionElement? FromICompositionElement(ICompositionElement? element) { if (element == null) { return null; } - ICompositionElement origin = FromICompositionElement(element.Origin); + ICompositionElement? origin = FromICompositionElement(element.Origin); // Otherwise, we need to create a serializable wrapper return new SerializableCompositionElement(element.DisplayName, origin); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/DisposableReflectionComposablePart.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/DisposableReflectionComposablePart.cs index c6cc44a6e26..d3030dadaf1 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/DisposableReflectionComposablePart.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/DisposableReflectionComposablePart.cs @@ -15,10 +15,9 @@ namespace System.ComponentModel.Composition.ReflectionModel { } - protected override void ReleaseInstanceIfNecessary(object instance) + protected override void ReleaseInstanceIfNecessary(object? instance) { - IDisposable disposable = instance as IDisposable; - if (disposable != null) + if (instance is IDisposable disposable) { disposable.Dispose(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs index b6ce9bee47c..847a2dd400f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs @@ -16,11 +16,9 @@ namespace System.ComponentModel.Composition.ReflectionModel { T exportedValue; Action disposeAction; - IDisposable disposable = null; + IDisposable? disposable = null; - CatalogExportProvider.ScopeFactoryExport scopeFactoryExport = export as CatalogExportProvider.ScopeFactoryExport; - - if (scopeFactoryExport != null) + if (export is CatalogExportProvider.ScopeFactoryExport scopeFactoryExport) { // Scoped PartCreatorExport Export exportProduct = scopeFactoryExport.CreateExportProduct(); @@ -29,9 +27,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } else { - CatalogExportProvider.FactoryExport factoryExport = export as CatalogExportProvider.FactoryExport; - - if (factoryExport != null) + if (export is CatalogExportProvider.FactoryExport factoryExport) { // PartCreatorExport is the more optimized route Export exportProduct = factoryExport.CreateExportProduct(); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs index 450c29b7ffa..da3e3f37ae9 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs @@ -9,8 +9,8 @@ namespace System.ComponentModel.Composition.ReflectionModel { internal sealed partial class ExportFactoryCreator { - private static readonly MethodInfo _createStronglyTypedExportFactoryOfT = typeof(ExportFactoryCreator).GetMethod("CreateStronglyTypedExportFactoryOfT", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - private static readonly MethodInfo _createStronglyTypedExportFactoryOfTM = typeof(ExportFactoryCreator).GetMethod("CreateStronglyTypedExportFactoryOfTM", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + private static readonly MethodInfo _createStronglyTypedExportFactoryOfT = typeof(ExportFactoryCreator).GetMethod("CreateStronglyTypedExportFactoryOfT", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)!; + private static readonly MethodInfo _createStronglyTypedExportFactoryOfTM = typeof(ExportFactoryCreator).GetMethod("CreateStronglyTypedExportFactoryOfTM", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)!; private readonly Type _exportFactoryType; @@ -24,9 +24,9 @@ namespace System.ComponentModel.Composition.ReflectionModel _exportFactoryType = exportFactoryType; } - public Func CreateStronglyTypedExportFactoryFactory(Type exportType, Type metadataViewType) + public Func CreateStronglyTypedExportFactoryFactory(Type exportType, Type? metadataViewType) { - MethodInfo genericMethod = null; + MethodInfo genericMethod; if (metadataViewType == null) { genericMethod = _createStronglyTypedExportFactoryOfT.MakeGenericMethod(exportType); @@ -57,7 +57,7 @@ namespace System.ComponentModel.Composition.ReflectionModel var instance = Activator.CreateInstance(constructed, args); - return instance; + return instance!; } private object CreateStronglyTypedExportFactoryOfTM(Export export) @@ -69,11 +69,11 @@ namespace System.ComponentModel.Composition.ReflectionModel Func> exportLifetimeContextCreator = () => lifetimeContext.GetExportLifetimeContextFromExport(export); var metadataView = AttributedModelServices.GetMetadataView(export.Metadata); - object[] args = { exportLifetimeContextCreator, metadataView }; + object?[] args = { exportLifetimeContextCreator, metadataView }; var instance = Activator.CreateInstance(constructed, args); - return instance; + return instance!; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs index c4d47eaa047..eaa450d2afd 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs @@ -13,7 +13,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { private readonly ExportDefinition _definition; private readonly ReflectionMember _member; - private object _cachedValue = null; + private object? _cachedValue = null; private volatile bool _isValueCached = false; public ExportingMember(ExportDefinition definition, ReflectionMember member) @@ -42,13 +42,13 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return _definition; } } - public object GetExportedValue(object instance, object @lock) + public object? GetExportedValue(object? instance, object @lock) { EnsureReadable(); if (!_isValueCached) { - object exportedValue; + object? exportedValue; try { exportedValue = _member.GetValue(instance); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs index c9ad48c9132..d4dfa880d08 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; +using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel.Composition.ReflectionModel { @@ -94,7 +95,8 @@ namespace System.ComponentModel.Composition.ReflectionModel return genericSpecialization; } - public static IEnumerable CreateTypeSpecializations(this Type[] types, Type[] specializationTypes) + [return: NotNullIfNotNull("types")] + public static IEnumerable? CreateTypeSpecializations(this Type[]? types, Type[] specializationTypes) { if (types == null) { @@ -138,12 +140,12 @@ namespace System.ComponentModel.Composition.ReflectionModel } - public static bool CanSpecialize(Type type, IEnumerable constraints, GenericParameterAttributes attributes) + public static bool CanSpecialize(Type? type, IEnumerable? constraints, GenericParameterAttributes attributes) { - return CanSpecialize(type, constraints) && CanSpecialize(type, attributes); + return CanSpecialize(type, constraints) && CanSpecialize(type!, attributes); } - public static bool CanSpecialize(Type type, IEnumerable constraintTypes) + public static bool CanSpecialize(Type? type, IEnumerable? constraintTypes) { if (constraintTypes == null) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs index 4ad040a9402..00f89e1b8fa 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs @@ -10,6 +10,7 @@ using System.Reflection; using System.Threading; using Microsoft.Internal; using Microsoft.Internal.Collections; +using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel.Composition.ReflectionModel { @@ -19,14 +20,14 @@ namespace System.ComponentModel.Composition.ReflectionModel private readonly ReflectionComposablePartDefinition _originalPart; private readonly Type[] _specialization; private readonly string[] _specializationIdentities; - private IEnumerable _exports; - private IEnumerable _imports; + private IEnumerable? _exports; + private IEnumerable? _imports; private readonly Lazy _lazyPartType; - private List _members; - private List> _parameters; - private Dictionary _membersTable; - private Dictionary, ParameterInfo> _parametersTable; - private ConstructorInfo _constructor; + private List? _members; + private List>? _parameters; + private Dictionary? _membersTable; + private Dictionary, ParameterInfo>? _parametersTable; + private ConstructorInfo? _constructor; private readonly object _lock = new object(); public GenericSpecializationPartCreationInfo(IReflectionPartCreationInfo originalPartCreationInfo, ReflectionComposablePartDefinition originalPart, Type[] specialization) @@ -78,12 +79,12 @@ namespace System.ComponentModel.Composition.ReflectionModel return _lazyPartType; } - public ConstructorInfo GetConstructor() + public ConstructorInfo? GetConstructor() { if (_constructor == null) { - ConstructorInfo genericConstuctor = _originalPartCreationInfo.GetConstructor(); - ConstructorInfo result = null; + ConstructorInfo? genericConstuctor = _originalPartCreationInfo.GetConstructor(); + ConstructorInfo? result = null; if (genericConstuctor != null) { foreach (ConstructorInfo constructor in GetPartType().GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) @@ -109,9 +110,9 @@ namespace System.ComponentModel.Composition.ReflectionModel return _constructor; } - public IDictionary GetMetadata() + public IDictionary GetMetadata() { - var originalMetadata = new Dictionary(_originalPartCreationInfo.GetMetadata(), StringComparers.MetadataKeyNames); + var originalMetadata = new Dictionary(_originalPartCreationInfo.GetMetadata()!, StringComparers.MetadataKeyNames); originalMetadata.Remove(CompositionConstants.IsGenericPartMetadataName); originalMetadata.Remove(CompositionConstants.GenericPartArityMetadataName); originalMetadata.Remove(CompositionConstants.GenericParameterConstraintsMetadataName); @@ -151,8 +152,8 @@ namespace System.ComponentModel.Composition.ReflectionModel PopulateImportsAndExports(); - List members = null; - List> parameters = null; + List? members = null; + List>? parameters = null; lock (_lock) { if (_membersTable == null) @@ -170,8 +171,8 @@ namespace System.ComponentModel.Composition.ReflectionModel // // Get all members that can be of interest and extract their MetadataTokens // - Dictionary membersTable = BuildMembersTable(members); - Dictionary, ParameterInfo> parametersTable = BuildParametersTable(parameters); + Dictionary membersTable = BuildMembersTable(members!); + Dictionary, ParameterInfo>? parametersTable = BuildParametersTable(parameters); lock (_lock) { @@ -241,7 +242,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { if (genericAccessors[i] != null) { - specializedPartMembers.TryGetValue(genericAccessors[i].MetadataToken, out accessors[i]); + specializedPartMembers.TryGetValue(genericAccessors[i].MetadataToken, out accessors[i]!); if (accessors[i] == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); @@ -255,13 +256,14 @@ namespace System.ComponentModel.Composition.ReflectionModel return membersTable; } - private Dictionary, ParameterInfo> BuildParametersTable(List> parameters) + [return: NotNullIfNotNull("parameters")] + private Dictionary, ParameterInfo>? BuildParametersTable(List>? parameters) { if (parameters != null) { Dictionary, ParameterInfo> parametersTable = new Dictionary, ParameterInfo>(); // GENTODO - error case - ParameterInfo[] constructorParameters = GetConstructor().GetParameters(); + ParameterInfo[] constructorParameters = GetConstructor()!.GetParameters(); foreach (var lazyParameter in parameters) { parametersTable[lazyParameter] = constructorParameters[lazyParameter.Value.Position]; @@ -281,7 +283,7 @@ namespace System.ComponentModel.Composition.ReflectionModel foreach (ImportDefinition originalImport in _originalPartCreationInfo.GetImports()) { - ReflectionImportDefinition reflectionImport = originalImport as ReflectionImportDefinition; + ReflectionImportDefinition? reflectionImport = originalImport as ReflectionImportDefinition; if (reflectionImport == null) { // we always ignore these @@ -299,20 +301,18 @@ namespace System.ComponentModel.Composition.ReflectionModel bool isExportFactory = false; ContractBasedImportDefinition productImport = reflectionImport; - IPartCreatorImportDefinition exportFactoryImportDefinition = reflectionImport as IPartCreatorImportDefinition; - if (exportFactoryImportDefinition != null) + if (reflectionImport is IPartCreatorImportDefinition exportFactoryImportDefinition) { productImport = exportFactoryImportDefinition.ProductImportDefinition; isExportFactory = true; } string contractName = Translate(productImport.ContractName); - string requiredTypeIdentity = Translate(productImport.RequiredTypeIdentity); - IDictionary metadata = TranslateImportMetadata(productImport); + string requiredTypeIdentity = Translate(productImport.RequiredTypeIdentity!); + IDictionary metadata = TranslateImportMetadata(productImport); - ReflectionMemberImportDefinition memberImport = reflectionImport as ReflectionMemberImportDefinition; - ImportDefinition import = null; - if (memberImport != null) + ImportDefinition? import = null; + if (reflectionImport is ReflectionMemberImportDefinition memberImport) { LazyMemberInfo lazyMember = memberImport.ImportingLazyMember; LazyMemberInfo importingMember = new LazyMemberInfo(lazyMember.MemberType, () => GetAccessors(lazyMember)); @@ -351,7 +351,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } else { - ReflectionParameterImportDefinition parameterImport = reflectionImport as ReflectionParameterImportDefinition; + ReflectionParameterImportDefinition? parameterImport = reflectionImport as ReflectionParameterImportDefinition; if (parameterImport == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); @@ -400,7 +400,7 @@ namespace System.ComponentModel.Composition.ReflectionModel foreach (ExportDefinition originalExport in _originalPartCreationInfo.GetExports()) { - ReflectionMemberExportDefinition reflectionExport = originalExport as ReflectionMemberExportDefinition; + ReflectionMemberExportDefinition? reflectionExport = originalExport as ReflectionMemberExportDefinition; if (reflectionExport == null) { // we always ignore these @@ -415,7 +415,7 @@ namespace System.ComponentModel.Composition.ReflectionModel public ExportDefinition TranslateExpot(ReflectionMemberExportDefinition reflectionExport, List members) { - ExportDefinition export = null; + ExportDefinition? export = null; LazyMemberInfo lazyMember = reflectionExport.ExportingLazyMember; var capturedLazyMember = lazyMember; var capturedReflectionExport = reflectionExport; @@ -423,7 +423,7 @@ namespace System.ComponentModel.Composition.ReflectionModel string contractName = Translate(reflectionExport.ContractName, reflectionExport.Metadata.GetValue(CompositionConstants.GenericExportParametersOrderMetadataName)); LazyMemberInfo exportingMember = new LazyMemberInfo(capturedLazyMember.MemberType, () => GetAccessors(capturedLazyMember)); - Lazy> lazyMetadata = new Lazy>(() => TranslateExportMetadata(capturedReflectionExport)); + Lazy> lazyMetadata = new Lazy>(() => TranslateExportMetadata(capturedReflectionExport)); export = new ReflectionMemberExportDefinition( exportingMember, @@ -435,7 +435,7 @@ namespace System.ComponentModel.Composition.ReflectionModel return export; } - private string Translate(string originalValue, int[] genericParametersOrder) + private string Translate(string originalValue, int[]? genericParametersOrder) { if (genericParametersOrder != null) { @@ -453,12 +453,12 @@ namespace System.ComponentModel.Composition.ReflectionModel return string.Format(CultureInfo.InvariantCulture, originalValue, _specializationIdentities); } - private IDictionary TranslateImportMetadata(ContractBasedImportDefinition originalImport) + private IDictionary TranslateImportMetadata(ContractBasedImportDefinition originalImport) { - int[] importParametersOrder = originalImport.Metadata.GetValue(CompositionConstants.GenericImportParametersOrderMetadataName); + int[]? importParametersOrder = originalImport.Metadata.GetValue(CompositionConstants.GenericImportParametersOrderMetadataName); if (importParametersOrder != null) { - Dictionary metadata = new Dictionary(originalImport.Metadata, StringComparers.MetadataKeyNames); + Dictionary metadata = new Dictionary(originalImport.Metadata, StringComparers.MetadataKeyNames); // Get the newly re-qualified name of the generic contract and the subset of applicable types from the specialization metadata[CompositionConstants.GenericContractMetadataName] = GenericServices.GetGenericName(originalImport.ContractName, importParametersOrder, _specialization.Length); @@ -473,11 +473,11 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - private IDictionary TranslateExportMetadata(ReflectionMemberExportDefinition originalExport) + private IDictionary TranslateExportMetadata(ReflectionMemberExportDefinition originalExport) { - Dictionary metadata = new Dictionary(originalExport.Metadata, StringComparers.MetadataKeyNames); + Dictionary metadata = new Dictionary(originalExport.Metadata, StringComparers.MetadataKeyNames); - string exportTypeIdentity = originalExport.Metadata.GetValue(CompositionConstants.ExportTypeIdentityMetadataName); + string? exportTypeIdentity = originalExport.Metadata.GetValue(CompositionConstants.ExportTypeIdentityMetadataName); if (!string.IsNullOrEmpty(exportTypeIdentity)) { metadata[CompositionConstants.ExportTypeIdentityMetadataName] = Translate(exportTypeIdentity, originalExport.Metadata.GetValue(CompositionConstants.GenericExportParametersOrderMetadataName)); @@ -519,13 +519,13 @@ namespace System.ComponentModel.Composition.ReflectionModel public IEnumerable GetExports() { PopulateImportsAndExports(); - return _exports; + return _exports!; } public IEnumerable GetImports() { PopulateImportsAndExports(); - return _imports; + return _imports!; } public bool IsDisposalRequired @@ -546,20 +546,14 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return Translate(_originalPartCreationInfo.DisplayName); } } - public ICompositionElement Origin + public ICompositionElement? Origin { get { return _originalPartCreationInfo.Origin; } } - public override bool Equals(object obj) + public override bool Equals(object? obj) { - GenericSpecializationPartCreationInfo that = obj as GenericSpecializationPartCreationInfo; - if (that == null) - { - return false; - } - - return (_originalPartCreationInfo.Equals(that._originalPartCreationInfo)) && + return obj is GenericSpecializationPartCreationInfo that && (_originalPartCreationInfo.Equals(that._originalPartCreationInfo)) && (_specialization.IsArrayEqual(that._specialization)); } @@ -568,7 +562,7 @@ namespace System.ComponentModel.Composition.ReflectionModel return _originalPartCreationInfo.GetHashCode(); } - public static bool CanSpecialize(IDictionary partMetadata, Type[] specialization) + public static bool CanSpecialize(IDictionary partMetadata, Type[] specialization) { int partArity = partMetadata.GetValue(CompositionConstants.GenericPartArityMetadataName); @@ -577,8 +571,8 @@ namespace System.ComponentModel.Composition.ReflectionModel return false; } - object[] genericParameterConstraints = partMetadata.GetValue(CompositionConstants.GenericParameterConstraintsMetadataName); - GenericParameterAttributes[] genericParameterAttributes = partMetadata.GetValue(CompositionConstants.GenericParameterAttributesMetadataName); + object[]? genericParameterConstraints = partMetadata.GetValue(CompositionConstants.GenericParameterConstraintsMetadataName); + GenericParameterAttributes[]? genericParameterAttributes = partMetadata.GetValue(CompositionConstants.GenericParameterAttributesMetadataName); // if no constraints and attributes been specifed, anything can be created if ((genericParameterConstraints == null) && (genericParameterAttributes == null)) @@ -600,8 +594,8 @@ namespace System.ComponentModel.Composition.ReflectionModel { if (!GenericServices.CanSpecialize( specialization[i], - (genericParameterConstraints[i] as Type[]).CreateTypeSpecializations(specialization), - genericParameterAttributes[i])) + (genericParameterConstraints![i] as Type[]).CreateTypeSpecializations(specialization), + genericParameterAttributes![i])) { return false; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/IReflectionPartCreationInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/IReflectionPartCreationInfo.cs index 974891f4820..1ff705c19d0 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/IReflectionPartCreationInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/IReflectionPartCreationInfo.cs @@ -12,8 +12,8 @@ namespace System.ComponentModel.Composition.ReflectionModel { Type GetPartType(); Lazy GetLazyPartType(); - ConstructorInfo GetConstructor(); - IDictionary GetMetadata(); + ConstructorInfo? GetConstructor(); + IDictionary? GetMetadata(); IEnumerable GetExports(); IEnumerable GetImports(); bool IsDisposalRequired { get; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs index 3b58f81371d..ebc0705dd8c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using Microsoft.Internal.Collections; +using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel.Composition.ReflectionModel { @@ -17,12 +18,12 @@ namespace System.ComponentModel.Composition.ReflectionModel private readonly Type _type; private readonly bool _isAssignableCollectionType; - private Type _contractType; - private Func _castSingleValue; + private Type _contractType = null!; // Initialized in Initialize() + private Func? _castSingleValue; private readonly bool _isOpenGeneric = false; [ThreadStatic] - internal static Dictionary> _castSingleValueCache; + internal static Dictionary>? _castSingleValueCache; private static Dictionary> CastSingleValueCache { @@ -58,7 +59,7 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return _isAssignableCollectionType; } } - public Type ElementType { get; private set; } + public Type? ElementType { get; private set; } public Type ActualType { @@ -69,7 +70,7 @@ namespace System.ComponentModel.Composition.ReflectionModel public Type ContractType { get { return _contractType; } } - public Func CastExport + public Func? CastExport { get { @@ -81,7 +82,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - public Type MetadataViewType { get; private set; } + public Type? MetadataViewType { get; private set; } private Type CheckForCollection(Type type) { @@ -93,7 +94,7 @@ namespace System.ComponentModel.Composition.ReflectionModel return type; } - private static bool IsGenericDescendentOf(Type type, Type baseGenericTypeDefinition) + private static bool IsGenericDescendentOf(Type? type, Type baseGenericTypeDefinition) { if (type == typeof(object) || type == null) { @@ -169,7 +170,7 @@ namespace System.ComponentModel.Composition.ReflectionModel return (genericType == LazyOfTType) || (genericType == LazyOfTMType); } - private static bool TryGetCastFunction(Type genericType, bool isOpenGeneric, Type[] arguments, out Func castFunction) + private static bool TryGetCastFunction(Type genericType, bool isOpenGeneric, Type[] arguments, [NotNullWhen(true)] out Func? castFunction) { castFunction = null; @@ -211,7 +212,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } else { - throw ExceptionBuilder.ExportFactory_TooManyGenericParameters(genericType.FullName); + throw ExceptionBuilder.ExportFactory_TooManyGenericParameters(genericType.FullName!); } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs index 98ef7f688c3..502e6e24041 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs @@ -34,7 +34,7 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return _importType; } } - public object CastExportsToImportType(Export[] exports) + public object? CastExportsToImportType(Export[] exports) { if (Definition.Cardinality == ImportCardinality.ZeroOrMore) { @@ -61,7 +61,7 @@ namespace System.ComponentModel.Composition.ReflectionModel for (int i = 0; i < array.Length; i++) { - object value = CastSingleExportToImportType(elementType, exports[i]); + object? value = CastSingleExportToImportType(elementType, exports[i]); array.SetValue(value, i); } @@ -69,7 +69,7 @@ namespace System.ComponentModel.Composition.ReflectionModel return array; } - private object CastExportsToSingleImportType(Export[] exports) + private object? CastExportsToSingleImportType(Export[] exports) { if (exports == null) { @@ -89,7 +89,7 @@ namespace System.ComponentModel.Composition.ReflectionModel return CastSingleExportToImportType(ImportType.ActualType, exports[0]); } - private object CastSingleExportToImportType(Type type, Export export) + private object? CastSingleExportToImportType(Type type, Export export) { if (ImportType.CastExport != null) { @@ -99,12 +99,11 @@ namespace System.ComponentModel.Composition.ReflectionModel return Cast(type, export); } - private object Cast(Type type, Export export) + private object? Cast(Type type, Export export) { - object value = export.Value; + object? value = export.Value; - object result; - if (!ContractServices.TryCast(type, value, out result)) + if (!ContractServices.TryCast(type, value, out object? result)) { throw new ComposablePartException( SR.Format( diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs index 5f5150b209b..3e7dfa2df8e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs @@ -28,7 +28,7 @@ namespace System.ComponentModel.Composition.ReflectionModel _member = member; } - public void SetExportedValue(object instance, object value) + public void SetExportedValue(object? instance, object value) { if (RequiresCollectionNormalization()) { @@ -59,7 +59,7 @@ namespace System.ComponentModel.Composition.ReflectionModel return true; } - private void SetSingleMemberValue(object instance, object value) + private void SetSingleMemberValue(object? instance, object? value) { EnsureWritable(); @@ -106,32 +106,32 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - private void SetCollectionMemberValue(object instance, IEnumerable values) + private void SetCollectionMemberValue(object? instance, IEnumerable values) { if (values == null) { throw new ArgumentNullException(nameof(values)); } - ICollection collection = null; - Type itemType = CollectionServices.GetCollectionElementType(ImportType.ActualType); + ICollection? collection = null; + Type? itemType = CollectionServices.GetCollectionElementType(ImportType.ActualType); if (itemType != null) { collection = GetNormalizedCollection(itemType, instance); } EnsureCollectionIsWritable(collection); - PopulateCollection(collection, values); + PopulateCollection(collection!, values); } - private ICollection GetNormalizedCollection(Type itemType, object instance) + private ICollection GetNormalizedCollection(Type itemType, object? instance) { if (itemType == null) { throw new ArgumentNullException(nameof(itemType)); } - object collectionObject = null; + object? collectionObject = null; if (_member.CanRead) { @@ -152,7 +152,7 @@ namespace System.ComponentModel.Composition.ReflectionModel if (collectionObject == null) { - ConstructorInfo constructor = ImportType.ActualType.GetConstructor(Type.EmptyTypes); + ConstructorInfo? constructor = ImportType.ActualType.GetConstructor(Type.EmptyTypes); // If it contains a default public constructor create a new instance. if (constructor != null) @@ -189,7 +189,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - private void EnsureCollectionIsWritable(ICollection collection) + private void EnsureCollectionIsWritable(ICollection? collection) { bool isReadOnly = true; @@ -206,7 +206,7 @@ namespace System.ComponentModel.Composition.ReflectionModel SR.Format( SR.ReflectionModel_ImportCollectionIsReadOnlyThrewException, _member.GetDisplayName(), - collection.GetType().FullName), + collection!.GetType().FullName), Definition.ToElement(), exception); } @@ -222,7 +222,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - private void PopulateCollection(ICollection collection, IEnumerable values) + private void PopulateCollection(ICollection collection, IEnumerable values) { if (collection == null) { @@ -249,7 +249,7 @@ namespace System.ComponentModel.Composition.ReflectionModel exception); } - foreach (object value in values) + foreach (object? value in values) { try { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs index 3a8367d30e5..333c8a1cb52 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs @@ -12,8 +12,8 @@ namespace System.ComponentModel.Composition.ReflectionModel public struct LazyMemberInfo { private readonly MemberTypes _memberType; - private MemberInfo[] _accessors; - private readonly Func _accessorsCreator; + private MemberInfo?[]? _accessors; + private readonly Func? _accessorsCreator; public LazyMemberInfo(MemberInfo member) { @@ -31,11 +31,11 @@ namespace System.ComponentModel.Composition.ReflectionModel { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - _accessors = new MemberInfo[] { property.GetGetMethod(true), property.GetSetMethod(true) }; + _accessors = new MemberInfo?[] { property.GetGetMethod(true), property.GetSetMethod(true) }; break; case MemberTypes.Event: EventInfo event_ = (EventInfo)member; - _accessors = new MemberInfo[] { event_.GetRaiseMethod(true), event_.GetAddMethod(true), event_.GetRemoveMethod(true) }; + _accessors = new MemberInfo?[] { event_.GetRaiseMethod(true), event_.GetAddMethod(true), event_.GetRemoveMethod(true) }; break; default: _accessors = new MemberInfo[] { member }; @@ -89,7 +89,7 @@ namespace System.ComponentModel.Composition.ReflectionModel _accessors = accessors; } - return _accessors; + return _accessors!; } public override int GetHashCode() @@ -104,13 +104,13 @@ namespace System.ComponentModel.Composition.ReflectionModel { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - return MemberType.GetHashCode() ^ _accessors[0].GetHashCode(); + return MemberType.GetHashCode() ^ _accessors[0]!.GetHashCode(); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644 } } - public override bool Equals(object obj) + public override bool Equals(object? obj) { - LazyMemberInfo that = (LazyMemberInfo)obj; + LazyMemberInfo that = (LazyMemberInfo)obj!; // Difefrent member types mean different members if (_memberType != that._memberType) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs index 8c6fd35b18f..ddb37bde462 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs @@ -11,7 +11,7 @@ namespace System.ComponentModel.Composition.ReflectionModel internal class PartCreatorExportDefinition : ExportDefinition { private readonly ExportDefinition _productDefinition; - private IDictionary _metadata; + private IDictionary? _metadata; public PartCreatorExportDefinition(ExportDefinition productDefinition) : base() @@ -27,13 +27,13 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - public override IDictionary Metadata + public override IDictionary Metadata { get { if (_metadata == null) { - var metadata = new Dictionary(_productDefinition.Metadata); + var metadata = new Dictionary(_productDefinition.Metadata); metadata[CompositionConstants.ExportTypeIdentityMetadataName] = CompositionConstants.PartCreatorTypeIdentity; metadata[CompositionConstants.ProductDefinitionMetadataName] = _productDefinition; @@ -45,12 +45,9 @@ namespace System.ComponentModel.Composition.ReflectionModel internal static bool IsProductConstraintSatisfiedBy(ImportDefinition productImportDefinition, ExportDefinition exportDefinition) { - object productValue = null; - if (exportDefinition.Metadata.TryGetValue(CompositionConstants.ProductDefinitionMetadataName, out productValue)) + if (exportDefinition.Metadata.TryGetValue(CompositionConstants.ProductDefinitionMetadataName, out object? productValue)) { - ExportDefinition productDefinition = productValue as ExportDefinition; - - if (productDefinition != null) + if (productValue is ExportDefinition productDefinition) { return productImportDefinition.IsConstraintSatisfiedBy(productDefinition); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs index a66f8809b2f..3e0f2299021 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs @@ -15,7 +15,7 @@ namespace System.ComponentModel.Composition.ReflectionModel public PartCreatorMemberImportDefinition( LazyMemberInfo importingLazyMember, - ICompositionElement origin, + ICompositionElement? origin, ContractBasedImportDefinition productImportDefinition) : base(importingLazyMember, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity, productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, productImportDefinition.IsRecomposable, false, productImportDefinition.RequiredCreationPolicy, MetadataServices.EmptyMetadata, origin) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs index e7b94be5eae..d8917b38e7a 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs @@ -16,7 +16,7 @@ namespace System.ComponentModel.Composition.ReflectionModel public PartCreatorParameterImportDefinition( Lazy importingLazyParameter, - ICompositionElement origin, + ICompositionElement? origin, ContractBasedImportDefinition productImportDefinition) : base(importingLazyParameter, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity, productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, CreationPolicy.Any, MetadataServices.EmptyMetadata, origin) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs index 292eeba259e..356575699af 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs @@ -10,18 +10,19 @@ using System.Linq; using System.Reflection; using Microsoft.Internal; using Microsoft.Internal.Collections; +using System.Diagnostics; namespace System.ComponentModel.Composition.ReflectionModel { internal class ReflectionComposablePart : ComposablePart, ICompositionElement { private readonly ReflectionComposablePartDefinition _definition; - private volatile Dictionary _importValues = null; - private volatile Dictionary _importsCache = null; - private volatile Dictionary _exportsCache = null; + private volatile Dictionary? _importValues = null; + private volatile Dictionary? _importsCache = null; + private volatile Dictionary? _exportsCache = null; private volatile bool _invokeImportsSatisfied = true; private bool _initialCompositionComplete = false; - private volatile object _cachedInstance; + private volatile object? _cachedInstance; private readonly object _lock = new object(); public ReflectionComposablePart(ReflectionComposablePartDefinition definition) @@ -53,11 +54,11 @@ namespace System.ComponentModel.Composition.ReflectionModel EnsureRunning(); } - protected virtual void ReleaseInstanceIfNecessary(object instance) + protected virtual void ReleaseInstanceIfNecessary(object? instance) { } - private Dictionary ImportValues + private Dictionary ImportValues { get { @@ -69,7 +70,7 @@ namespace System.ComponentModel.Composition.ReflectionModel value = _importValues; if (value == null) { - value = new Dictionary(); + value = new Dictionary(); _importValues = value; } } @@ -98,7 +99,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - protected object CachedInstance + protected object? CachedInstance { get { @@ -118,7 +119,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - public override IDictionary Metadata + public override IDictionary Metadata { get { @@ -157,7 +158,7 @@ namespace System.ComponentModel.Composition.ReflectionModel // This is the ONLY method which is not executed under the ImportEngine composition lock. // We need to protect all state that is accesses - public override object GetExportedValue(ExportDefinition definition) + public override object? GetExportedValue(ExportDefinition definition) { RequiresRunning(); // given the implementation of the ImportEngine, this iwll be called under a lock if the part is still being composed @@ -169,7 +170,7 @@ namespace System.ComponentModel.Composition.ReflectionModel // access to _instance Requires.NotNull(definition, nameof(definition)); - ExportingMember member = null; + ExportingMember? member = null; lock (_lock) { member = GetExportingMemberFromDefinition(definition); @@ -189,7 +190,7 @@ namespace System.ComponentModel.Composition.ReflectionModel Requires.NotNull(definition, nameof(definition)); Requires.NotNull(exports, nameof(exports)); - ImportingItem item = GetImportingItemFromDefinition(definition); + ImportingItem? item = GetImportingItemFromDefinition(definition); if (item == null) { throw ExceptionBuilder.CreateImportDefinitionNotOnThisComposablePart(nameof(definition)); @@ -225,9 +226,9 @@ namespace System.ComponentModel.Composition.ReflectionModel return GetDisplayName(); } - private object GetExportedValue(ExportingMember member) + private object? GetExportedValue(ExportingMember member) { - object instance = null; + object? instance = null; if (member.RequiresInstance) { // Only activate the instance if we actually need to @@ -239,7 +240,7 @@ namespace System.ComponentModel.Composition.ReflectionModel private void SetImport(ImportingItem item, Export[] exports) { - object value = item.CastExportsToImportType(exports); + object? value = item.CastExportsToImportType(exports); lock (_lock) { @@ -248,7 +249,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - private object GetInstanceActivatingIfNeeded() + private object? GetInstanceActivatingIfNeeded() { var cachedInstance = _cachedInstance; @@ -258,8 +259,8 @@ namespace System.ComponentModel.Composition.ReflectionModel } else { - ConstructorInfo constructor = null; - object[] arguments = null; + ConstructorInfo? constructor = null; + object?[]? arguments = null; // determine whether activation is required, and collect necessary information for activation // we need to do that under a lock lock (_lock) @@ -282,7 +283,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } // create instance outside of the lock - object createdInstance = CreateInstance(constructor, arguments); + object? createdInstance = CreateInstance(constructor, arguments); SetPrerequisiteImports(); @@ -300,7 +301,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } // if the instance has been already set - if (createdInstance == null) + if (createdInstance != null) { ReleaseInstanceIfNecessary(createdInstance); } @@ -309,10 +310,10 @@ namespace System.ComponentModel.Composition.ReflectionModel return _cachedInstance; } - private object[] GetConstructorArguments() + private object?[] GetConstructorArguments() { ReflectionParameterImportDefinition[] parameterImports = ImportDefinitions.OfType().ToArray(); - object[] arguments = new object[parameterImports.Length]; + object?[] arguments = new object?[parameterImports.Length]; UseImportedValues( parameterImports, @@ -349,8 +350,8 @@ namespace System.ComponentModel.Composition.ReflectionModel // need activation. return ExportDefinitions.Any(definition => { - ExportingMember member = GetExportingMemberFromDefinition(definition); - + ExportingMember? member = GetExportingMemberFromDefinition(definition); + Debug.Assert(member != null); return member.RequiresInstance; }); } @@ -411,10 +412,10 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - private object CreateInstance(ConstructorInfo constructor, object[] arguments) + private object CreateInstance(ConstructorInfo constructor, object?[] arguments) { - Exception exception = null; - object instance = null; + Exception? exception = null; + object instance = null!; try { @@ -462,7 +463,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { ImportingMember importMember = (ImportingMember)import; - object instance = GetInstanceActivatingIfNeeded(); + object? instance = GetInstanceActivatingIfNeeded(); importMember.SetExportedValue(instance, value); } @@ -474,10 +475,10 @@ namespace System.ComponentModel.Composition.ReflectionModel foreach (var definition in definitions) { - ImportingItem import = GetImportingItemFromDefinition(definition); + ImportingItem? import = GetImportingItemFromDefinition(definition); + Debug.Assert(import != null); - object value; - if (!TryGetImportValue(definition, out value)) + if (!TryGetImportValue(definition, out object? value)) { if (!errorIfMissing) { @@ -500,13 +501,13 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - useImportValue(import, definition, value); + useImportValue(import, definition, value!); } result.ThrowOnErrors(); } - private bool TryGetImportValue(ImportDefinition definition, out object value) + private bool TryGetImportValue(ImportDefinition definition, out object? value) { lock (_lock) { @@ -526,7 +527,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { if (_invokeImportsSatisfied) { - IPartImportsSatisfiedNotification notify = GetInstanceActivatingIfNeeded() as IPartImportsSatisfiedNotification; + IPartImportsSatisfiedNotification? notify = GetInstanceActivatingIfNeeded() as IPartImportsSatisfiedNotification; lock (_lock) { @@ -558,10 +559,9 @@ namespace System.ComponentModel.Composition.ReflectionModel } // this is always called under a lock - private ExportingMember GetExportingMemberFromDefinition(ExportDefinition definition) + private ExportingMember? GetExportingMemberFromDefinition(ExportDefinition definition) { - ExportingMember result; - ReflectionMemberExportDefinition reflectionExport = definition as ReflectionMemberExportDefinition; + ReflectionMemberExportDefinition? reflectionExport = definition as ReflectionMemberExportDefinition; if (reflectionExport == null) { return null; @@ -572,7 +572,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { _exportsCache = new Dictionary(); } - if (!_exportsCache.TryGetValue(exportIndex, out result)) + if (!_exportsCache.TryGetValue(exportIndex, out ExportingMember? result)) { result = GetExportingMember(definition); if (result != null) @@ -584,10 +584,9 @@ namespace System.ComponentModel.Composition.ReflectionModel return result; } - private ImportingItem GetImportingItemFromDefinition(ImportDefinition definition) + private ImportingItem? GetImportingItemFromDefinition(ImportDefinition definition) { - ImportingItem result; - if (!ImportsCache.TryGetValue(definition, out result)) + if (!ImportsCache.TryGetValue(definition, out ImportingItem? result)) { result = GetImportingItem(definition); if (result != null) @@ -599,10 +598,9 @@ namespace System.ComponentModel.Composition.ReflectionModel return result; } - private static ImportingItem GetImportingItem(ImportDefinition definition) + private static ImportingItem? GetImportingItem(ImportDefinition definition) { - ReflectionImportDefinition reflectionDefinition = definition as ReflectionImportDefinition; - if (reflectionDefinition != null) + if (definition is ReflectionImportDefinition reflectionDefinition) { return reflectionDefinition.ToImportingItem(); } @@ -610,10 +608,9 @@ namespace System.ComponentModel.Composition.ReflectionModel return null; } - private static ExportingMember GetExportingMember(ExportDefinition definition) + private static ExportingMember? GetExportingMember(ExportDefinition definition) { - ReflectionMemberExportDefinition exportDefinition = definition as ReflectionMemberExportDefinition; - if (exportDefinition != null) + if (definition is ReflectionMemberExportDefinition exportDefinition) { return exportDefinition.ToExportingMember(); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs index 704c9f143d9..5cce60871db 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs @@ -16,10 +16,10 @@ namespace System.ComponentModel.Composition.ReflectionModel { private readonly IReflectionPartCreationInfo _creationInfo; - private volatile ImportDefinition[] _imports; - private volatile ExportDefinition[] _exports; - private volatile IDictionary _metadata; - private volatile ConstructorInfo _constructor; + private volatile ImportDefinition[]? _imports; + private volatile ExportDefinition[]? _exports; + private volatile IDictionary? _metadata; + private volatile ConstructorInfo? _constructor; private readonly object _lock = new object(); public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo) @@ -41,11 +41,11 @@ namespace System.ComponentModel.Composition.ReflectionModel return _creationInfo.GetLazyPartType(); } - public ConstructorInfo GetConstructor() + public ConstructorInfo? GetConstructor() { if (_constructor == null) { - ConstructorInfo constructor = _creationInfo.GetConstructor(); + ConstructorInfo? constructor = _creationInfo.GetConstructor(); lock (_lock) { if (_constructor == null) @@ -104,13 +104,13 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - public override IDictionary Metadata + public override IDictionary Metadata { get { if (_metadata == null) { - IDictionary metadata = _creationInfo.GetMetadata().AsReadOnly(); + IDictionary metadata = _creationInfo.GetMetadata().AsReadOnly(); lock (_lock) { if (_metadata == null) @@ -144,10 +144,9 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - internal override ComposablePartDefinition GetGenericPartDefinition() + internal override ComposablePartDefinition? GetGenericPartDefinition() { - GenericSpecializationPartCreationInfo genericCreationInfo = _creationInfo as GenericSpecializationPartCreationInfo; - if (genericCreationInfo != null) + if (_creationInfo is GenericSpecializationPartCreationInfo genericCreationInfo) { return genericCreationInfo.OriginalPart; } @@ -155,31 +154,29 @@ namespace System.ComponentModel.Composition.ReflectionModel return null; } - internal override bool TryGetExports(ImportDefinition definition, out Tuple singleMatch, out IEnumerable> multipleMatches) + internal override bool TryGetExports(ImportDefinition definition, out Tuple? singleMatch, out IEnumerable>? multipleMatches) { if (this.IsGeneric()) { singleMatch = null; multipleMatches = null; - List> exports = null; + List>? exports = null; var genericParameters = (definition.Metadata.Count > 0) ? definition.Metadata.GetValue>(CompositionConstants.GenericParametersMetadataName) : null; // if and only if generic parameters have been supplied can we attempt to "close" the generic if (genericParameters != null) { - Type[] genericTypeParameters = null; // we only understand types - if (TryGetGenericTypeParameters(genericParameters, out genericTypeParameters)) + if (TryGetGenericTypeParameters(genericParameters, out Type?[]? genericTypeParameters)) { - HashSet candidates = null; - ComposablePartDefinition candidatePart = null; - ComposablePartDefinition previousPart = null; + HashSet? candidates = null; + ComposablePartDefinition? previousPart = null; // go through all orders of generic parameters that part exports allows - foreach (Type[] candidateParameters in GetCandidateParameters(genericTypeParameters)) + foreach (Type[] candidateParameters in GetCandidateParameters(genericTypeParameters!)) { - if (TryMakeGenericPartDefinition(candidateParameters, out candidatePart)) + if (TryMakeGenericPartDefinition(candidateParameters, out ComposablePartDefinition? candidatePart)) { bool alreadyProcessed = false; if (candidates == null) @@ -215,9 +212,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } if (!alreadyProcessed) { - Tuple candidateSingleMatch; - IEnumerable> candidateMultipleMatches; - if (candidatePart.TryGetExports(definition, out candidateSingleMatch, out candidateMultipleMatches)) + if (candidatePart.TryGetExports(definition, out Tuple? candidateSingleMatch, out IEnumerable>? candidateMultipleMatches)) { exports = exports.FastAppendToListAllowNulls(candidateSingleMatch, candidateMultipleMatches); } @@ -243,13 +238,13 @@ namespace System.ComponentModel.Composition.ReflectionModel } // Optimised for local as array case - private bool TryGetNonGenericExports(ImportDefinition definition, out Tuple singleMatch, out IEnumerable> multipleMatches) + private bool TryGetNonGenericExports(ImportDefinition definition, out Tuple? singleMatch, out IEnumerable>? multipleMatches) { singleMatch = null; multipleMatches = null; - List> multipleExports = null; - Tuple singleExport = null; + List>? multipleExports = null; + Tuple? singleExport = null; bool matchesFound = false; foreach (var export in ExportDefinitionsInternal) @@ -303,7 +298,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } - private static bool TryGetGenericTypeParameters(IEnumerable genericParameters, out Type[] genericTypeParameters) + private static bool TryGetGenericTypeParameters(IEnumerable genericParameters, [NotNullWhen(true)] out Type?[]? genericTypeParameters) { genericTypeParameters = genericParameters as Type[]; if (genericTypeParameters == null) @@ -322,7 +317,7 @@ namespace System.ComponentModel.Composition.ReflectionModel return true; } - internal bool TryMakeGenericPartDefinition(Type[] genericTypeParameters, out ComposablePartDefinition genericPartDefinition) + internal bool TryMakeGenericPartDefinition(Type[] genericTypeParameters, [NotNullWhen(true)] out ComposablePartDefinition? genericPartDefinition) { genericPartDefinition = null; @@ -340,7 +335,7 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return _creationInfo.DisplayName; } } - ICompositionElement ICompositionElement.Origin + ICompositionElement? ICompositionElement.Origin { get { return _creationInfo.Origin; } } @@ -350,7 +345,7 @@ namespace System.ComponentModel.Composition.ReflectionModel return _creationInfo.DisplayName; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (_creationInfo.IsIdentityComparison) { @@ -358,13 +353,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } else { - ReflectionComposablePartDefinition that = obj as ReflectionComposablePartDefinition; - if (that == null) - { - return false; - } - - return _creationInfo.Equals(that._creationInfo); + return obj is ReflectionComposablePartDefinition that && _creationInfo.Equals(that._creationInfo); } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs index 0b028adc92d..4548be420d3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs @@ -51,13 +51,13 @@ namespace System.ComponentModel.Composition.ReflectionModel if (member.MemberType == MemberTypes.Property) { - PropertyInfo property = member as PropertyInfo; + PropertyInfo? property = member as PropertyInfo; if (property == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - MemberInfo[] accessors = new MemberInfo[] { property.GetGetMethod(true), property.GetSetMethod(true) }; + MemberInfo[] accessors = new MemberInfo[] { property.GetGetMethod(true)!, property.GetSetMethod(true)! }; return new LazyMemberInfo(MemberTypes.Property, accessors); } else @@ -73,7 +73,7 @@ namespace System.ComponentModel.Composition.ReflectionModel throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - ReflectionWritableMember reflectionMember = lazyMember.ToReflectionMember() as ReflectionWritableMember; + ReflectionWritableMember? reflectionMember = lazyMember.ToReflectionMember() as ReflectionWritableMember; if (reflectionMember == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); @@ -89,7 +89,7 @@ namespace System.ComponentModel.Composition.ReflectionModel throw new ArgumentNullException(nameof(property)); } - return CreateReflectionProperty(property.GetGetMethod(true), property.GetSetMethod(true)); + return CreateReflectionProperty(property.GetGetMethod(true)!, property.GetSetMethod(true)!); } public static ReflectionProperty CreateReflectionProperty(MethodInfo getMethod, MethodInfo setMethod) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs index a0983210c1b..494795fb530 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs @@ -56,12 +56,12 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return ReflectionItemType.Field; } } - public override object GetValue(object instance) + public override object? GetValue(object? instance) { return UndelyingField.SafeGetValue(instance); } - public override void SetValue(object instance, object value) + public override void SetValue(object? instance, object? value) { UndelyingField.SafeSetValue(instance, value); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionImportDefinition.cs index ec92b85ef20..c4687935d75 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionImportDefinition.cs @@ -9,18 +9,18 @@ namespace System.ComponentModel.Composition.ReflectionModel { internal abstract class ReflectionImportDefinition : ContractBasedImportDefinition, ICompositionElement { - private readonly ICompositionElement _origin; + private readonly ICompositionElement? _origin; public ReflectionImportDefinition( string contractName, - string requiredTypeIdentity, - IEnumerable> requiredMetadata, + string? requiredTypeIdentity, + IEnumerable>? requiredMetadata, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy, - IDictionary metadata, - ICompositionElement origin) + IDictionary metadata, + ICompositionElement? origin) : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, metadata) { _origin = origin; @@ -31,7 +31,7 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return GetDisplayName(); } } - ICompositionElement ICompositionElement.Origin + ICompositionElement? ICompositionElement.Origin { get { return _origin; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionItem.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionItem.cs index 6de13a509dc..8a7419deada 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionItem.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionItem.cs @@ -6,7 +6,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { internal abstract class ReflectionItem { - public abstract string Name { get; } + public abstract string? Name { get; } public abstract string GetDisplayName(); public abstract Type ReturnType { get; } public abstract ReflectionItemType ItemType { get; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMember.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMember.cs index 5da9f84ac36..b74f5725661 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMember.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMember.cs @@ -16,7 +16,7 @@ namespace System.ComponentModel.Composition.ReflectionModel public Type DeclaringType { - get { return UnderlyingMember.DeclaringType; } + get { return UnderlyingMember.DeclaringType!; } } public override string Name @@ -36,6 +36,6 @@ namespace System.ComponentModel.Composition.ReflectionModel public abstract MemberInfo UnderlyingMember { get; } - public abstract object GetValue(object instance); + public abstract object? GetValue(object? instance); } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs index 620ef1019c1..9050a1490e7 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs @@ -12,10 +12,10 @@ namespace System.ComponentModel.Composition.ReflectionModel { private readonly LazyMemberInfo _member; private readonly ExportDefinition _exportDefinition; - private readonly ICompositionElement _origin; - private IDictionary _metadata; + private readonly ICompositionElement? _origin; + private IDictionary? _metadata; - public ReflectionMemberExportDefinition(LazyMemberInfo member, ExportDefinition exportDefinition, ICompositionElement origin) + public ReflectionMemberExportDefinition(LazyMemberInfo member, ExportDefinition exportDefinition, ICompositionElement? origin) { if (exportDefinition == null) { @@ -37,7 +37,7 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return _member; } } - public override IDictionary Metadata + public override IDictionary Metadata { get { @@ -54,7 +54,7 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return GetDisplayName(); } } - ICompositionElement ICompositionElement.Origin + ICompositionElement? ICompositionElement.Origin { get { return _origin; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs index 1b91f3babde..276d92d2a24 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs @@ -15,14 +15,14 @@ namespace System.ComponentModel.Composition.ReflectionModel public ReflectionMemberImportDefinition( LazyMemberInfo importingLazyMember, string contractName, - string requiredTypeIdentity, - IEnumerable> requiredMetadata, + string? requiredTypeIdentity, + IEnumerable>? requiredMetadata, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy, - IDictionary metadata, - ICompositionElement origin) + IDictionary metadata, + ICompositionElement? origin) : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, metadata, origin) { if (contractName == null) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs index 0f5824ec236..8cf26b96520 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs @@ -51,12 +51,12 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return ReflectionItemType.Method; } } - public override object GetValue(object instance) + public override object GetValue(object? instance) { return SafeCreateExportedDelegate(instance, _method); } - private static ExportedDelegate SafeCreateExportedDelegate(object instance, MethodInfo method) + private static ExportedDelegate SafeCreateExportedDelegate(object? instance, MethodInfo method) { return new ExportedDelegate(instance, method); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs index 474615bc357..3b4b6b572b4 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs @@ -19,7 +19,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { Requires.NotNull(partDefinition, nameof(partDefinition)); - ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; + ReflectionComposablePartDefinition? reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; if (reflectionPartDefinition == null) { throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType()); @@ -32,7 +32,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { Requires.NotNull(partDefinition, nameof(partDefinition)); - ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; + ReflectionComposablePartDefinition? reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; if (reflectionPartDefinition == null) { throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType()); @@ -45,7 +45,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { Requires.NotNull(exportDefinition, nameof(exportDefinition)); - ReflectionMemberExportDefinition reflectionExportDefinition = exportDefinition as ReflectionMemberExportDefinition; + ReflectionMemberExportDefinition? reflectionExportDefinition = exportDefinition as ReflectionMemberExportDefinition; if (reflectionExportDefinition == null) { throw new ArgumentException( @@ -60,7 +60,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { Requires.NotNull(importDefinition, nameof(importDefinition)); - ReflectionMemberImportDefinition reflectionMemberImportDefinition = importDefinition as ReflectionMemberImportDefinition; + ReflectionMemberImportDefinition? reflectionMemberImportDefinition = importDefinition as ReflectionMemberImportDefinition; if (reflectionMemberImportDefinition == null) { throw new ArgumentException( @@ -75,7 +75,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { Requires.NotNull(importDefinition, nameof(importDefinition)); - ReflectionParameterImportDefinition reflectionParameterImportDefinition = importDefinition as ReflectionParameterImportDefinition; + ReflectionParameterImportDefinition? reflectionParameterImportDefinition = importDefinition as ReflectionParameterImportDefinition; if (reflectionParameterImportDefinition == null) { throw new ArgumentException( @@ -91,7 +91,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { Requires.NotNull(importDefinition, nameof(importDefinition)); - ReflectionImportDefinition reflectionImportDefinition = importDefinition as ReflectionImportDefinition; + ReflectionImportDefinition? reflectionImportDefinition = importDefinition as ReflectionImportDefinition; if (reflectionImportDefinition == null) { throw new ArgumentException( @@ -113,7 +113,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { Requires.NotNull(importDefinition, nameof(importDefinition)); - IPartCreatorImportDefinition partCreatorImportDefinition = importDefinition as IPartCreatorImportDefinition; + IPartCreatorImportDefinition? partCreatorImportDefinition = importDefinition as IPartCreatorImportDefinition; if (partCreatorImportDefinition == null) { throw new ArgumentException( @@ -128,10 +128,10 @@ namespace System.ComponentModel.Composition.ReflectionModel public static ComposablePartDefinition CreatePartDefinition( Lazy partType, bool isDisposalRequired, - Lazy> imports, - Lazy> exports, - Lazy> metadata, - ICompositionElement origin) + Lazy>? imports, + Lazy>? exports, + Lazy>? metadata, + ICompositionElement? origin) { Requires.NotNull(partType, nameof(partType)); @@ -149,8 +149,8 @@ namespace System.ComponentModel.Composition.ReflectionModel public static ExportDefinition CreateExportDefinition( LazyMemberInfo exportingMember, string contractName, - Lazy> metadata, - ICompositionElement origin) + Lazy> metadata, + ICompositionElement? origin) { Requires.NotNullOrEmpty(contractName, nameof(contractName)); Requires.IsInMembertypeSet(exportingMember.MemberType, nameof(exportingMember), MemberTypes.Field | MemberTypes.Property | MemberTypes.NestedType | MemberTypes.TypeInfo | MemberTypes.Method); @@ -165,12 +165,12 @@ namespace System.ComponentModel.Composition.ReflectionModel public static ContractBasedImportDefinition CreateImportDefinition( LazyMemberInfo importingMember, string contractName, - string requiredTypeIdentity, - IEnumerable> requiredMetadata, + string? requiredTypeIdentity, + IEnumerable>? requiredMetadata, ImportCardinality cardinality, bool isRecomposable, CreationPolicy requiredCreationPolicy, - ICompositionElement origin) + ICompositionElement? origin) { return CreateImportDefinition(importingMember, contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, requiredCreationPolicy, MetadataServices.EmptyMetadata, false, origin); } @@ -179,14 +179,14 @@ namespace System.ComponentModel.Composition.ReflectionModel public static ContractBasedImportDefinition CreateImportDefinition( LazyMemberInfo importingMember, string contractName, - string requiredTypeIdentity, - IEnumerable> requiredMetadata, + string? requiredTypeIdentity, + IEnumerable>? requiredMetadata, ImportCardinality cardinality, bool isRecomposable, CreationPolicy requiredCreationPolicy, - IDictionary metadata, + IDictionary metadata, bool isExportFactory, - ICompositionElement origin) + ICompositionElement? origin) { return CreateImportDefinition( importingMember, @@ -206,15 +206,15 @@ namespace System.ComponentModel.Composition.ReflectionModel public static ContractBasedImportDefinition CreateImportDefinition( LazyMemberInfo importingMember, string contractName, - string requiredTypeIdentity, - IEnumerable> requiredMetadata, + string? requiredTypeIdentity, + IEnumerable>? requiredMetadata, ImportCardinality cardinality, bool isRecomposable, bool isPreRequisite, CreationPolicy requiredCreationPolicy, - IDictionary metadata, + IDictionary metadata, bool isExportFactory, - ICompositionElement origin) + ICompositionElement? origin) { Requires.NotNullOrEmpty(contractName, nameof(contractName)); Requires.IsInMembertypeSet(importingMember.MemberType, nameof(importingMember), MemberTypes.Property | MemberTypes.Field); @@ -254,11 +254,11 @@ namespace System.ComponentModel.Composition.ReflectionModel public static ContractBasedImportDefinition CreateImportDefinition( Lazy parameter, string contractName, - string requiredTypeIdentity, - IEnumerable> requiredMetadata, + string? requiredTypeIdentity, + IEnumerable>? requiredMetadata, ImportCardinality cardinality, CreationPolicy requiredCreationPolicy, - ICompositionElement origin) + ICompositionElement? origin) { return CreateImportDefinition(parameter, contractName, requiredTypeIdentity, requiredMetadata, cardinality, requiredCreationPolicy, MetadataServices.EmptyMetadata, false, origin); } @@ -267,13 +267,13 @@ namespace System.ComponentModel.Composition.ReflectionModel public static ContractBasedImportDefinition CreateImportDefinition( Lazy parameter, string contractName, - string requiredTypeIdentity, - IEnumerable> requiredMetadata, + string? requiredTypeIdentity, + IEnumerable>? requiredMetadata, ImportCardinality cardinality, CreationPolicy requiredCreationPolicy, - IDictionary metadata, + IDictionary metadata, bool isExportFactory, - ICompositionElement origin) + ICompositionElement? origin) { Requires.NotNull(parameter, nameof(parameter)); Requires.NotNullOrEmpty(contractName, nameof(contractName)); @@ -307,12 +307,12 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - public static bool TryMakeGenericPartDefinition(ComposablePartDefinition partDefinition, IEnumerable genericParameters, out ComposablePartDefinition specialization) + public static bool TryMakeGenericPartDefinition(ComposablePartDefinition partDefinition, IEnumerable genericParameters, [NotNullWhen(true)] out ComposablePartDefinition? specialization) { Requires.NotNull(partDefinition, nameof(partDefinition)); specialization = null; - ReflectionComposablePartDefinition reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; + ReflectionComposablePartDefinition? reflectionPartDefinition = partDefinition as ReflectionComposablePartDefinition; if (reflectionPartDefinition == null) { throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition(nameof(partDefinition), partDefinition.GetType()); @@ -325,20 +325,20 @@ namespace System.ComponentModel.Composition.ReflectionModel internal class ReflectionPartCreationInfo : IReflectionPartCreationInfo { private readonly Lazy _partType; - private readonly Lazy> _imports; - private readonly Lazy> _exports; - private readonly Lazy> _metadata; - private readonly ICompositionElement _origin; - private ConstructorInfo _constructor; + private readonly Lazy>? _imports; + private readonly Lazy>? _exports; + private readonly Lazy>? _metadata; + private readonly ICompositionElement? _origin; + private ConstructorInfo? _constructor; private readonly bool _isDisposalRequired; public ReflectionPartCreationInfo( Lazy partType, bool isDisposalRequired, - Lazy> imports, - Lazy> exports, - Lazy> metadata, - ICompositionElement origin) + Lazy>? imports, + Lazy>? exports, + Lazy>? metadata, + ICompositionElement? origin) { if (partType == null) { @@ -363,11 +363,11 @@ namespace System.ComponentModel.Composition.ReflectionModel return _partType; } - public ConstructorInfo GetConstructor() + public ConstructorInfo? GetConstructor() { if (_constructor == null) { - ConstructorInfo[] constructors = null; + ConstructorInfo[]? constructors = null; constructors = GetImports() .OfType() .Select(parameterImport => parameterImport.ImportingLazyParameter.Value.Member) @@ -403,7 +403,7 @@ namespace System.ComponentModel.Composition.ReflectionModel } } - public IDictionary GetMetadata() + public IDictionary? GetMetadata() { return (_metadata != null) ? _metadata.Value : null; } @@ -424,7 +424,7 @@ namespace System.ComponentModel.Composition.ReflectionModel foreach (ExportDefinition export in exports) { - ReflectionMemberExportDefinition reflectionExport = export as ReflectionMemberExportDefinition; + ReflectionMemberExportDefinition? reflectionExport = export as ReflectionMemberExportDefinition; if (reflectionExport == null) { throw new InvalidOperationException( @@ -450,7 +450,7 @@ namespace System.ComponentModel.Composition.ReflectionModel foreach (ImportDefinition import in imports) { - ReflectionImportDefinition reflectionImport = import as ReflectionImportDefinition; + ReflectionImportDefinition? reflectionImport = import as ReflectionImportDefinition; if (reflectionImport == null) { throw new InvalidOperationException( @@ -465,7 +465,7 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return GetPartType().GetDisplayName(); } } - public ICompositionElement Origin + public ICompositionElement? Origin { get { return _origin; } } @@ -473,15 +473,15 @@ namespace System.ComponentModel.Composition.ReflectionModel internal class LazyExportDefinition : ExportDefinition { - private readonly Lazy> _metadata; + private readonly Lazy> _metadata; - public LazyExportDefinition(string contractName, Lazy> metadata) - : base(contractName, (IDictionary)null) + public LazyExportDefinition(string contractName, Lazy> metadata) + : base(contractName, (IDictionary?)null) { _metadata = metadata; } - public override IDictionary Metadata + public override IDictionary Metadata { get { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs index 190bb7f1100..8458281d3e6 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs @@ -27,7 +27,7 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return _parameter; } } - public override string Name + public override string? Name { get { return UnderlyingParameter.Name; } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs index bd25724f6d0..2949cac892e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs @@ -17,12 +17,12 @@ namespace System.ComponentModel.Composition.ReflectionModel public ReflectionParameterImportDefinition( Lazy importingLazyParameter, string contractName, - string requiredTypeIdentity, - IEnumerable> requiredMetadata, + string? requiredTypeIdentity, + IEnumerable>? requiredMetadata, ImportCardinality cardinality, CreationPolicy requiredCreationPolicy, - IDictionary metadata, - ICompositionElement origin) + IDictionary metadata, + ICompositionElement? origin) : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, false, true, requiredCreationPolicy, metadata, origin) { if (importingLazyParameter == null) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs index 30890a1366f..4fa68c97e5e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs @@ -17,10 +17,10 @@ namespace System.ComponentModel.Composition.ReflectionModel internal class ReflectionProperty : ReflectionWritableMember { - private readonly MethodInfo _getMethod; - private readonly MethodInfo _setMethod; + private readonly MethodInfo? _getMethod; + private readonly MethodInfo? _setMethod; - public ReflectionProperty(MethodInfo getMethod, MethodInfo setMethod) + public ReflectionProperty(MethodInfo? getMethod, MethodInfo? setMethod) { if (getMethod == null && setMethod == null) { @@ -33,7 +33,7 @@ namespace System.ComponentModel.Composition.ReflectionModel public override MemberInfo UnderlyingMember { - get { return UnderlyingGetMethod ?? UnderlyingSetMethod; } + get { return UnderlyingGetMethod ?? UnderlyingSetMethod!; } } public override bool CanRead @@ -46,12 +46,12 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return UnderlyingSetMethod != null; } } - public MethodInfo UnderlyingGetMethod + public MethodInfo? UnderlyingGetMethod { get { return _getMethod; } } - public MethodInfo UnderlyingSetMethod + public MethodInfo? UnderlyingSetMethod { get { return _setMethod; } } @@ -60,7 +60,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { get { - MethodInfo method = UnderlyingGetMethod ?? UnderlyingSetMethod; + MethodInfo method = UnderlyingGetMethod ?? UnderlyingSetMethod!; string name = method.Name; @@ -84,7 +84,7 @@ namespace System.ComponentModel.Composition.ReflectionModel { get { - MethodInfo method = UnderlyingGetMethod ?? UnderlyingSetMethod; + MethodInfo method = UnderlyingGetMethod ?? UnderlyingSetMethod!; return !method.IsStatic; } @@ -99,7 +99,7 @@ namespace System.ComponentModel.Composition.ReflectionModel return UnderlyingGetMethod.ReturnType; } - ParameterInfo[] parameters = UnderlyingSetMethod.GetParameters(); + ParameterInfo[] parameters = UnderlyingSetMethod!.GetParameters(); if (parameters.Length == 0) { @@ -114,23 +114,23 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return ReflectionItemType.Property; } } - public override object GetValue(object instance) + public override object? GetValue(object? instance) { if (_getMethod == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - return UnderlyingGetMethod.SafeInvoke(instance); + return UnderlyingGetMethod!.SafeInvoke(instance); } - public override void SetValue(object instance, object value) + public override void SetValue(object? instance, object? value) { if (_setMethod == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - UnderlyingSetMethod.SafeInvoke(instance, value); + UnderlyingSetMethod!.SafeInvoke(instance, value); } } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs index 413a073ba1d..3bece6625b3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs @@ -45,7 +45,7 @@ namespace System.ComponentModel.Composition.ReflectionModel get { return ReflectionItemType.Type; } } - public override object GetValue(object instance) + public override object? GetValue(object? instance) { return instance; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionWritableMember.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionWritableMember.cs index 8d0eba47158..67e4097728e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionWritableMember.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionWritableMember.cs @@ -11,6 +11,6 @@ namespace System.ComponentModel.Composition.ReflectionModel get; } - public abstract void SetValue(object instance, object value); + public abstract void SetValue(object? instance, object? value); } } -- 2.34.1