Annotate System.ComponentModel.Composition for nullable (#1842)
authorbuyaa-n <bunamnan@microsoft.com>
Mon, 3 Feb 2020 18:11:04 +0000 (10:11 -0800)
committerGitHub <noreply@github.com>
Mon, 3 Feb 2020 18:11:04 +0000 (10:11 -0800)
* Annotating System.ComponentModel.Composition for nullable

128 files changed:
src/libraries/Common/src/System/Composition/Diagnostics/DebuggerTraceWriter.cs
src/libraries/System.ComponentModel.Composition/ref/System.ComponentModel.Composition.cs
src/libraries/System.ComponentModel.Composition/ref/System.ComponentModel.Composition.csproj
src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/AttributeServices.cs
src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs
src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs
src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/WeakReferenceCollection.cs
src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ContractServices.cs
src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs
src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionInvoke.cs
src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs
src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Requires.cs
src/libraries/System.ComponentModel.Composition/src/System.ComponentModel.Composition.csproj
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModelServices.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CatalogReflectionContextAttribute.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ChangeRejectedException.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionContractMismatchException.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionError.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionErrorDebuggerProxy.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionException.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResult.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/CompositionResultOfT.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportAttribute.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportMetadataAttribute.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateCatalog.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AggregateExportProvider.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ApplicationCatalog.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AssemblyCatalog.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicComposition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.CatalogExport.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.FactoryExport.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogChangeEventArgs.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartCatalogCollection.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionLock.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.DirectoryCatalogDebuggerProxy.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportsChangeEventArgs.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.IComposablePartCatalogTraversal.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/INotifyComposablePartCatalogChanged.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.PartManager.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.RecompositionManager.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ScopingExtensions.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/IAttributedImport.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportAttribute.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportCardinalityMismatchException.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportCardinalityMismatchExceptionDebuggerProxy.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ImportManyAttribute.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/InheritedExportAttribute.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewImplementationAttribute.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/PartMetadataAttribute.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePart.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartCatalog.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartException.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ComposablePartExceptionDebuggerProxy.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElement.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElementDebuggerProxy.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/CompositionElementExtensions.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ContractBasedImportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/Export.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ExportedDelegate.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ICompositionElement.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/ImportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/SerializableCompositionElement.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/DisposableReflectionComposablePart.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportingMember.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/IReflectionPartCreationInfo.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/LazyMemberInfo.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorExportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePart.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionImportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionItem.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMember.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionProperty.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionWritableMember.cs

index ad0652e..5584f56 100644 (file)
@@ -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
         {
index 4d71f31..1ade2b5 100644 (file)
@@ -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<T>(this System.ComponentModel.Composition.Primitives.ComposablePartDefinition part) { throw null; }
         public static string GetContractName(System.Type type) { throw null; }
-        public static TMetadataView GetMetadataView<TMetadataView>(System.Collections.Generic.IDictionary<string, object> metadata) { throw null; }
+        public static TMetadataView GetMetadataView<TMetadataView>(System.Collections.Generic.IDictionary<string, object?> 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<System.ComponentModel.Composition.CompositionError> errors) { }
-        public ChangeRejectedException(string message) { }
-        public ChangeRejectedException(string message, System.Exception innerException) { }
+        public ChangeRejectedException(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.CompositionError>? 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<System.ComponentModel.Composition.CompositionError> errors) { }
-        public CompositionException(string message) { }
-        public CompositionException(string message, System.Exception innerException) { }
+        public CompositionException(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.CompositionError>? errors) { }
+        public CompositionException(string? message) { }
+        public CompositionException(string? message, System.Exception? innerException) { }
         public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.CompositionError> Errors { get { throw null; } }
         public override string Message { get { throw null; } }
         public System.Collections.ObjectModel.ReadOnlyCollection<System.Exception> 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<T>
     {
@@ -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<System.ComponentModel.Composition.Primitives.ComposablePartCatalog> catalogs) { }
-        public AggregateCatalog(params System.ComponentModel.Composition.Primitives.ComposablePartCatalog[] catalogs) { }
+        public AggregateCatalog(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartCatalog>? catalogs) { }
+        public AggregateCatalog(params System.ComponentModel.Composition.Primitives.ComposablePartCatalog[]? catalogs) { }
         public System.Collections.Generic.ICollection<System.ComponentModel.Composition.Primitives.ComposablePartCatalog> Catalogs { get { throw null; } }
-        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
-        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
+        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changed { add { } remove { } }
+        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changing { add { } remove { } }
         protected override void Dispose(bool disposing) { }
         public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
         public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> 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<System.ComponentModel.Composition.Hosting.ExportProvider> providers) { }
-        public AggregateExportProvider(params System.ComponentModel.Composition.Hosting.ExportProvider[] providers) { }
+        public AggregateExportProvider(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Hosting.ExportProvider>? providers) { }
+        public AggregateExportProvider(params System.ComponentModel.Composition.Hosting.ExportProvider[]? providers) { }
         public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.Hosting.ExportProvider> Providers { get { throw null; } }
         public void Dispose() { }
         protected virtual void Dispose(bool disposing) { }
-        protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
+        protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> 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<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
         public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> 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<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
         public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> 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<T>(object key, bool localAtomicCompositionOnly, out T value) { throw null; }
-        public bool TryGetValue<T>(object key, out T value) { throw null; }
+        public void SetValue(object key, object? value) { }
+        public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, [System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute(false)] out T value) { throw null; }
+        public bool TryGetValue<T>(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<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
+        protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> 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<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> addedDefinitions, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> removedDefinitions, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { }
+        public ComposablePartCatalogChangeEventArgs(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> addedDefinitions, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> removedDefinitions, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { }
         public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> 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<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> 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<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
+        protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export>? 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<System.ComponentModel.Composition.Primitives.ComposablePart> partsToAdd, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePart> partsToRemove) { }
+        public CompositionBatch(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePart>? partsToAdd, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePart>? partsToRemove) { }
         public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.Primitives.ComposablePart> PartsToAdd { get { throw null; } }
         public System.Collections.ObjectModel.ReadOnlyCollection<System.ComponentModel.Composition.Primitives.ComposablePart> 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<System.ComponentModel.Composition.Hosting.ExportProvider> 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<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
+        protected override System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export>? 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<System.ComponentModel.Composition.Primitives.Export> exports) { }
         public void ReleaseExports<T>(System.Collections.Generic.IEnumerable<System.Lazy<T>> exports) { }
@@ -369,8 +371,8 @@ namespace System.ComponentModel.Composition.Hosting
         public CompositionScopeDefinition(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Hosting.CompositionScopeDefinition> children, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> publicSurface) { }
         public virtual System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Hosting.CompositionScopeDefinition> Children { get { throw null; } }
         public virtual System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> PublicSurface { get { throw null; } }
-        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
-        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
+        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changed { add { } remove { } }
+        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changing { add { } remove { } }
         protected override void Dispose(bool disposing) { }
         public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
         public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> 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<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
-        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
+        System.ComponentModel.Composition.Primitives.ICompositionElement? System.ComponentModel.Composition.Primitives.ICompositionElement.Origin { get { throw null; } }
+        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changed { add { } remove { } }
+        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changing { add { } remove { } }
         protected override void Dispose(bool disposing) { }
         public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
         public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> 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<System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs> ExportsChanged { add { } remove { } }
-        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs> ExportsChanging { add { } remove { } }
+        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs>? ExportsChanged { add { } remove { } }
+        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ExportsChangeEventArgs>? ExportsChanging { add { } remove { } }
+        [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute]
         public T GetExportedValueOrDefault<T>() { throw null; }
-        public T GetExportedValueOrDefault<T>(string contractName) { throw null; }
+        [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute]
+        public T GetExportedValueOrDefault<T>(string? contractName) { throw null; }
         public System.Collections.Generic.IEnumerable<T> GetExportedValues<T>() { throw null; }
-        public System.Collections.Generic.IEnumerable<T> GetExportedValues<T>(string contractName) { throw null; }
+        public System.Collections.Generic.IEnumerable<T> GetExportedValues<T>(string? contractName) { throw null; }
+        [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute]
         public T GetExportedValue<T>() { throw null; }
-        public T GetExportedValue<T>(string contractName) { throw null; }
+        [return: System.Diagnostics.CodeAnalysis.MaybeNullAttribute]
+        public T GetExportedValue<T>(string? contractName) { throw null; }
         public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition) { throw null; }
-        public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { throw null; }
-        public System.Collections.Generic.IEnumerable<System.Lazy<object, object>> GetExports(System.Type type, System.Type metadataViewType, string contractName) { throw null; }
-        protected abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition);
+        public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export> GetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { throw null; }
+        public System.Collections.Generic.IEnumerable<System.Lazy<object, object>> GetExports(System.Type type, System.Type? metadataViewType, string? contractName) { throw null; }
+        protected abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export>? GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition);
         public System.Collections.Generic.IEnumerable<System.Lazy<T>> GetExports<T>() { throw null; }
-        public System.Collections.Generic.IEnumerable<System.Lazy<T>> GetExports<T>(string contractName) { throw null; }
+        public System.Collections.Generic.IEnumerable<System.Lazy<T>> GetExports<T>(string? contractName) { throw null; }
         public System.Collections.Generic.IEnumerable<System.Lazy<T, TMetadataView>> GetExports<T, TMetadataView>() { throw null; }
-        public System.Collections.Generic.IEnumerable<System.Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string contractName) { throw null; }
-        public System.Lazy<T> GetExport<T>() { throw null; }
-        public System.Lazy<T> GetExport<T>(string contractName) { throw null; }
-        public System.Lazy<T, TMetadataView> GetExport<T, TMetadataView>() { throw null; }
-        public System.Lazy<T, TMetadataView> GetExport<T, TMetadataView>(string contractName) { throw null; }
+        public System.Collections.Generic.IEnumerable<System.Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string? contractName) { throw null; }
+        public System.Lazy<T>? GetExport<T>() { throw null; }
+        public System.Lazy<T>? GetExport<T>(string? contractName) { throw null; }
+        public System.Lazy<T, TMetadataView>? GetExport<T, TMetadataView>() { throw null; }
+        public System.Lazy<T, TMetadataView>? GetExport<T, TMetadataView>(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<System.ComponentModel.Composition.Primitives.Export> exports) { throw null; }
+        public bool TryGetExports(System.ComponentModel.Composition.Primitives.ImportDefinition definition, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition, out System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.Export>? exports) { throw null; }
     }
     public partial class ExportsChangeEventArgs : System.EventArgs
     {
-        public ExportsChangeEventArgs(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> addedExports, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> removedExports, System.ComponentModel.Composition.Hosting.AtomicComposition atomicComposition) { }
+        public ExportsChangeEventArgs(System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> addedExports, System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> removedExports, System.ComponentModel.Composition.Hosting.AtomicComposition? atomicComposition) { }
         public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> 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<string> ChangedContractNames { get { throw null; } }
         public System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> RemovedExports { get { throw null; } }
     }
@@ -448,8 +454,8 @@ namespace System.ComponentModel.Composition.Hosting
     {
         public FilteredCatalog(System.ComponentModel.Composition.Primitives.ComposablePartCatalog catalog, System.Func<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, bool> filter) { }
         public System.ComponentModel.Composition.Hosting.FilteredCatalog Complement { get { throw null; } }
-        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed { add { } remove { } }
-        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing { add { } remove { } }
+        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changed { add { } remove { } }
+        public event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changing { add { } remove { } }
         protected override void Dispose(bool disposing) { }
         public override System.Collections.Generic.IEnumerator<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> GetEnumerator() { throw null; }
         public override System.Collections.Generic.IEnumerable<System.Tuple<System.ComponentModel.Composition.Primitives.ComposablePartDefinition, System.ComponentModel.Composition.Primitives.ExportDefinition>> 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<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changed;
-        event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs> Changing;
+        event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changed;
+        event System.EventHandler<System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs>? Changing;
     }
     public static partial class ScopingExtensions
     {
@@ -494,7 +500,7 @@ namespace System.ComponentModel.Composition.Hosting
         public TypeCatalog(System.Collections.Generic.IEnumerable<System.Type> 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<System.ComponentModel.Composition.Primitives.ComposablePartDefinition> 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<System.ComponentModel.Composition.Primitives.ExportDefinition> ExportDefinitions { get; }
         public abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ImportDefinition> ImportDefinitions { get; }
-        public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
+        public virtual System.Collections.Generic.IDictionary<string, object?> 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<System.ComponentModel.Composition.Primitives.Export> exports);
     }
     public abstract partial class ComposablePartCatalog : System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ComposablePartDefinition>, System.Collections.IEnumerable, System.IDisposable
@@ -528,61 +534,61 @@ namespace System.ComponentModel.Composition.Primitives
         protected ComposablePartDefinition() { }
         public abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition> ExportDefinitions { get; }
         public abstract System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ImportDefinition> ImportDefinitions { get; }
-        public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
+        public virtual System.Collections.Generic.IDictionary<string, object?> 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<System.Collections.Generic.KeyValuePair<string, System.Type>> 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<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> metadata) { }
+        public ContractBasedImportDefinition(string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>>? 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<System.Collections.Generic.KeyValuePair<string, System.Type>>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object?> metadata) { }
         public override System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> Constraint { get { throw null; } }
         public virtual System.ComponentModel.Composition.CreationPolicy RequiredCreationPolicy { get { throw null; } }
         public virtual System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> 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<object> exportedValueGetter) { }
-        public Export(string contractName, System.Collections.Generic.IDictionary<string, object> metadata, System.Func<object> exportedValueGetter) { }
-        public Export(string contractName, System.Func<object> exportedValueGetter) { }
+        public Export(System.ComponentModel.Composition.Primitives.ExportDefinition definition, System.Func<object?> exportedValueGetter) { }
+        public Export(string contractName, System.Collections.Generic.IDictionary<string, object?>? metadata, System.Func<object?> exportedValueGetter) { }
+        public Export(string contractName, System.Func<object?> exportedValueGetter) { }
         public virtual System.ComponentModel.Composition.Primitives.ExportDefinition Definition { get { throw null; } }
-        public System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
-        public object Value { get { throw null; } }
-        protected virtual object GetExportedValueCore() { throw null; }
+        public System.Collections.Generic.IDictionary<string, object?> 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<string, object> metadata) { }
+        public ExportDefinition(string contractName, System.Collections.Generic.IDictionary<string, object?>? metadata) { }
         public virtual string ContractName { get { throw null; } }
-        public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get { throw null; } }
+        public virtual System.Collections.Generic.IDictionary<string, object?> 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<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> constraint, string contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { }
-        public ImportDefinition(System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> constraint, string contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.Collections.Generic.IDictionary<string, object> metadata) { }
+        public ImportDefinition(System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> constraint, string? contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) { }
+        public ImportDefinition(System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> constraint, string? contractName, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, System.Collections.Generic.IDictionary<string, object?>? metadata) { }
         public virtual System.ComponentModel.Composition.Primitives.ImportCardinality Cardinality { get { throw null; } }
         public virtual System.Linq.Expressions.Expression<System.Func<System.ComponentModel.Composition.Primitives.ExportDefinition, bool>> 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<string, object> Metadata { get { throw null; } }
+        public virtual System.Collections.Generic.IDictionary<string, object?> 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<System.Reflection.MemberInfo[]> 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<System.Collections.Generic.IDictionary<string, object>> 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<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPreRequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> 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<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> 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<System.Collections.Generic.KeyValuePair<string, System.Type>> 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<System.Reflection.ParameterInfo> parameter, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object> metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement origin) { throw null; }
-        public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy<System.Reflection.ParameterInfo> parameter, string contractName, string requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>> 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<System.Type> partType, bool isDisposalRequired, System.Lazy<System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ImportDefinition>> imports, System.Lazy<System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition>> exports, System.Lazy<System.Collections.Generic.IDictionary<string, object>> 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<System.Collections.Generic.IDictionary<string, object?>> 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<System.Collections.Generic.KeyValuePair<string, System.Type>>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, bool isPreRequisite, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object?> 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<System.Collections.Generic.KeyValuePair<string, System.Type>>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, bool isRecomposable, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object?> 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<System.Collections.Generic.KeyValuePair<string, System.Type>>? 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<System.Reflection.ParameterInfo> parameter, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>>? requiredMetadata, System.ComponentModel.Composition.Primitives.ImportCardinality cardinality, System.ComponentModel.Composition.CreationPolicy requiredCreationPolicy, System.Collections.Generic.IDictionary<string, object?> metadata, bool isExportFactory, System.ComponentModel.Composition.Primitives.ICompositionElement? origin) { throw null; }
+        public static System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition CreateImportDefinition(System.Lazy<System.Reflection.ParameterInfo> parameter, string contractName, string? requiredTypeIdentity, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Type>>? 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<System.Type> partType, bool isDisposalRequired, System.Lazy<System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ImportDefinition>>? imports, System.Lazy<System.Collections.Generic.IEnumerable<System.ComponentModel.Composition.Primitives.ExportDefinition>>? exports, System.Lazy<System.Collections.Generic.IDictionary<string, object?>>? 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<System.Type> genericParameters, out System.ComponentModel.Composition.Primitives.ComposablePartDefinition specialization) { throw null; }
+        public static bool TryMakeGenericPartDefinition(System.ComponentModel.Composition.Primitives.ComposablePartDefinition partDefinition, System.Collections.Generic.IEnumerable<System.Type> genericParameters, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.ComponentModel.Composition.Primitives.ComposablePartDefinition? specialization) { throw null; }
     }
 }
index 974e475..6a72da4 100644 (file)
@@ -1,6 +1,7 @@
 <Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <Configurations>netstandard2.0-Debug;netstandard2.0-Release</Configurations>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="System.ComponentModel.Composition.cs" />
index 8f9ec5a..a95ca29 100644 (file)
@@ -19,12 +19,12 @@ namespace Microsoft.Internal
             return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit);
         }
 
-        public static T GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider) where T : class
+        public static T? GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider) where T : class
         {
             return GetAttributes<T>(attributeProvider).FirstOrDefault();
         }
 
-        public static T GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class
+        public static T? GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class
         {
             return GetAttributes<T>(attributeProvider, inherit).FirstOrDefault();
         }
index 82dc723..f50a231 100644 (file)
@@ -39,7 +39,7 @@ namespace Microsoft.Internal.Collections
 
             Type collectionType = typeof(CollectionOfObject<>).MakeGenericType(underlyingItemType);
 
-            return (ICollection<object>)Activator.CreateInstance(collectionType, collectionObject);
+            return (ICollection<object>)Activator.CreateInstance(collectionType, collectionObject)!;
         }
 
         private class CollectionOfObjectList : ICollection<object>
index be8239c..71a388e 100644 (file)
@@ -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<T>(source.AsArray());
         }
 
-        public static IEnumerable<T> ConcatAllowingNull<T>(this IEnumerable<T> source, IEnumerable<T> second)
+        public static IEnumerable<T>? ConcatAllowingNull<T>(this IEnumerable<T>? source, IEnumerable<T>? second)
         {
             if (second == null || !second.FastAny())
             {
@@ -83,7 +81,7 @@ namespace Microsoft.Internal.Collections
             return source.Concat(second);
         }
 
-        public static ICollection<T> ConcatAllowingNull<T>(this ICollection<T> source, ICollection<T> second)
+        public static ICollection<T>? ConcatAllowingNull<T>(this ICollection<T>? source, ICollection<T>? second)
         {
             if (second == null || (second.Count == 0))
             {
@@ -101,7 +99,7 @@ namespace Microsoft.Internal.Collections
             return result;
         }
 
-        public static List<T> FastAppendToListAllowNulls<T>(this List<T> source, IEnumerable<T> second)
+        public static List<T>? FastAppendToListAllowNulls<T>(this List<T>? source, IEnumerable<T>? second)
         {
             if (second == null)
             {
@@ -115,8 +113,7 @@ namespace Microsoft.Internal.Collections
             }
 
             // if the second is List<T>, and contains very few elements there's no need for AddRange
-            List<T> secondAsList = second as List<T>;
-            if (secondAsList != null)
+            if (second is List<T> secondAsList)
             {
                 if (secondAsList.Count == 0)
                 {
@@ -135,7 +132,7 @@ namespace Microsoft.Internal.Collections
 
         }
 
-        private static List<T> FastAppendToListAllowNulls<T>(this List<T> source, T value)
+        private static List<T> FastAppendToListAllowNulls<T>(this List<T>? source, T value)
         {
             if (source == null)
             {
@@ -146,9 +143,9 @@ namespace Microsoft.Internal.Collections
             return source;
         }
 
-        public static List<T> FastAppendToListAllowNulls<T>(
-                        this List<T> source, T value,
-                        IEnumerable<T> second)
+        public static List<T>? FastAppendToListAllowNulls<T>(
+                        this List<T>? source, T value,
+                        IEnumerable<T>? second)
         {
             if (second == null)
             {
@@ -177,8 +174,7 @@ namespace Microsoft.Internal.Collections
             }
 
             // Cast to ICollection instead of ICollection<T> 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<T> 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<T>(this IEnumerable<T> 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<T> AsList<T>(this IEnumerable<T> enumerable)
         {
-            List<T> list = enumerable as List<T>;
-
-            if (list != null)
+            if (enumerable is List<T> 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;
                 }
index e335ec2..599d1cd 100644 (file)
@@ -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);
                 }
index 32e5cd7..307d792 100644 (file)
@@ -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);
index e827568..d1b6ca3 100644 (file)
@@ -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
         /// <param name="ilGenerator"></param>
         /// <param name="value"></param>
-        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<char>
                 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[<index>] = 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);
         }
     }
 }
index 45caab2..393ca2a 100644 (file)
@@ -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);
         }
index 74a01cb..a0b896b 100644 (file)
@@ -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<MethodInfo> 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<FieldInfo> 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)
             {
index 010856a..aab09fa 100644 (file)
@@ -22,7 +22,7 @@ namespace Microsoft.Internal
         }
 
         [DebuggerStepThrough]
-        public static void NullOrNotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> values, string parameterName)
+        public static void NullOrNotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>>? values, string parameterName)
             where TKey : class
             where TValue : class
         {
@@ -30,14 +30,14 @@ namespace Microsoft.Internal
         }
 
         [DebuggerStepThrough]
-        public static void NullOrNotNullElements<T>(IEnumerable<T> values, string parameterName)
+        public static void NullOrNotNullElements<T>(IEnumerable<T>? values, string parameterName)
             where T : class
         {
             NotNullElements(values, parameterName);
         }
 
         [DebuggerStepThrough]
-        private static void NotNullElements<T>(IEnumerable<T> values, string parameterName)
+        private static void NotNullElements<T>(IEnumerable<T>? values, string parameterName)
             where T : class
         {
             if (values != null)
@@ -53,14 +53,14 @@ namespace Microsoft.Internal
         }
 
         [DebuggerStepThrough]
-        public static void NullOrNotNullElements<T>(T[] values, string parameterName)
+        public static void NullOrNotNullElements<T>(T[]? values, string parameterName)
             where T : class
         {
             NotNullElements(values, parameterName);
         }
 
         [DebuggerStepThrough]
-        private static void NotNullElements<T>(T[] values, string parameterName)
+        private static void NotNullElements<T>(T[]? values, string parameterName)
             where T : class
         {
             if (values != null)
@@ -76,7 +76,7 @@ namespace Microsoft.Internal
         }
 
         [DebuggerStepThrough]
-        private static void NotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> values, string parameterName)
+        private static void NotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>>? values, string parameterName)
             where TKey : class
             where TValue : class
         {
index f7067b4..99aae7a 100644 (file)
@@ -7,6 +7,8 @@
     <NoWarn>$(NoWarn);CS1573</NoWarn>
     <GeneratePlatformNotSupportedAssemblyMessage Condition="'$(TargetsNetStandard)' == 'true'">SR.PlatformNotSupported_ComponentModel_Composition</GeneratePlatformNotSupportedAssemblyMessage>
     <Configurations>$(NetCoreAppCurrent)-Debug;$(NetCoreAppCurrent)-Release;netcoreapp2.0-Debug;netcoreapp2.0-Release;netstandard2.0-Debug;netstandard2.0-Release</Configurations>
+    <Nullable>enable</Nullable>
+    <NoWarn Condition="'$(TargetsNetCoreApp)' != 'true' or '$(TargetFramework)' == 'netcoreapp2.0'">$(NoWarn);nullable</NoWarn>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="TypeForwards.cs" />
index 5dd1e60..cc83ca4 100644 (file)
@@ -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<string, object> _metadata;
+        private IDictionary<string, object?>? _metadata;
 
-        public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo, MemberInfo member, ExportAttribute exportAttribute, Type typeIdentityType, string contractName)
-            : base(contractName, (IDictionary<string, object>)null)
+        public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo, MemberInfo member, ExportAttribute exportAttribute, Type? typeIdentityType, string contractName)
+            : base(contractName, (IDictionary<string, object?>?)null)
         {
             if (partCreationInfo == null)
             {
@@ -43,14 +43,13 @@ namespace System.ComponentModel.Composition.AttributedModel
             _typeIdentityType = typeIdentityType;
         }
 
-        public override IDictionary<string, object> Metadata
+        public override IDictionary<string, object?> Metadata
         {
             get
             {
                 if (_metadata == null)
                 {
-                    IDictionary<string, object> metadata;
-                    _member.TryExportMetadataForMember(out metadata);
+                    _member.TryExportMetadataForMember(out IDictionary<string, object?> metadata);
 
                     string typeIdentity = _exportAttribute.IsContractNameSameAsTypeIdentity() ?
                         ContractName :
index d9271be..128550a 100644 (file)
@@ -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);
         }
index f3686fc..5ad1a4e 100644 (file)
@@ -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<ExportDefinition> _exports;
-        private IEnumerable<ImportDefinition> _imports;
-        private HashSet<string> _contractNamesOnNonInterfaces;
-
-        public AttributedPartCreationInfo(Type type, PartCreationPolicyAttribute partCreationPolicy, bool ignoreConstructorImports, ICompositionElement origin)
+        private readonly ICompositionElement? _origin;
+        private PartCreationPolicyAttribute? _partCreationPolicy = null;
+        private ConstructorInfo? _constructor;
+        private IEnumerable<ExportDefinition>? _exports;
+        private IEnumerable<ImportDefinition>? _imports;
+        private HashSet<string>? _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<Type>(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<string, object> GetMetadata()
+        public IDictionary<string, object?> GetMetadata()
         {
             return _type.GetPartMetadataForType(CreationPolicy);
         }
@@ -65,13 +65,13 @@ namespace System.ComponentModel.Composition.AttributedModel
         public IEnumerable<ExportDefinition> GetExports()
         {
             DiscoverExportsAndImports();
-            return _exports;
+            return _exports!;
         }
 
         public IEnumerable<ImportDefinition> 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.
index 31a6dd0..c218156 100644 (file)
@@ -18,7 +18,7 @@ namespace System.ComponentModel.Composition
     public static class AttributedModelServices
     {
         [SuppressMessage("Microsoft.Design", "CA1004")]
-        public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object> metadata)
+        public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object?> 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<string, object> metadata = new Dictionary<string, object>();
+            IDictionary<string, object?> metadata = new Dictionary<string, object?>();
             metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, typeIdentity);
 
             return batch.AddExport(new Export(contractName, metadata, () => exportedValue));
index dbc9b3e..7328e03 100644 (file)
@@ -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)
             {
index df8056e..4c4a416 100644 (file)
@@ -17,23 +17,23 @@ namespace System.ComponentModel.Composition
         ///     Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
         /// </summary>
         public ChangeRejectedException()
-            : this((string)null, (Exception)null)
+            : this((string?)null, (Exception?)null)
         {
         }
 
         /// <summary>
         ///     Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
         /// </summary>
-        public ChangeRejectedException(string message)
-            : this(message, (Exception)null)
+        public ChangeRejectedException(string? message)
+            : this(message, (Exception?)null)
         {
         }
 
         /// <summary>
         ///     Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
         /// </summary>
-        public ChangeRejectedException(string message, Exception innerException)
-            : base(message, innerException, (IEnumerable<CompositionError>)null)
+        public ChangeRejectedException(string? message, Exception? innerException)
+            : base(message, innerException, (IEnumerable<CompositionError>?)null)
         {
         }
 
@@ -41,8 +41,8 @@ namespace System.ComponentModel.Composition
         ///     Initializes a new instance of the <see cref="ChangeRejectedException"/> class.
         /// </summary>
         /// <param name="errors">List of errors that occured while applying the changes.</param>
-        public ChangeRejectedException(IEnumerable<CompositionError> errors)
-            : base((string)null, (Exception)null, errors)
+        public ChangeRejectedException(IEnumerable<CompositionError>? errors)
+            : base((string?)null, (Exception?)null, errors)
         {
         }
 
index ff8aa11..14bf9d4 100644 (file)
@@ -18,7 +18,7 @@ namespace System.ComponentModel.Composition
         ///     Initializes a new instance of the <see cref="CompositionContractMismatchException"/> class.
         /// </summary>
         public CompositionContractMismatchException()
-            : this((string)null, (Exception)null)
+            : this((string?)null, (Exception?)null)
         {
         }
 
@@ -31,8 +31,8 @@ namespace System.ComponentModel.Composition
         ///     <see cref="CompositionContractMismatchException"/>; or <see langword="null"/> to set
         ///     the <see cref="Exception.Message"/> property to its default value.
         /// </param>
-        public CompositionContractMismatchException(string message)
-            : this(message, (Exception)null)
+        public CompositionContractMismatchException(string? message)
+            : this(message, (Exception?)null)
         {
         }
 
@@ -51,7 +51,7 @@ namespace System.ComponentModel.Composition
         ///     <see cref="CompositionContractMismatchException"/>; or <see langword="null"/> to set
         ///     the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
         /// </param>
-        public CompositionContractMismatchException(string message, Exception innerException)
+        public CompositionContractMismatchException(string? message, Exception? innerException)
             : base(message, innerException)
         {
         }
index 5188718..051b491 100644 (file)
@@ -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;
 
         /// <summary>
         ///     Initializes a new instance of the <see cref="CompositionError"/> class
@@ -29,8 +29,8 @@ namespace System.ComponentModel.Composition
         ///     <see cref="CompositionError"/>; or <see langword="null"/> to set the
         ///     <see cref="Description"/> property to an empty string ("").
         /// </param>
-        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
         ///     <see cref="CompositionError"/>; or <see langword="null"/> to set the
         ///     <see cref="Description"/> property to an empty string ("").
         /// </param>
-        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
         ///     <see cref="CompositionError"/>; or <see langword="null"/> to set
         ///     the <see cref="CompositionError.Exception"/> property to <see langword="null"/>.
         /// </param>
-        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
         ///     <see cref="CompositionError"/>; or <see langword="null"/> to set
         ///     the <see cref="CompositionError.Exception"/> property to <see langword="null"/>.
         /// </param>
-        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 <see cref="ICompositionElement"/> that is the cause of the
         ///     <see cref="CompositionError"/>. The default is <see langword="null"/>.
         /// </value>
-        public ICompositionElement Element
+        public ICompositionElement? Element
         {
             get { return _element; }
         }
@@ -140,7 +140,7 @@ namespace System.ComponentModel.Composition
         ///     The <see cref="Exception"/> that is the underlying cause of the
         ///     <see cref="CompositionError"/>. The default is <see langword="null"/>.
         /// </value>
-        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);
         }
index b88721d..66ff16f 100644 (file)
@@ -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; }
         }
index aef115d..e5341dd 100644 (file)
@@ -28,7 +28,7 @@ namespace System.ComponentModel.Composition
         ///     Initializes a new instance of the <see cref="CompositionException"/> class.
         /// </summary>
         public CompositionException()
-                : this((string)null, (Exception)null, (IEnumerable<CompositionError>)null)
+                : this((string?)null, (Exception?)null, (IEnumerable<CompositionError>?)null)
         {
         }
 
@@ -41,8 +41,8 @@ namespace System.ComponentModel.Composition
         ///     <see cref="CompositionException"/>; or <see langword="null"/> to set
         ///     the <see cref="Exception.Message"/> property to its default value.
         /// </param>
-        public CompositionException(string message)
-            : this(message, (Exception)null, (IEnumerable<CompositionError>)null)
+        public CompositionException(string? message)
+            : this(message, (Exception?)null, (IEnumerable<CompositionError>?)null)
         {
         }
 
@@ -61,8 +61,8 @@ namespace System.ComponentModel.Composition
         ///     <see cref="ComposablePartException"/>; or <see langword="null"/> to set
         ///     the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
         /// </param>
-        public CompositionException(string message, Exception innerException)
-            : this(message, innerException, (IEnumerable<CompositionError>)null)
+        public CompositionException(string? message, Exception? innerException)
+            : this(message, innerException, (IEnumerable<CompositionError>?)null)
         {
         }
 
@@ -84,12 +84,12 @@ namespace System.ComponentModel.Composition
         /// <exception cref="ArgumentException">
         ///     <paramref name="errors"/> contains an element that is <see langword="null"/>.
         /// </exception>
-        public CompositionException(IEnumerable<CompositionError> errors)
-            : this((string)null, (Exception)null, errors)
+        public CompositionException(IEnumerable<CompositionError>? errors)
+            : this((string?)null, (Exception?)null, errors)
         {
         }
 
-        internal CompositionException(string message, Exception innerException, IEnumerable<CompositionError> errors)
+        internal CompositionException(string? message, Exception? innerException, IEnumerable<CompositionError>? 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);
             }
index 7f06572..4b4859f 100644 (file)
@@ -12,14 +12,14 @@ namespace System.ComponentModel.Composition
     internal struct CompositionResult
     {
         public static readonly CompositionResult SucceededResult;
-        private readonly IEnumerable<CompositionError> _errors;
+        private readonly IEnumerable<CompositionError>? _errors;
 
         public CompositionResult(params CompositionError[] errors)
             : this((IEnumerable<CompositionError>)errors)
         {
         }
 
-        public CompositionResult(IEnumerable<CompositionError> errors)
+        public CompositionResult(IEnumerable<CompositionError>? errors)
         {
             _errors = errors;
         }
@@ -52,7 +52,7 @@ namespace System.ComponentModel.Composition
             return MergeErrors(new CompositionError[] { error });
         }
 
-        public CompositionResult MergeErrors(IEnumerable<CompositionError> errors)
+        public CompositionResult MergeErrors(IEnumerable<CompositionError>? 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)
             {
index 7a9ece6..12c1339 100644 (file)
@@ -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<T>
     {
-        private readonly IEnumerable<CompositionError> _errors;
-        private readonly T _value;
+        private readonly IEnumerable<CompositionError>? _errors;
+        [AllowNull] private readonly T _value;
 
         public CompositionResult(T value)
             : this(value, null)
@@ -23,12 +24,12 @@ namespace System.ComponentModel.Composition
         {
         }
 
-        public CompositionResult(IEnumerable<CompositionError> errors)
+        public CompositionResult(IEnumerable<CompositionError>? errors)
             : this(default, errors)
         {
         }
 
-        internal CompositionResult(T value, IEnumerable<CompositionError> errors)
+        internal CompositionResult([AllowNull] T value, IEnumerable<CompositionError>? errors)
         {
             _errors = errors;
             _value = value;
index 3ee2140..84f0b97 100644 (file)
@@ -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<string, object>).GetMethod("ContainsKey");
-        private static readonly MethodInfo _metadataItemMethod = typeof(IDictionary<string, object>).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<Func<ExportDefinition, bool>> CreateConstraint(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> 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<string, object>).GetMethod("ContainsKey")!;
+        private static readonly MethodInfo _metadataItemMethod = typeof(IDictionary<string, object>).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<Func<ExportDefinition, bool>> CreateConstraint(string contractName, string? requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> 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<KeyValuePair<string, Type>> requiredMetadata, ParameterExpression parameter)
+        private static Expression? CreateMetadataConstraintBody(IEnumerable<KeyValuePair<string, Type>> 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<string, Type> requiredMetadataItem in requiredMetadata)
             {
                 // export.Metadata.ContainsKey(<metadataItem>)
index da73857..97bf2e6 100644 (file)
@@ -27,7 +27,7 @@ namespace System.ComponentModel.Composition
         private const char GenericFormatClosingBracket = '}';
 
         [ThreadStatic]
-        private static Dictionary<Type, string> typeIdentityCache;
+        private static Dictionary<Type, string>? typeIdentityCache;
 
         private static Dictionary<Type, string> 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 <TypeName>*
             //
-            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 <TypeName>&
             //
-            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)
index 315f052..970bb55 100644 (file)
@@ -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)
index 6ffafd2..ef5cc34 100644 (file)
@@ -30,7 +30,7 @@ namespace System.ComponentModel.Composition
         ///     </para>
         /// </remarks>
         public ExportAttribute()
-            : this((string)null, (Type)null)
+            : this((string?)null, (Type?)null)
         {
         }
 
@@ -60,8 +60,8 @@ namespace System.ComponentModel.Composition
         ///         using <see cref="StringComparer.Ordinal"/>.
         ///     </para>
         /// </remarks>
-        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 <see cref="StringComparer.Ordinal"/>.
         ///     </para>
         /// </remarks>
-        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 <see cref="StringComparer.Ordinal"/>.
         ///     </para>
         /// </remarks>
-        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 <see cref="string"/> containing the contract name to export the type or member
         ///      marked with this attribute, under. The default value is an empty string ("").
         /// </value>
-        public string ContractName { get; private set; }
+        public string? ContractName { get; private set; }
 
         /// <summary>
         ///     Get the contract type that is exported by the member that this attribute is attached to.
@@ -138,6 +138,6 @@ namespace System.ComponentModel.Composition
         ///     <see langword="null"/> which means that the type will be obtained by looking at the type on
         ///     the member that this export is attached to.
         /// </value>
-        public Type ContractType { get; private set; }
+        public Type? ContractType { get; private set; }
     }
 }
index 6cb62ab..e029f4d 100644 (file)
@@ -25,7 +25,7 @@ namespace System.ComponentModel.Composition
         ///     An <see cref="object"/> containing the metadata value. This can be
         ///     <see langword="null"/>.
         /// </param>
-        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
         /// <value>
         ///     An <see cref="object"/> containing the metadata value.
         /// </value>
-        public object Value
+        public object? Value
         {
             get;
             private set;
index 254eadc..f016f95 100644 (file)
@@ -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<string, object>);
         internal static readonly Type DefaultExportedValueType = typeof(object);
@@ -51,9 +51,9 @@ namespace System.ComponentModel.Composition
                                                     Array.Empty<ParameterModifier>()) != null;
         }
 
-        internal static Func<Export, object> CreateStronglyTypedLazyFactory(Type exportType, Type metadataViewType)
+        internal static Func<Export, object> 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<Export, object>)Delegate.CreateDelegate(typeof(Func<Export, object>), genericMethod);
         }
 
-        internal static Func<Export, Lazy<object, object>> CreateSemiStronglyTypedLazyFactory(Type exportType, Type metadataViewType)
+        internal static Func<Export, Lazy<object, object>> 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<T, M> CreateStronglyTypedLazyOfTM<T, M>(Export export)
         {
-            IDisposable disposable = export as IDisposable;
-            if (disposable != null)
+            if (export is IDisposable disposable)
             {
                 return new DisposableLazy<T, M>(
                     () => ExportServices.GetCastedExportedValue<T>(export),
@@ -107,8 +106,7 @@ namespace System.ComponentModel.Composition
         [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
         internal static Lazy<T> CreateStronglyTypedLazyOfT<T>(Export export)
         {
-            IDisposable disposable = export as IDisposable;
-            if (disposable != null)
+            if (export is IDisposable disposable)
             {
                 return new DisposableLazy<T>(
                     () => ExportServices.GetCastedExportedValue<T>(export),
@@ -118,27 +116,25 @@ namespace System.ComponentModel.Composition
             else
             {
                 return new Lazy<T>(() => ExportServices.GetCastedExportedValue<T>(export), LazyThreadSafetyMode.PublicationOnly);
-
             }
         }
 
         [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
-        internal static Lazy<object, object> CreateSemiStronglyTypedLazy<T, M>(Export export)
+        internal static Lazy<object?, object> CreateSemiStronglyTypedLazy<T, M>(Export export)
         {
-            IDisposable disposable = export as IDisposable;
-            if (disposable != null)
+            if (export is IDisposable disposable)
             {
-                return new DisposableLazy<object, object>(
+                return new DisposableLazy<object?, object>(
                     () => ExportServices.GetCastedExportedValue<T>(export),
-                    AttributedModelServices.GetMetadataView<M>(export.Metadata),
+                    AttributedModelServices.GetMetadataView<M>(export.Metadata)!,
                     disposable,
                     LazyThreadSafetyMode.PublicationOnly);
             }
             else
             {
-                return new Lazy<object, object>(
+                return new Lazy<object?, object>(
                     () => ExportServices.GetCastedExportedValue<T>(export),
-                    AttributedModelServices.GetMetadataView<M>(export.Metadata),
+                    AttributedModelServices.GetMetadataView<M>(export.Metadata)!,
                     LazyThreadSafetyMode.PublicationOnly);
             }
         }
@@ -148,11 +144,9 @@ namespace System.ComponentModel.Composition
             return CastExportedValue<T>(export.ToElement(), export.Value);
         }
 
-        internal static T CastExportedValue<T>(ICompositionElement element, object exportedValue)
+        internal static T CastExportedValue<T>(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<T>(ImportDefinition definition, IEnumerable<T> enumerable)
+        internal static ExportCardinalityCheckResult CheckCardinality<T>(ImportDefinition definition, IEnumerable<T>? enumerable)
         {
             EnumerableCardinality actualCardinality = (enumerable != null) ? enumerable.GetCardinality() : EnumerableCardinality.Zero;
 
index 03ee056..0fe4133 100644 (file)
@@ -19,14 +19,14 @@ namespace System.ComponentModel.Composition.Hosting
     /// </remarks>
     public class AggregateCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged
     {
-        private readonly ComposablePartCatalogCollection _catalogs = null;
+        private readonly ComposablePartCatalogCollection _catalogs;
         private volatile int _isDisposed = 0;
 
         /// <summary>
         ///     Initializes a new instance of the <see cref="AggregateCatalog"/> class.
         /// </summary>
         public AggregateCatalog()
-            : this((IEnumerable<ComposablePartCatalog>)null)
+            : this((IEnumerable<ComposablePartCatalog>?)null)
         {
         }
 
@@ -44,8 +44,8 @@ namespace System.ComponentModel.Composition.Hosting
         /// <exception cref="ArgumentException">
         ///     <paramref name="catalogs"/> contains an element that is <see langword="null"/>.
         /// </exception>
-        public AggregateCatalog(params ComposablePartCatalog[] catalogs)
-            : this((IEnumerable<ComposablePartCatalog>)catalogs)
+        public AggregateCatalog(params ComposablePartCatalog[]? catalogs)
+            : this((IEnumerable<ComposablePartCatalog>?)catalogs)
         {
         }
 
@@ -61,7 +61,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// <exception cref="ArgumentException">
         ///     <paramref name="catalogs"/> contains an element that is <see langword="null"/>.
         /// </exception>
-        public AggregateCatalog(IEnumerable<ComposablePartCatalog> catalogs)
+        public AggregateCatalog(IEnumerable<ComposablePartCatalog>? catalogs)
         {
             Requires.NullOrNotNullElements(catalogs, nameof(catalogs));
 
@@ -71,7 +71,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// <summary>
         /// Notify when the contents of the Catalog has changed.
         /// </summary>
-        public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed
+        public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed
         {
             add
             {
@@ -86,7 +86,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// <summary>
         /// Notify when the contents of the Catalog has changing.
         /// </summary>
-        public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing
+        public event EventHandler<ComposablePartCatalogChangeEventArgs>? 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<Tuple<ComposablePartDefinition, ExportDefinition>> result = null;
-            List<Tuple<ComposablePartDefinition, ExportDefinition>> aggregateResult = null;
+            IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? result = null;
+            List<Tuple<ComposablePartDefinition, ExportDefinition>>? aggregateResult = null;
 
             foreach (var catalog in _catalogs)
             {
index 0e70ea9..84a4e48 100644 (file)
@@ -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.
         ///     </para>
         /// </remarks>
-        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.
         ///     </para>
         /// </remarks>
-        public AggregateExportProvider(IEnumerable<ExportProvider> providers)
+        public AggregateExportProvider(IEnumerable<ExportProvider>? providers)
             : this((providers != null) ? providers.AsArray() : null)
         {
         }
@@ -153,7 +153,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
         /// </note>
         /// </remarks>
-        protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+        protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition)
         {
             ThrowIfDisposed();
 
@@ -171,14 +171,14 @@ namespace System.ComponentModel.Composition.Hosting
             }
             else
             {
-                IEnumerable<Export> allExports = null;
+                IEnumerable<Export>? 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<Export> exports;
-                    bool cardinalityCheckResult = provider.TryGetExports(definition, atomicComposition, out exports);
+                    bool cardinalityCheckResult = provider.TryGetExports(definition, atomicComposition, out IEnumerable<Export>? 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);
         }
index ed3e532..8f583ba 100644 (file)
@@ -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 <see langword="null"/>.
         /// </value>
         [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
-        ICompositionElement ICompositionElement.Origin
+        ICompositionElement? ICompositionElement.Origin
         {
             get { return null; }
         }
index c340378..4a9fe60 100644 (file)
@@ -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);
 
         /// <summary>
         ///     Initializes a new instance of the <see cref="AssemblyCatalog"/> class
@@ -492,7 +492,7 @@ namespace System.ComponentModel.Composition.Hosting
         ///     This property always returns <see langword="null"/>.
         /// </value>
         [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
-        ICompositionElement ICompositionElement.Origin
+        ICompositionElement? ICompositionElement.Origin
         {
             get { return null; }
         }
index 86cf668..b7e606c 100644 (file)
@@ -35,11 +35,11 @@ namespace System.ComponentModel.Composition.Hosting
     /// </summary>
     public class AtomicComposition : IDisposable
     {
-        private readonly AtomicComposition _outerAtomicComposition;
-        private KeyValuePair<object, object>[] _values;
+        private readonly AtomicComposition? _outerAtomicComposition;
+        private KeyValuePair<object, object?>[]? _values;
         private int _valueCount = 0;
-        private List<Action> _completeActionList;
-        private List<Action> _revertActionList;
+        private List<Action>? _completeActionList;
+        private List<Action>? _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<T>(object key, out T value)
+        public bool TryGetValue<T>(object key, [MaybeNullWhen(false)] out T value)
         {
             return TryGetValue(key, false, out value);
         }
 
         [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters")]
-        public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, out T value)
+        public bool TryGetValue<T>(object key, bool localAtomicCompositionOnly, [MaybeNullWhen(false)] out T value)
         {
             ThrowIfDisposed();
             ThrowIfCompleted();
@@ -156,7 +156,7 @@ namespace System.ComponentModel.Composition.Hosting
             {
                 if (_revertActionList != null)
                 {
-                    List<Exception> exceptions = null;
+                    List<Exception>? 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<Exception> exceptions = null;
+                List<Exception>? 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<T>(object key, bool localAtomicCompositionOnly, out T value)
+        private bool TryGetValueInternal<T>(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<T>(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<object, object>(key, value);
+                    _values[index] = new KeyValuePair<object, object?>(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<object, object>[_valueCount == 0 ? 5 : _valueCount * 2];
+                var newQueries = new KeyValuePair<object, object?>[_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<object, object>(key, value);
+            _values[_valueCount] = new KeyValuePair<object, object?>(key, value);
             _valueCount++;
             return;
         }
index b22c8c2..d5b522c 100644 (file)
@@ -7,7 +7,7 @@ namespace System.ComponentModel.Composition.Hosting
 {
     internal static class AtomicCompositionExtensions
     {
-        internal static T GetValueAllowNull<T>(this AtomicComposition atomicComposition, T defaultResultAndKey) where T : class
+        internal static T GetValueAllowNull<T>(this AtomicComposition? atomicComposition, T defaultResultAndKey) where T : class
         {
             if (defaultResultAndKey == null)
             {
@@ -17,7 +17,7 @@ namespace System.ComponentModel.Composition.Hosting
             return GetValueAllowNull<T>(atomicComposition, defaultResultAndKey, defaultResultAndKey);
         }
 
-        internal static T GetValueAllowNull<T>(this AtomicComposition atomicComposition, object key, T defaultResult)
+        internal static T GetValueAllowNull<T>(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)
             {
index fda7e10..3fe8913 100644 (file)
@@ -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)
                     {
index 83777e7..61f506e 100644 (file)
@@ -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();
                     }
index 78f294f..47361be 100644 (file)
@@ -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)
                     {
index e103528..848c5c2 100644 (file)
@@ -29,11 +29,11 @@ namespace System.ComponentModel.Composition.Hosting
                 _catalogExportProvider = catalogExportProvider;
             }
 
-            protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+            protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition)
             {
                 List<Export> exports = new List<Export>();
 
-                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)
                 {
index c00f0b0..9c06b88 100644 (file)
@@ -32,7 +32,7 @@ namespace System.ComponentModel.Composition.Hosting
                 _outerExportProvider = outerExportProvider;
             }
 
-            protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+            protected override IEnumerable<Export> 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<ComposablePartDefinition, CatalogPart> _activatedParts = new Dictionary<ComposablePartDefinition, CatalogPart>();
         private readonly HashSet<ComposablePartDefinition> _rejectedParts = new HashSet<ComposablePartDefinition>();
-        private ConditionalWeakTable<object, List<ComposablePart>> _gcRoots;
+        private ConditionalWeakTable<object, List<ComposablePart>>? _gcRoots;
         private readonly HashSet<IDisposable> _partsToDispose = new HashSet<IDisposable>();
         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;
 
         /// <summary>
         /// Initializes a new instance of the <see cref="CatalogExportProvider"/> 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
         ///     <see cref="CatalogExportProvider"/>.
         /// </remarks>
         [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<IDisposable> partsToDispose = null;
-                    ImportEngine importEngine = null;
-                    ExportProvider sourceProvider = null;
-                    AggregateExportProvider aggregateExportProvider = null;
+                    INotifyComposablePartCatalogChanged? catalogToUnsubscribeFrom = null;
+                    HashSet<IDisposable>? 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 <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
         /// </note>
         /// </remarks>
-        protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+        protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition)
         {
             ThrowIfDisposed();
             EnsureRunning();
@@ -317,12 +316,11 @@ namespace System.ComponentModel.Composition.Hosting
                 throw new Exception(SR.Diagnostic_InternalExceptionMessage);
             }
 
-            IEnumerable<Export> exports;
-            _innerExportProvider.TryGetExports(definition, atomicComposition, out exports);
-            return exports;
+            _innerExportProvider.TryGetExports(definition, atomicComposition, out IEnumerable<Export>? exports);
+            return exports!;
         }
 
-        private IEnumerable<Export> InternalGetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+        private IEnumerable<Export> 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<ComposablePart> partList;
+                List<ComposablePart>? partList;
 
-                ConditionalWeakTable<object, List<ComposablePart>> gcRoots = _gcRoots;
+                ConditionalWeakTable<object, List<ComposablePart>>? gcRoots = _gcRoots;
                 if (gcRoots == null)
                 {
                     gcRoots = new ConditionalWeakTable<object, List<ComposablePart>>();
@@ -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<ExportDefinition> changedExports, AtomicComposition atomicComposition)
+        private void UpdateRejections(IEnumerable<ExportDefinition> changedExports, AtomicComposition? atomicComposition)
         {
             using (var localAtomicComposition = new AtomicComposition(atomicComposition))
             {
@@ -934,7 +929,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// <typeparam name="T"></typeparam>
         /// <param name="currentValue"></param>
         [DebuggerStepThrough]
-        private void EnsureCanSet<T>(T currentValue)
+        private void EnsureCanSet<T>(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<ComposablePartDefinition> 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<ComposablePartDefinition> _parts;
-            public PartInHashSetQueryStateNode(HashSet<ComposablePartDefinition> parts, PartQueryStateNode previousNode, AtomicCompositionQueryState state) :
+            public PartInHashSetQueryStateNode(HashSet<ComposablePartDefinition> parts, PartQueryStateNode? previousNode, AtomicCompositionQueryState state) :
                 base(previousNode, state)
             {
                 _parts = parts;
index b92e488..06b46c7 100644 (file)
@@ -40,7 +40,7 @@ namespace System.ComponentModel.Composition.Hosting
         ///     <paramref name="addedDefinitions"/> or <paramref name="removedDefinitions"/> is <see langword="null"/>.
         /// </exception>
         public ComposablePartCatalogChangeEventArgs(IEnumerable<ComposablePartDefinition> addedDefinitions,
-            IEnumerable<ComposablePartDefinition> removedDefinitions, AtomicComposition atomicComposition)
+            IEnumerable<ComposablePartDefinition> 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.
         /// </value>
-        public AtomicComposition AtomicComposition { get; private set; }
+        public AtomicComposition? AtomicComposition { get; private set; }
     }
 }
index c623733..ff38779 100644 (file)
@@ -21,17 +21,17 @@ namespace System.ComponentModel.Composition.Hosting
     internal class ComposablePartCatalogCollection : ICollection<ComposablePartCatalog>, INotifyComposablePartCatalogChanged, IDisposable
     {
         private readonly Lock _lock = new Lock();
-        private readonly Action<ComposablePartCatalogChangeEventArgs> _onChanged;
-        private readonly Action<ComposablePartCatalogChangeEventArgs> _onChanging;
+        private readonly Action<ComposablePartCatalogChangeEventArgs>? _onChanged;
+        private readonly Action<ComposablePartCatalogChangeEventArgs>? _onChanging;
         private List<ComposablePartCatalog> _catalogs = new List<ComposablePartCatalog>();
         private volatile bool _isCopyNeeded = false;
         private volatile bool _isDisposed = false;
         private bool _hasChanged = false;
 
         public ComposablePartCatalogCollection(
-            IEnumerable<ComposablePartCatalog> catalogs,
-            Action<ComposablePartCatalogChangeEventArgs> onChanged,
-            Action<ComposablePartCatalogChangeEventArgs> onChanging)
+            IEnumerable<ComposablePartCatalog>? catalogs,
+            Action<ComposablePartCatalogChangeEventArgs>? onChanged,
+            Action<ComposablePartCatalogChangeEventArgs>? onChanging)
         {
             catalogs = catalogs ?? Enumerable.Empty<ComposablePartCatalog>();
             _catalogs = new List<ComposablePartCatalog>(catalogs);
@@ -76,19 +76,19 @@ namespace System.ComponentModel.Composition.Hosting
         /// <summary>
         /// Notify when the contents of the Catalog has changed.
         /// </summary>
-        public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
+        public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;
 
         /// <summary>
         /// Notify when the contents of the Catalog has changing.
         /// </summary>
-        public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
+        public event EventHandler<ComposablePartCatalogChangeEventArgs>? 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<ComposablePartCatalog> catalogs = null;
+                    IEnumerable<ComposablePartCatalog>? 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<IEnumerable<ComposablePartDefinition>> addedDefinitions,
-            Lazy<IEnumerable<ComposablePartDefinition>> removedDefinitions)
+            Lazy<IEnumerable<ComposablePartDefinition>>? addedDefinitions,
+            Lazy<IEnumerable<ComposablePartDefinition>>? removedDefinitions)
         {
             if (_onChanged == null || Changed == null)
             {
@@ -317,9 +317,9 @@ namespace System.ComponentModel.Composition.Hosting
         }
 
         private void RaiseChangingEvent(
-           Lazy<IEnumerable<ComposablePartDefinition>> addedDefinitions,
-           Lazy<IEnumerable<ComposablePartDefinition>> removedDefinitions,
-           AtomicComposition atomicComposition)
+           Lazy<IEnumerable<ComposablePartDefinition>>? addedDefinitions,
+           Lazy<IEnumerable<ComposablePartDefinition>>? 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;
index 35ddb14..537865f 100644 (file)
@@ -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<ComposablePart> _parts = new List<ComposablePart>();
         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
         ///     <see cref="ComposablePartExportProvider"/>.
         /// </remarks>
         [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 <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
         /// </note>
         /// </remarks>
-        protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+        protected override IEnumerable<Export>? 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<ComposablePart> parts = null;
+            List<ComposablePart>? 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<ComposablePart> parts = null;
+            List<ComposablePart>? 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<ComposablePart> partsToRemove = null;
+            List<ComposablePart>? 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>(T currentValue)
+        private void EnsureCanSet<T>(T? currentValue)
             where T : class
         {
             if ((_isRunning) || (currentValue != null))
index 913f10d..5c81dc0 100644 (file)
@@ -26,7 +26,7 @@ namespace System.ComponentModel.Composition.Hosting
                 _export = export;
             }
 
-            public override IDictionary<string, object> Metadata
+            public override IDictionary<string, object?> Metadata
             {
                 get { return MetadataServices.EmptyMetadata; }
             }
@@ -41,7 +41,7 @@ namespace System.ComponentModel.Composition.Hosting
                 get { return Enumerable.Empty<ImportDefinition>(); }
             }
 
-            public override object GetExportedValue(ExportDefinition definition)
+            public override object? GetExportedValue(ExportDefinition definition)
             {
                 Requires.NotNull(definition, nameof(definition));
 
index 4aeb28c..77fce3b 100644 (file)
@@ -33,7 +33,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// </summary>
         /// <param name="partsToAdd">The parts to add.</param>
         /// <param name="partsToRemove">The parts to remove.</param>
-        public CompositionBatch(IEnumerable<ComposablePart> partsToAdd, IEnumerable<ComposablePart> partsToRemove)
+        public CompositionBatch(IEnumerable<ComposablePart>? partsToAdd, IEnumerable<ComposablePart>? partsToRemove)
         {
             _partsToAdd = new List<ComposablePart>();
             if (partsToAdd != null)
index 6c17611..f6d4785 100644 (file)
@@ -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)
             {
index b37bf6b..17ac42c 100644 (file)
@@ -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<ExportProvider> _providers;
         private volatile bool _isDisposed = false;
@@ -34,7 +34,7 @@ namespace System.ComponentModel.Composition.Hosting
         ///     Initializes a new instance of the <see cref="CompositionContainer"/> class.
         /// </summary>
         public CompositionContainer()
-            : this((ComposablePartCatalog)null)
+            : this((ComposablePartCatalog?)null)
         {
         }
 
@@ -51,8 +51,8 @@ namespace System.ComponentModel.Composition.Hosting
         /// <exception cref="ArgumentException">
         ///     <paramref name="providers"/> contains an element that is <see langword="null"/>.
         /// </exception>
-        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
         /// <exception cref="ArgumentException">
         ///     <paramref name="providers"/> contains an element that is <see langword="null"/>.
         /// </exception>
-        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
         /// <exception cref="ArgumentException">
         ///     <paramref name="providers"/> contains an element that is <see langword="null"/>.
         /// </exception>
-        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
         /// <exception cref="ArgumentException">
         ///     <paramref name="providers"/> contains an element that is <see langword="null"/>.
         /// </exception>
-        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
         /// <exception cref="ArgumentException">
         ///     <paramref name="providers"/> contains an element that is <see langword="null"/>.
         /// </exception>
-        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
         /// <exception cref="ObjectDisposedException">
         ///     The <see cref="CompositionContainer"/> has been disposed of.
         /// </exception>
-        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 <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
         /// </note>
         /// </remarks>
-        protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
+        protected override IEnumerable<Export>? GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition)
         {
             ThrowIfDisposed();
 
-            IEnumerable<Export> exports = null;
+            IEnumerable<Export>? 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)
index db82fde..0bf6c62 100644 (file)
@@ -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
             {
index e4cef2e..4863183 100644 (file)
@@ -14,8 +14,8 @@ namespace System.ComponentModel.Composition.Hosting
     [DebuggerTypeProxy(typeof(CompositionScopeDefinitionDebuggerProxy))]
     public class CompositionScopeDefinition : ComposablePartCatalog, INotifyComposablePartCatalogChanged
     {
-        private ComposablePartCatalog _catalog;
-        private IEnumerable<ExportDefinition> _publicSurface = null;
+        private ComposablePartCatalog? _catalog;
+        private IEnumerable<ExportDefinition>? _publicSurface = null;
         private IEnumerable<CompositionScopeDefinition> _children = Enumerable.Empty<CompositionScopeDefinition>();
         private volatile int _isDisposed = 0;
 
@@ -57,7 +57,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// </summary>
         /// <param name="catalog">The catalog.</param>
         /// <param name="children">The children.</param>
-        private void InitializeCompositionScopeDefinition(ComposablePartCatalog catalog, IEnumerable<CompositionScopeDefinition> children, IEnumerable<ExportDefinition> publicSurface)
+        private void InitializeCompositionScopeDefinition(ComposablePartCatalog catalog, IEnumerable<CompositionScopeDefinition>? children, IEnumerable<ExportDefinition>? 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
         /// <value>The children.</value>
         public override IEnumerator<ComposablePartDefinition> 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
         /// <summary>
         /// Notify when the contents of the Catalog has changed.
         /// </summary>
-        public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
+        public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;
 
         /// <summary>
         /// Notify when the contents of the Catalog is changing.
         /// </summary>
-        public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
+        public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing;
 
         /// <summary>
         /// Raises the <see cref="Changed"/> event.
@@ -226,7 +226,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// <param name="e">The <see cref="System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs"/> instance containing the event data.</param>
         protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
         {
-            EventHandler<ComposablePartCatalogChangeEventArgs> changedEvent = Changed;
+            EventHandler<ComposablePartCatalogChangeEventArgs>? changedEvent = Changed;
             if (changedEvent != null)
             {
                 changedEvent.Invoke(this, e);
@@ -239,19 +239,19 @@ namespace System.ComponentModel.Composition.Hosting
         /// <param name="e">The <see cref="System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs"/> instance containing the event data.</param>
         protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
         {
-            EventHandler<ComposablePartCatalogChangeEventArgs> changingEvent = Changing;
+            EventHandler<ComposablePartCatalogChangeEventArgs>? 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);
         }
index 8b02b5c..08b2a7b 100644 (file)
@@ -15,8 +15,8 @@ namespace System.ComponentModel.Composition.Hosting
     /// </remarks>
     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);
         }
index 93cf9ac..8c30467 100644 (file)
@@ -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<string, object> GetPartMetadataForType(this Type type, CreationPolicy creationPolicy)
+        internal static IDictionary<string, object?> GetPartMetadataForType(this Type type, CreationPolicy creationPolicy)
         {
-            IDictionary<string, object> dictionary = new Dictionary<string, object>(StringComparers.MetadataKeyNames);
+            IDictionary<string, object?> dictionary = new Dictionary<string, object?>(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<string, object> dictionary)
+        internal static void TryExportMetadataForMember(this MemberInfo member, out IDictionary<string, object?> dictionary)
         {
-            dictionary = new Dictionary<string, object>();
+            dictionary = new Dictionary<string, object?>();
 
             foreach (var attr in member.GetAttributes<Attribute>())
             {
@@ -290,7 +290,7 @@ namespace System.ComponentModel.Composition.Hosting
                     if ((attrType != CompositionServices.ExportAttributeType) && attrType.IsAttributeDefined<MetadataAttributeAttribute>(true))
                     {
                         bool allowsMultiple = false;
-                        AttributeUsageAttribute usage = attrType.GetFirstAttribute<AttributeUsageAttribute>(true);
+                        AttributeUsageAttribute? usage = attrType.GetFirstAttribute<AttributeUsageAttribute>(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<string, object> dictionary, string name, object value, Type valueType, bool allowsMultiple)
+        private static bool TryContributeMetadataValue(this IDictionary<string, object?> 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<object> _innerList = new Collection<object>();
+            private readonly Collection<object?> _innerList = new Collection<object?>();
 
-            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<KeyValuePair<string, Type>> GetRequiredMetadata(Type metadataViewType)
+        internal static IEnumerable<KeyValuePair<string, Type>> GetRequiredMetadata(Type? metadataViewType)
         {
             if ((metadataViewType == null) ||
                 ExportServices.IsDefaultMetadataViewType(metadataViewType) ||
@@ -498,19 +497,19 @@ namespace System.ComponentModel.Composition.Hosting
             return properties.Select(property => new KeyValuePair<string, Type>(property.Name, property.PropertyType));
         }
 
-        internal static IDictionary<string, object> GetImportMetadata(ImportType importType, IAttributedImport attributedImport)
+        internal static IDictionary<string, object?> GetImportMetadata(ImportType importType, IAttributedImport attributedImport)
         {
             return GetImportMetadata(importType.ContractType, attributedImport);
         }
 
-        internal static IDictionary<string, object> GetImportMetadata(Type type, IAttributedImport attributedImport)
+        internal static IDictionary<string, object?> GetImportMetadata(Type type, IAttributedImport? attributedImport)
         {
-            Dictionary<string, object> metadata = null;
+            Dictionary<string, object?>? metadata = null;
 
             //Prior to V4.5 MEF did not support ImportMetadata
             if (type.IsGenericType)
             {
-                metadata = new Dictionary<string, object>();
+                metadata = new Dictionary<string, object?>();
 
                 if (type.ContainsGenericParameters)
                 {
@@ -528,7 +527,7 @@ namespace System.ComponentModel.Composition.Hosting
             {
                 if (metadata == null)
                 {
-                    metadata = new Dictionary<string, object>();
+                    metadata = new Dictionary<string, object?>();
                 }
                 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<TEventArgs>(EventHandler<TEventArgs> _delegate, object sender, TEventArgs e)
+        internal static CompositionResult TryFire<TEventArgs>(EventHandler<TEventArgs> _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;
             }
index ddaaee6..6432b6a 100644 (file)
@@ -33,7 +33,7 @@ namespace System.ComponentModel.Composition.Hosting
                 }
             }
 
-            public ReflectionContext ReflectionContext
+            public ReflectionContext? ReflectionContext
             {
                 get
                 {
index fd5aa01..a693744 100644 (file)
@@ -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<string, AssemblyCatalog> _assemblyCatalogs;
+        private readonly ICompositionElement? _definitionOrigin = null;
+        private ComposablePartCatalogCollection _catalogCollection = null!; // Always initialized with Initialize()
+        private Dictionary<string, AssemblyCatalog> _assemblyCatalogs = null!;
         private volatile bool _isDisposed = false;
-        private string _path;
-        private string _fullPath;
-        private string _searchPattern;
-        private ReadOnlyCollection<string> _loadedFiles;
+        private string _path = null!;
+        private string _fullPath = null!;
+        private string _searchPattern = null!;
+        private ReadOnlyCollection<string> _loadedFiles = null!;
 
-        private readonly ReflectionContext _reflectionContext = null;
+        private readonly ReflectionContext? _reflectionContext = null;
 
         /// <summary>
         ///     Creates a catalog of <see cref="ComposablePartDefinition"/>s based on all the *.dll files
@@ -434,12 +434,12 @@ namespace System.ComponentModel.Composition.Hosting
         /// <summary>
         /// Notify when the contents of the Catalog has changed.
         /// </summary>
-        public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
+        public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;
 
         /// <summary>
         /// Notify when the contents of the Catalog has changing.
         /// </summary>
-        public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
+        public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing;
 
         /// <summary>
         /// 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
         /// </param>
         protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
         {
-            EventHandler<ComposablePartCatalogChangeEventArgs> changedEvent = Changed;
+            EventHandler<ComposablePartCatalogChangeEventArgs>? changedEvent = Changed;
             if (changedEvent != null)
             {
                 changedEvent(this, e);
@@ -547,7 +547,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// </param>
         protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
         {
-            EventHandler<ComposablePartCatalogChangeEventArgs> changingEvent = Changing;
+            EventHandler<ComposablePartCatalogChangeEventArgs>? 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<string> 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<string, AssemblyCatalog>(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 <see langword="null"/>.
         /// </value>
         [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
-        ICompositionElement ICompositionElement.Origin
+        ICompositionElement? ICompositionElement.Origin
         {
             get { return null; }
         }
index 3e38009..c986f2f 100644 (file)
@@ -57,9 +57,9 @@ namespace System.ComponentModel.Composition.Hosting
         /// <exception cref="ObjectDisposedException">
         ///     The <see cref="CompositionContainer"/> has been disposed of.
         /// </exception>
-        public Lazy<T> GetExport<T>()
+        public Lazy<T>? GetExport<T>()
         {
-            return GetExport<T>((string)null);
+            return GetExport<T>((string?)null);
         }
 
         /// <summary>
@@ -108,7 +108,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// <exception cref="ObjectDisposedException">
         ///     The <see cref="CompositionContainer"/> has been disposed of.
         /// </exception>
-        public Lazy<T> GetExport<T>(string contractName)
+        public Lazy<T>? GetExport<T>(string? contractName)
         {
             return GetExportCore<T>(contractName);
         }
@@ -158,9 +158,9 @@ namespace System.ComponentModel.Composition.Hosting
         /// <exception cref="ObjectDisposedException">
         ///     The <see cref="CompositionContainer"/> has been disposed of.
         /// </exception>
-        public Lazy<T, TMetadataView> GetExport<T, TMetadataView>()
+        public Lazy<T, TMetadataView>? GetExport<T, TMetadataView>()
         {
-            return GetExport<T, TMetadataView>((string)null);
+            return GetExport<T, TMetadataView>((string?)null);
         }
 
         /// <summary>
@@ -209,7 +209,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// <exception cref="ObjectDisposedException">
         ///     The <see cref="CompositionContainer"/> has been disposed of.
         /// </exception>
-        public Lazy<T, TMetadataView> GetExport<T, TMetadataView>(string contractName)
+        public Lazy<T, TMetadataView>? GetExport<T, TMetadataView>(string? contractName)
         {
             return GetExportCore<T, TMetadataView>(contractName);
         }
@@ -260,7 +260,7 @@ namespace System.ComponentModel.Composition.Hosting
         ///     The <see cref="CompositionContainer"/> has been disposed of.
         /// </exception>
         [SuppressMessage("Microsoft.Design", "CA1006")]
-        public IEnumerable<Lazy<object, object>> GetExports(Type type, Type metadataViewType, string contractName)
+        public IEnumerable<Lazy<object, object>> GetExports(Type type, Type? metadataViewType, string? contractName)
         {
             IEnumerable<Export> exports = GetExportsCore(type, metadataViewType, contractName, ImportCardinality.ZeroOrMore);
             Collection<Lazy<object, object>> result = new Collection<Lazy<object, object>>();
@@ -309,7 +309,7 @@ namespace System.ComponentModel.Composition.Hosting
         [SuppressMessage("Microsoft.Design", "CA1006")]
         public IEnumerable<Lazy<T>> GetExports<T>()
         {
-            return GetExports<T>((string)null);
+            return GetExports<T>((string?)null);
         }
 
         /// <summary>
@@ -349,7 +349,7 @@ namespace System.ComponentModel.Composition.Hosting
         ///     The <see cref="CompositionContainer"/> has been disposed of.
         /// </exception>
         [SuppressMessage("Microsoft.Design", "CA1006")]
-        public IEnumerable<Lazy<T>> GetExports<T>(string contractName)
+        public IEnumerable<Lazy<T>> GetExports<T>(string? contractName)
         {
             return GetExportsCore<T>(contractName);
         }
@@ -390,7 +390,7 @@ namespace System.ComponentModel.Composition.Hosting
         [SuppressMessage("Microsoft.Design", "CA1006")]
         public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>()
         {
-            return GetExports<T, TMetadataView>((string)null);
+            return GetExports<T, TMetadataView>((string?)null);
         }
 
         /// <summary>
@@ -431,7 +431,7 @@ namespace System.ComponentModel.Composition.Hosting
         ///     The <see cref="CompositionContainer"/> has been disposed of.
         /// </exception>
         [SuppressMessage("Microsoft.Design", "CA1006")]
-        public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string contractName)
+        public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string? contractName)
         {
             return GetExportsCore<T, TMetadataView>(contractName);
         }
@@ -479,9 +479,10 @@ namespace System.ComponentModel.Composition.Hosting
         ///     An error occurred during composition. <see cref="CompositionException.Errors"/> will
         ///     contain a collection of errors that occurred.
         /// </exception>
+        [return: MaybeNull]
         public T GetExportedValue<T>()
         {
-            return GetExportedValue<T>((string)null);
+            return GetExportedValue<T>((string?)null);
         }
 
         /// <summary>
@@ -529,7 +530,8 @@ namespace System.ComponentModel.Composition.Hosting
         ///     An error occurred during composition. <see cref="CompositionException.Errors"/> will
         ///     contain a collection of errors that occurred.
         /// </exception>
-        public T GetExportedValue<T>(string contractName)
+        [return: MaybeNull]
+        public T GetExportedValue<T>(string? contractName)
         {
             return GetExportedValueCore<T>(contractName, ImportCardinality.ExactlyOne);
         }
@@ -579,9 +581,10 @@ namespace System.ComponentModel.Composition.Hosting
         ///     An error occurred during composition. <see cref="CompositionException.Errors"/> will
         ///     contain a collection of errors that occurred.
         /// </exception>
+        [return: MaybeNull]
         public T GetExportedValueOrDefault<T>()
         {
-            return GetExportedValueOrDefault<T>((string)null);
+            return GetExportedValueOrDefault<T>((string?)null);
         }
 
         /// <summary>
@@ -629,7 +632,8 @@ namespace System.ComponentModel.Composition.Hosting
         ///     An error occurred during composition. <see cref="CompositionException.Errors"/> will
         ///     contain a collection of errors that occurred.
         /// </exception>
-        public T GetExportedValueOrDefault<T>(string contractName)
+        [return: MaybeNull]
+        public T GetExportedValueOrDefault<T>(string? contractName)
         {
             return GetExportedValueCore<T>(contractName, ImportCardinality.ZeroOrOne);
         }
@@ -670,7 +674,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// </exception>
         public IEnumerable<T> GetExportedValues<T>()
         {
-            return GetExportedValues<T>((string)null);
+            return GetExportedValues<T>((string?)null);
         }
 
         /// <summary>
@@ -709,14 +713,14 @@ namespace System.ComponentModel.Composition.Hosting
         ///     An error occurred during composition. <see cref="CompositionException.Errors"/> will
         ///     contain a collection of errors that occurred.
         /// </exception>
-        public IEnumerable<T> GetExportedValues<T>(string contractName)
+        public IEnumerable<T> GetExportedValues<T>(string? contractName)
         {
             return GetExportedValuesCore<T>(contractName);
         }
 
-        private IEnumerable<T> GetExportedValuesCore<T>(string contractName)
+        private IEnumerable<T> GetExportedValuesCore<T>(string? contractName)
         {
-            IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore);
+            IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type?)null, contractName, ImportCardinality.ZeroOrMore);
 
             Collection<T> result = new Collection<T>();
             foreach (Export export in exports)
@@ -726,21 +730,22 @@ namespace System.ComponentModel.Composition.Hosting
             return result;
         }
 
-        private T GetExportedValueCore<T>(string contractName, ImportCardinality cardinality)
+        [return: MaybeNull]
+        private T GetExportedValueCore<T>(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<T>(export) : default(T);
+            return (export != null) ? ExportServices.GetCastedExportedValue<T>(export) : default(T)!;
         }
 
-        private IEnumerable<Lazy<T>> GetExportsCore<T>(string contractName)
+        private IEnumerable<Lazy<T>> GetExportsCore<T>(string? contractName)
         {
-            IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore);
+            IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type?)null, contractName, ImportCardinality.ZeroOrMore);
 
             Collection<Lazy<T>> result = new Collection<Lazy<T>>();
             foreach (Export export in exports)
@@ -750,7 +755,7 @@ namespace System.ComponentModel.Composition.Hosting
             return result;
         }
 
-        private IEnumerable<Lazy<T, TMetadataView>> GetExportsCore<T, TMetadataView>(string contractName)
+        private IEnumerable<Lazy<T, TMetadataView>> GetExportsCore<T, TMetadataView>(string? contractName)
         {
             IEnumerable<Export> exports = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ZeroOrMore);
 
@@ -762,21 +767,21 @@ namespace System.ComponentModel.Composition.Hosting
             return result;
         }
 
-        private Lazy<T, TMetadataView> GetExportCore<T, TMetadataView>(string contractName)
+        private Lazy<T, TMetadataView>? GetExportCore<T, TMetadataView>(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<T, TMetadataView>(export) : null;
         }
 
-        private Lazy<T> GetExportCore<T>(string contractName)
+        private Lazy<T>? GetExportCore<T>(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<T>(export) : null;
         }
 
-        private IEnumerable<Export> GetExportsCore(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality)
+        private IEnumerable<Export> 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<KeyValuePair<string, Type>> requiredMetadata = CompositionServices.GetRequiredMetadata(metadataViewType);
-            IDictionary<string, object> metadata = CompositionServices.GetImportMetadata(type, null);
+            IDictionary<string, object?> metadata = CompositionServices.GetImportMetadata(type, null);
 
-            string requiredTypeIdentity = null;
+            string? requiredTypeIdentity = null;
             if (type != typeof(object))
             {
                 requiredTypeIdentity = AttributedModelServices.GetTypeIdentity(type);
index bc9fc3d..e583cd5 100644 (file)
@@ -26,12 +26,12 @@ namespace System.ComponentModel.Composition.Hosting
         /// <summary>
         ///     Occurs when the exports in the <see cref="ExportProvider"/> have changed.
         /// </summary>
-        public event EventHandler<ExportsChangeEventArgs> ExportsChanged;
+        public event EventHandler<ExportsChangeEventArgs>? ExportsChanged;
 
         /// <summary>
         ///     Occurs when the exports in the <see cref="ExportProvider"/> are changing.
         /// </summary>
-        public event EventHandler<ExportsChangeEventArgs> ExportsChanging;
+        public event EventHandler<ExportsChangeEventArgs>? ExportsChanging;
 
         /// <summary>
         ///     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 <see cref="ImportDefinition"/>.
         ///     </para>
         /// </exception>
-        public IEnumerable<Export> GetExports(ImportDefinition definition, AtomicComposition atomicComposition)
+        public IEnumerable<Export> GetExports(ImportDefinition definition, AtomicComposition? atomicComposition)
         {
             Requires.NotNull(definition, nameof(definition));
 
-            IEnumerable<Export> exports;
-            ExportCardinalityCheckResult result = TryGetExportsCore(definition, atomicComposition, out exports);
+            ExportCardinalityCheckResult result = TryGetExportsCore(definition, atomicComposition, out IEnumerable<Export>? exports);
             switch (result)
             {
                 case ExportCardinalityCheckResult.Match:
@@ -141,11 +140,10 @@ namespace System.ComponentModel.Composition.Hosting
         /// <exception cref="ArgumentNullException">
         ///     <paramref name="definition"/> is <see langword="null"/>.
         /// </exception>
-        public bool TryGetExports(ImportDefinition definition, AtomicComposition atomicComposition, out IEnumerable<Export> exports)
+        public bool TryGetExports(ImportDefinition definition, AtomicComposition? atomicComposition, out IEnumerable<Export>? 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 <see cref="ImportDefinition"/>, an <see cref="IEnumerable{T}"/> should be returned.
         ///     </note>
         /// </remarks>
-        protected abstract IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition);
+        protected abstract IEnumerable<Export>? GetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition);
 
         /// <summary>
         ///     Raises the <see cref="ExportsChanged"/> event.
@@ -181,7 +179,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// </param>
         protected virtual void OnExportsChanged(ExportsChangeEventArgs e)
         {
-            EventHandler<ExportsChangeEventArgs> changedEvent = ExportsChanged;
+            EventHandler<ExportsChangeEventArgs>? changedEvent = ExportsChanged;
             if (changedEvent != null)
             {
                 CompositionResult result = CompositionServices.TryFire(changedEvent, this, e);
@@ -197,7 +195,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// </param>
         protected virtual void OnExportsChanging(ExportsChangeEventArgs e)
         {
-            EventHandler<ExportsChangeEventArgs> changingEvent = ExportsChanging;
+            EventHandler<ExportsChangeEventArgs>? 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<Export> exports)
+        private ExportCardinalityCheckResult TryGetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition, out IEnumerable<Export>? exports)
         {
             if (definition == null)
             {
index e4300f2..f57c618 100644 (file)
@@ -19,7 +19,7 @@ namespace System.ComponentModel.Composition.Hosting
     {
         private readonly IEnumerable<ExportDefinition> _addedExports;
         private readonly IEnumerable<ExportDefinition> _removedExports;
-        private IEnumerable<string> _changedContractNames = null;
+        private IEnumerable<string>? _changedContractNames = null;
 
         /// <summary>
         ///     Initializes a new instance of the <see cref="ExportsChangeEventArgs"/> class with
@@ -43,7 +43,7 @@ namespace System.ComponentModel.Composition.Hosting
         ///     <paramref name="addedExports"/> or <paramref name="removedExports"/> is <see langword="null"/>.
         /// </exception>
         public ExportsChangeEventArgs(IEnumerable<ExportDefinition> addedExports,
-                IEnumerable<ExportDefinition> removedExports, AtomicComposition atomicComposition)
+                IEnumerable<ExportDefinition> 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.
         /// </value>
-        public AtomicComposition AtomicComposition { get; private set; }
+        public AtomicComposition? AtomicComposition { get; private set; }
     }
 }
index 7041633..2b4f0e4 100644 (file)
@@ -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<ComposablePartDefinition> _parts;
             private readonly Func<ImportDefinition, bool> _importFilter;
-            private Dictionary<string, List<ComposablePartDefinition>> _exportersIndex;
+            private Dictionary<string, List<ComposablePartDefinition>>? _exportersIndex;
 
             public DependenciesTraversal(FilteredCatalog catalog, Func<ImportDefinition, bool> importFilter)
             {
@@ -50,8 +52,7 @@ namespace System.ComponentModel.Composition.Hosting
 
             private void AddToExportersIndex(string contractName, ComposablePartDefinition part)
             {
-                List<ComposablePartDefinition> parts = null;
-                if (!_exportersIndex.TryGetValue(contractName, out parts))
+                if (!_exportersIndex!.TryGetValue(contractName, out List<ComposablePartDefinition>? parts))
                 {
                     parts = new List<ComposablePartDefinition>();
                     _exportersIndex.Add(contractName, parts);
@@ -59,16 +60,17 @@ namespace System.ComponentModel.Composition.Hosting
                 parts.Add(part);
             }
 
-            public bool TryTraverse(ComposablePartDefinition part, out IEnumerable<ComposablePartDefinition> reachableParts)
+            public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out IEnumerable<ComposablePartDefinition>? reachableParts)
             {
                 reachableParts = null;
-                List<ComposablePartDefinition> reachablePartList = null;
+                List<ComposablePartDefinition>? 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<ComposablePartDefinition> candidateReachableParts = null;
+                    List<ComposablePartDefinition>? candidateReachableParts = null;
+                    Debug.Assert(_exportersIndex != null);
                     foreach (var contractName in import.GetCandidateContractNames(part))
                     {
                         if (_exportersIndex.TryGetValue(contractName, out candidateReachableParts))
index f4d39ca..b9355b5 100644 (file)
@@ -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<ComposablePartDefinition> _parts;
             private readonly Func<ImportDefinition, bool> _importFilter;
-            private Dictionary<string, List<ComposablePartDefinition>> _importersIndex;
+            private Dictionary<string, List<ComposablePartDefinition>>? _importersIndex;
 
             public DependentsTraversal(FilteredCatalog catalog, Func<ImportDefinition, bool> importFilter)
             {
@@ -59,8 +61,7 @@ namespace System.ComponentModel.Composition.Hosting
 
             private void AddToImportersIndex(string contractName, ComposablePartDefinition part)
             {
-                List<ComposablePartDefinition> parts = null;
-                if (!_importersIndex.TryGetValue(contractName, out parts))
+                if (!_importersIndex!.TryGetValue(contractName, out List<ComposablePartDefinition>? parts))
                 {
                     parts = new List<ComposablePartDefinition>();
                     _importersIndex.Add(contractName, parts);
@@ -68,16 +69,17 @@ namespace System.ComponentModel.Composition.Hosting
                 parts.Add(part);
             }
 
-            public bool TryTraverse(ComposablePartDefinition part, out IEnumerable<ComposablePartDefinition> reachableParts)
+            public bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out IEnumerable<ComposablePartDefinition>? reachableParts)
             {
                 reachableParts = null;
-                List<ComposablePartDefinition> reachablePartList = null;
+                List<ComposablePartDefinition>? 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<ComposablePartDefinition> candidateReachableParts = null;
+                    List<ComposablePartDefinition>? candidateReachableParts = null;
                     if (_importersIndex.TryGetValue(export.ContractName, out candidateReachableParts))
                     {
                         // find if they actually match
index 5785445..7cc17dd 100644 (file)
@@ -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<ComposablePartDefinition> reachableParts);
+            bool TryTraverse(ComposablePartDefinition part, [NotNullWhen(true)] out IEnumerable<ComposablePartDefinition>? reachableParts);
         }
     }
 }
index ff3ed47..a282992 100644 (file)
@@ -98,8 +98,7 @@ namespace System.ComponentModel.Composition.Hosting
             {
                 if (traversedParts.Add(part))
                 {
-                    IEnumerable<ComposablePartDefinition> partsToTraverse = null;
-                    if (traversal.TryTraverse(part, out partsToTraverse))
+                    if (traversal.TryTraverse(part, out IEnumerable<ComposablePartDefinition>? 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();
         }
index 1270460..6b39064 100644 (file)
@@ -16,7 +16,7 @@ namespace System.ComponentModel.Composition.Hosting
     {
         private readonly Func<ComposablePartDefinition, bool> _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<ComposablePartDefinition, bool> filter, FilteredCatalog complement)
+        internal FilteredCatalog(ComposablePartCatalog catalog, Func<ComposablePartDefinition, bool> 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
         /// <summary>
         /// Notify when the contents of the Catalog has changed.
         /// </summary>
-        public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
+        public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;
 
         /// <summary>
         /// Notify when the contents of the Catalog is changing.
         /// </summary>
-        public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
+        public event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing;
 
         /// <summary>
         /// Raises the <see cref="Changed"/> event.
@@ -184,7 +183,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// <param name="e">The <see cref="System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs"/> instance containing the event data.</param>
         protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
         {
-            EventHandler<ComposablePartCatalogChangeEventArgs> changedEvent = Changed;
+            EventHandler<ComposablePartCatalogChangeEventArgs>? changedEvent = Changed;
             if (changedEvent != null)
             {
                 changedEvent.Invoke(this, e);
@@ -197,32 +196,32 @@ namespace System.ComponentModel.Composition.Hosting
         /// <param name="e">The <see cref="System.ComponentModel.Composition.Hosting.ComposablePartCatalogChangeEventArgs"/> instance containing the event data.</param>
         protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
         {
-            EventHandler<ComposablePartCatalogChangeEventArgs> changingEvent = Changing;
+            EventHandler<ComposablePartCatalogChangeEventArgs>? 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(
index d827af2..6f80320 100644 (file)
@@ -9,7 +9,7 @@ namespace System.ComponentModel.Composition.Hosting
     /// </summary>
     public interface INotifyComposablePartCatalogChanged
     {
-        event EventHandler<ComposablePartCatalogChangeEventArgs> Changed;
-        event EventHandler<ComposablePartCatalogChangeEventArgs> Changing;
+        event EventHandler<ComposablePartCatalogChangeEventArgs>? Changed;
+        event EventHandler<ComposablePartCatalogChangeEventArgs>? Changing;
     }
 }
index 4628d73..bd6d870 100644 (file)
@@ -18,9 +18,9 @@ namespace System.ComponentModel.Composition.Hosting
             private readonly ImportEngine _importEngine;
             private readonly List<PartManager> _addedPartManagers = new List<PartManager>();
             private readonly List<PartManager> _removedPartManagers = new List<PartManager>();
-            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<PartManager> GetAddedPartManagers()
+            public IEnumerable<PartManager>? GetAddedPartManagers()
             {
                 if (_parentEngineContext != null)
                 {
@@ -61,7 +61,7 @@ namespace System.ComponentModel.Composition.Hosting
                 return _addedPartManagers;
             }
 
-            public IEnumerable<PartManager> GetRemovedPartManagers()
+            public IEnumerable<PartManager>? GetRemovedPartManagers()
             {
                 if (_parentEngineContext != null)
                 {
index e3e8999..9adc214 100644 (file)
@@ -18,9 +18,9 @@ namespace System.ComponentModel.Composition.Hosting
         /// </summary>
         private class PartManager
         {
-            private Dictionary<ImportDefinition, List<IDisposable>> _importedDisposableExports;
-            private Dictionary<ImportDefinition, Export[]> _importCache;
-            private string[] _importedContractNames;
+            private Dictionary<ImportDefinition, List<IDisposable>>? _importedDisposableExports;
+            private Dictionary<ImportDefinition, Export[]?>? _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<ImportDefinition, Export[]>();
+                    _importCache = new Dictionary<ImportDefinition, Export[]?>();
                 }
 
                 _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<IDisposable> disposableExports = null;
+                List<IDisposable>? 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<IDisposable> oldDisposableExports = null;
+                List<IDisposable>? oldDisposableExports = null;
                 if (_importedDisposableExports != null &&
                     _importedDisposableExports.TryGetValue(import, out oldDisposableExports))
                 {
index 78da869..ba2095a 100644 (file)
@@ -70,8 +70,7 @@ namespace System.ComponentModel.Composition.Hosting
 
             public IEnumerable<PartManager> GetPartsImporting(string contractName)
             {
-                WeakReferenceCollection<PartManager> partManagerList;
-                if (!_partManagerIndex.TryGetValue(contractName, out partManagerList))
+                if (!_partManagerIndex.TryGetValue(contractName, out WeakReferenceCollection<PartManager>? partManagerList))
                 {
                     return Enumerable.Empty<PartManager>();
                 }
@@ -83,8 +82,7 @@ namespace System.ComponentModel.Composition.Hosting
             {
                 foreach (string contractName in partManager.GetImportedContractNames())
                 {
-                    WeakReferenceCollection<PartManager> indexEntries;
-                    if (!_partManagerIndex.TryGetValue(contractName, out indexEntries))
+                    if (!_partManagerIndex.TryGetValue(contractName, out WeakReferenceCollection<PartManager>? indexEntries))
                     {
                         indexEntries = new WeakReferenceCollection<PartManager>();
                         _partManagerIndex.Add(contractName, indexEntries);
@@ -101,8 +99,7 @@ namespace System.ComponentModel.Composition.Hosting
             {
                 foreach (string contractName in partManager.GetImportedContractNames())
                 {
-                    WeakReferenceCollection<PartManager> indexEntries;
-                    if (_partManagerIndex.TryGetValue(contractName, out indexEntries))
+                    if (_partManagerIndex.TryGetValue(contractName, out WeakReferenceCollection<PartManager>? 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<PartManager?> partsToUnindex = _partsToUnindex.AliveItemsToList()!;
                 _partsToUnindex.Clear();
 
                 if (partsToIndex.Count == 0 && partsToUnindex.Count == 0)
index 6d1863a..5937de7 100644 (file)
@@ -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<PartManager> _recursionStateStack = new Stack<PartManager>();
         private ConditionalWeakTable<ComposablePart, PartManager> _partManagers = new ConditionalWeakTable<ComposablePart, PartManager>();
         private RecompositionManager _recompositionManager = new RecompositionManager();
-        private readonly CompositionLock _lock = null;
+        private readonly CompositionLock _lock;
         private readonly CompositionOptions _compositionOptions;
 
         /// <summary>
@@ -81,7 +81,7 @@ namespace System.ComponentModel.Composition.Hosting
         /// <exception cref="ObjectDisposedException">
         ///     The <see cref="ImportEngine"/> has been disposed of.
         /// </exception>
-        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
         /// <param name="atomicComposition">
         ///     The <see cref="AtomicComposition"/> that the release imports is running under.
         /// </param>
-        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<ImportDefinition> imports, AtomicComposition atomicComposition)
+            IEnumerable<ImportDefinition> 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<PartManager> 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<ExportDefinition> changedExports, AtomicComposition atomicComposition)
+            IEnumerable<ExportDefinition> 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<ComposablePart, PartManager> partManagers = null;
-                RecompositionManager recompositionManager = null;
+                ConditionalWeakTable<ComposablePart, PartManager>? 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<IEnumerable<Export>> TryGetExports(ExportProvider provider,
-            ComposablePart part, ImportDefinition definition, AtomicComposition atomicComposition)
+        private static CompositionResult<IEnumerable<Export>> TryGetExports(ExportProvider? provider,
+            ComposablePart part, ImportDefinition definition, AtomicComposition? atomicComposition)
         {
             try
             {
-                IEnumerable<Export> exports = null;
+                IEnumerable<Export>? exports = null;
                 if (provider != null)
                 {
                     exports = provider.GetExports(definition, atomicComposition).AsArray();
                 }
-                return new CompositionResult<IEnumerable<Export>>(exports);
+                return new CompositionResult<IEnumerable<Export>>(exports!);
             }
             catch (ImportCardinalityMismatchException ex)
             {
index ed0c221..12e8f97 100644 (file)
@@ -29,7 +29,7 @@ namespace System.ComponentModel.Composition.Hosting
         internal class NonImportSourceImportDefinition : ContractBasedImportDefinition
         {
             private readonly ContractBasedImportDefinition _sourceDefinition;
-            private IDictionary<string, object> _metadata;
+            private IDictionary<string, object?>? _metadata;
 
             public NonImportSourceImportDefinition(ContractBasedImportDefinition sourceDefinition)
             {
@@ -46,14 +46,14 @@ namespace System.ComponentModel.Composition.Hosting
                 get { return _sourceDefinition.ContractName; }
             }
 
-            public override IDictionary<string, object> Metadata
+            public override IDictionary<string, object?> Metadata
             {
                 get
                 {
                     var reply = _metadata;
                     if (reply == null)
                     {
-                        reply = new Dictionary<string, object>(_sourceDefinition.Metadata);
+                        reply = new Dictionary<string, object?>(_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; }
             }
index 57f8d8c..41623db 100644 (file)
@@ -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)
                 {
index 0e60ac6..a272384 100644 (file)
@@ -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<ComposablePartDefinition> _parts;
+        private Type[]? _types = null;
+        private volatile List<ComposablePartDefinition>? _parts;
         private volatile bool _isDisposed = false;
         private readonly ICompositionElement _definitionOrigin;
         private readonly Lazy<IDictionary<string, List<ComposablePartDefinition>>> _contractPartIndex;
@@ -243,7 +243,7 @@ namespace System.ComponentModel.Composition.Hosting
         ///     This property always returns <see langword="null"/>.
         /// </value>
         [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<ComposablePartDefinition> GetCandidateParts(ImportDefinition definition)
+        internal override IEnumerable<ComposablePartDefinition>? GetCandidateParts(ImportDefinition definition)
         {
             if (definition == null)
             {
@@ -297,23 +297,22 @@ namespace System.ComponentModel.Composition.Hosting
                 return PartsInternal;
             }
 
-            string genericContractName = definition.Metadata.GetValue<string>(CompositionConstants.GenericContractMetadataName);
+            string? genericContractName = definition.Metadata.GetValue<string>(CompositionConstants.GenericContractMetadataName);
 
-            List<ComposablePartDefinition> nonGenericMatches = GetCandidateParts(contractName);
-            List<ComposablePartDefinition> genericMatches = GetCandidateParts(genericContractName);
+            List<ComposablePartDefinition>? nonGenericMatches = GetCandidateParts(contractName);
+            List<ComposablePartDefinition>? genericMatches = GetCandidateParts(genericContractName);
 
             return nonGenericMatches.ConcatAllowingNull(genericMatches);
         }
 
-        private List<ComposablePartDefinition> GetCandidateParts(string contractName)
+        private List<ComposablePartDefinition>? GetCandidateParts(string? contractName)
         {
             if (contractName == null)
             {
                 return null;
             }
 
-            List<ComposablePartDefinition> contractCandidateParts = null;
-            _contractPartIndex.Value.TryGetValue(contractName, out contractCandidateParts);
+            _contractPartIndex.Value.TryGetValue(contractName, out List<ComposablePartDefinition>? contractCandidateParts);
             return contractCandidateParts;
         }
 
@@ -325,7 +324,7 @@ namespace System.ComponentModel.Composition.Hosting
             {
                 foreach (string contractName in part.ExportDefinitions.Select(export => export.ContractName).Distinct())
                 {
-                    List<ComposablePartDefinition> contractParts = null;
+                    List<ComposablePartDefinition>? contractParts = null;
                     if (!index.TryGetValue(contractName, out contractParts))
                     {
                         contractParts = new List<ComposablePartDefinition>();
index b44c13f..65e38a7 100644 (file)
@@ -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; }
index e30a964..73d0d65 100644 (file)
@@ -31,7 +31,7 @@ namespace System.ComponentModel.Composition
         ///     </para>
         /// </remarks>
         public ImportAttribute()
-            : this((string)null)
+            : this((string?)null)
         {
         }
 
@@ -59,8 +59,8 @@ namespace System.ComponentModel.Composition
         ///         using <see cref="StringComparer.Ordinal"/>.
         ///     </para>
         /// </remarks>
-        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 <see cref="StringComparer.Ordinal"/>.
         ///     </para>
         /// </remarks>
-        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 <see cref="string"/> containing the contract name of the export to import. The
         ///      default value is an empty string ("").
         /// </value>
-        public string ContractName { get; private set; }
+        public string? ContractName { get; private set; }
 
         /// <summary>
         ///     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 <see cref="object"/> then the
         ///     importer is delaring they can accept any exported type.
         /// </value>
-        public Type ContractType { get; private set; }
+        public Type? ContractType { get; private set; }
 
         /// <summary>
         ///     Gets or sets a value indicating whether the property, field or parameter will be set
index 0fe2041..0e49855 100644 (file)
@@ -21,7 +21,7 @@ namespace System.ComponentModel.Composition
         ///     Initializes a new instance of the <see cref="ImportCardinalityMismatchException"/> class.
         /// </summary>
         public ImportCardinalityMismatchException()
-            : this((string)null, (Exception)null)
+            : this((string?)null, (Exception?)null)
         {
         }
 
@@ -34,8 +34,8 @@ namespace System.ComponentModel.Composition
         ///     <see cref="ImportCardinalityMismatchException"/>; or <see langword="null"/> to set
         ///     the <see cref="Exception.Message"/> property to its default value.
         /// </param>
-        public ImportCardinalityMismatchException(string message)
-            : this(message, (Exception)null)
+        public ImportCardinalityMismatchException(string? message)
+            : this(message, (Exception?)null)
         {
         }
 
@@ -54,7 +54,7 @@ namespace System.ComponentModel.Composition
         ///     <see cref="ImportCardinalityMismatchException"/>; or <see langword="null"/> to set
         ///     the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
         /// </param>
-        public ImportCardinalityMismatchException(string message, Exception innerException)
+        public ImportCardinalityMismatchException(string? message, Exception? innerException)
             : base(message, innerException)
         {
         }
index 49c1506..4878cc1 100644 (file)
@@ -17,7 +17,7 @@ namespace System.ComponentModel.Composition
             _exception = exception;
         }
 
-        public Exception InnerException
+        public Exception? InnerException
         {
             get { return _exception.InnerException; }
         }
index 383e18d..1653047 100644 (file)
@@ -31,7 +31,7 @@ namespace System.ComponentModel.Composition
         ///     </para>
         /// </remarks>
         public ImportManyAttribute()
-            : this((string)null)
+            : this((string?)null)
         {
         }
 
@@ -59,8 +59,8 @@ namespace System.ComponentModel.Composition
         ///         using <see cref="StringComparer.Ordinal"/>.
         ///     </para>
         /// </remarks>
-        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 <see cref="StringComparer.Ordinal"/>.
         ///     </para>
         /// </remarks>
-        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 <see cref="string"/> containing the contract name of the exports to import. The
         ///      default value is an empty string ("").
         /// </value>
-        public string ContractName { get; private set; }
+        public string? ContractName { get; private set; }
 
         /// <summary>
         ///     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 <see cref="object"/> then the
         ///     importer is delaring they can accept any exported type.
         /// </value>
-        public Type ContractType { get; private set; }
+        public Type? ContractType { get; private set; }
 
         /// <summary>
         ///     Gets or sets a value indicating whether the property or field will be recomposed
index 826afb6..f28cb99 100644 (file)
@@ -29,7 +29,7 @@ namespace System.ComponentModel.Composition
         ///     </para>
         /// </remarks>
         public InheritedExportAttribute()
-            : this((string)null, (Type)null)
+            : this((string?)null, (Type?)null)
         {
         }
 
@@ -58,8 +58,8 @@ namespace System.ComponentModel.Composition
         ///         using <see cref="StringComparer.Ordinal"/>.
         ///     </para>
         /// </remarks>
-        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 <see cref="StringComparer.Ordinal"/>.
         ///     </para>
         /// </remarks>
-        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 <see cref="StringComparer.Ordinal"/>.
         ///     </para>
         /// </remarks>
-        public InheritedExportAttribute(string contractName, Type contractType)
+        public InheritedExportAttribute(string? contractName, Type? contractType)
             : base(contractName, contractType)
         {
         }
index 61958bf..5906e2c 100644 (file)
@@ -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<string, object> EmptyMetadata = new ReadOnlyDictionary<string, object>(new Dictionary<string, object>(0));
+        public static readonly IDictionary<string, object?> EmptyMetadata = new ReadOnlyDictionary<string, object?>(new Dictionary<string, object?>(0));
 
-        public static IDictionary<string, object> AsReadOnly(this IDictionary<string, object> metadata)
+        public static IDictionary<string, object?> AsReadOnly(this IDictionary<string, object?>? metadata)
         {
             if (metadata == null)
             {
                 return EmptyMetadata;
             }
 
-            if (metadata is ReadOnlyDictionary<string, object>)
+            if (metadata is ReadOnlyDictionary<string, object?>)
             {
                 return metadata;
             }
 
-            return new ReadOnlyDictionary<string, object>(metadata);
+            return new ReadOnlyDictionary<string, object?>(metadata);
         }
 
-        public static T GetValue<T>(this IDictionary<string, object> metadata, string key)
+        [return: MaybeNull]
+        public static T GetValue<T>(this IDictionary<string, object?> 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)!;
             }
         }
     }
index 84853dd..d66409b 100644 (file)
@@ -57,7 +57,7 @@ namespace System.ComponentModel.Composition
     // }
     internal static class MetadataViewGenerator
     {
-        public delegate object MetadataViewFactory(IDictionary<string, object> metadata);
+        public delegate object MetadataViewFactory(IDictionary<string, object?> 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<Type, MetadataViewFactory> _metadataViewFactories = new Dictionary<Type, MetadataViewFactory>();
         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<string, object>) };
-        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<TMetadataView>(MetadataViewFactory metadataViewFactory, IDictionary<string, object> metadata)
+        public static TMetadataView CreateMetadataView<TMetadataView>(MetadataViewFactory metadataViewFactory, IDictionary<string, object?> 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);
index 4eeca11..ae03992 100644 (file)
@@ -24,7 +24,7 @@ namespace System.ComponentModel.Composition
         ///         using a generated type.
         ///     </para>
         /// </remarks>
-        public MetadataViewImplementationAttribute(Type implementationType)
+        public MetadataViewImplementationAttribute(Type? implementationType)
         {
             ImplementationType = implementationType;
         }
@@ -37,6 +37,6 @@ namespace System.ComponentModel.Composition
         ///     <see langword="null"/> which means that the type will be obtained by looking at the type on
         ///     the member that this export is attached to.
         /// </value>
-        public Type ImplementationType { get; private set; }
+        public Type? ImplementationType { get; private set; }
     }
 }
index 31c82c4..ac61aa5 100644 (file)
@@ -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<TMetadataView>(IDictionary<string, object> metadata)
+        public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object?> 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<string, object>)))
+            if (metadataViewType.IsAssignableFrom(typeof(IDictionary<string, object?>)))
             {
                 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<MetadataViewImplementationAttribute>())
@@ -48,13 +49,13 @@ namespace System.ComponentModel.Composition
                     else
                     {
                         var implementationAttribute = metadataViewType.GetFirstAttribute<MetadataViewImplementationAttribute>();
+                        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<string, object>.
                     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(
index f8d8167..5758dda 100644 (file)
@@ -23,7 +23,7 @@ namespace System.ComponentModel.Composition
         ///     An <see cref="object"/> containing the metadata value. This can be
         ///     <see langword="null"/>.
         /// </param>
-        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
         /// <value>
         ///     An <see cref="object"/> containing the metadata value.
         /// </value>
-        public object Value
+        public object? Value
         {
             get;
             private set;
index 516a5ac..a9f9ee8 100644 (file)
@@ -105,7 +105,7 @@ namespace System.ComponentModel.Composition.Primitives
         ///         </note>
         ///      </para>
         /// </remarks>
-        public virtual IDictionary<string, object> Metadata
+        public virtual IDictionary<string, object?> Metadata
         {
             get
             {
@@ -155,7 +155,7 @@ namespace System.ComponentModel.Composition.Primitives
         /// <exception cref="ComposablePartException">
         ///     An error occurred getting the exported value described by the <see cref="ExportDefinition"/>.
         /// </exception>
-        public abstract object GetExportedValue(ExportDefinition definition);
+        public abstract object? GetExportedValue(ExportDefinition definition);
 
         /// <summary>
         ///     Sets the import described by the specified definition with the specified exports.
index b08dc29..2e3a3c7 100644 (file)
@@ -23,7 +23,7 @@ namespace System.ComponentModel.Composition.Primitives
     public abstract class ComposablePartCatalog : IEnumerable<ComposablePartDefinition>, IDisposable
     {
         private bool _isDisposed;
-        private volatile IQueryable<ComposablePartDefinition> _queryableParts = null;
+        private volatile IQueryable<ComposablePartDefinition>? _queryableParts = null;
 
         internal static readonly List<Tuple<ComposablePartDefinition, ExportDefinition>> _EmptyExportsList = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
 
@@ -102,16 +102,13 @@ namespace System.ComponentModel.Composition.Primitives
 
             Requires.NotNull(definition, nameof(definition));
 
-            List<Tuple<ComposablePartDefinition, ExportDefinition>> exports = null;
+            List<Tuple<ComposablePartDefinition, ExportDefinition>>? exports = null;
             var candidateParts = GetCandidateParts(definition);
             if (candidateParts != null)
             {
                 foreach (var part in candidateParts)
                 {
-                    Tuple<ComposablePartDefinition, ExportDefinition> singleMatch;
-                    IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches;
-
-                    if (part.TryGetExports(definition, out singleMatch, out multipleMatches))
+                    if (part.TryGetExports(definition, out Tuple<ComposablePartDefinition, ExportDefinition>? singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleMatches))
                     {
                         exports = exports.FastAppendToListAllowNulls(singleMatch, multipleMatches);
                     }
@@ -122,7 +119,7 @@ namespace System.ComponentModel.Composition.Primitives
             return exports ?? _EmptyExportsList;
         }
 
-        internal virtual IEnumerable<ComposablePartDefinition> GetCandidateParts(ImportDefinition definition)
+        internal virtual IEnumerable<ComposablePartDefinition>? GetCandidateParts(ImportDefinition definition)
         {
             return this;
         }
index 565858b..039e464 100644 (file)
@@ -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
         ///         </note>
         ///     </para>
         /// </remarks>
-        public virtual IDictionary<string, object> Metadata
+        public virtual IDictionary<string, object?> Metadata
         {
             get { return MetadataServices.EmptyMetadata; }
         }
@@ -102,13 +103,13 @@ namespace System.ComponentModel.Composition.Primitives
         /// </remarks>
         public abstract ComposablePart CreatePart();
 
-        internal virtual bool TryGetExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
+        internal virtual bool TryGetExports(ImportDefinition definition, [NotNullWhen(true)] out Tuple<ComposablePartDefinition, ExportDefinition>? singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleMatches)
         {
             singleMatch = null;
             multipleMatches = null;
 
-            List<Tuple<ComposablePartDefinition, ExportDefinition>> multipleExports = null;
-            Tuple<ComposablePartDefinition, ExportDefinition> singleExport = null;
+            List<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleExports = null;
+            Tuple<ComposablePartDefinition, ExportDefinition>? 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;
         }
index 5d542a8..e47ad1d 100644 (file)
@@ -16,13 +16,13 @@ namespace System.ComponentModel.Composition.Primitives
     [Serializable]
     public class ComposablePartException : Exception
     {
-        private readonly ICompositionElement _element;
+        private readonly ICompositionElement? _element;
 
         /// <summary>
         ///     Initializes a new instance of the <see cref="ComposablePartException"/> class.
         /// </summary>
         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
         /// </exception>
         protected ComposablePartException(SerializationInfo info, StreamingContext context) : base(info, context)
         {
-            _element = (ICompositionElement)info.GetValue("Element", typeof(ICompositionElement));
+            _element = (ICompositionElement?)info.GetValue("Element", typeof(ICompositionElement));
         }
 
         /// <summary>
@@ -61,8 +61,8 @@ namespace System.ComponentModel.Composition.Primitives
         ///     <see cref="ComposablePartException"/>; or <see langword="null"/> to set
         ///     the <see cref="Exception.Message"/> property to its default value.
         /// </param>
-        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 <see cref="ComposablePartException.Element"/> property to
         ///     <see langword="null"/>.
         /// </param>
-        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
         ///     <see cref="ComposablePartException"/>; or <see langword="null"/> to set
         ///     the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
         /// </param>
-        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
         ///     <see cref="ComposablePartException"/>; or <see langword="null"/> to set
         ///     the <see cref="Exception.InnerException"/> property to <see langword="null"/>.
         /// </param>
-        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 <see cref="ICompositionElement"/> that is the cause of the
         ///     <see cref="ComposablePartException"/>. The default is <see langword="null"/>.
         /// </value>
-        public ICompositionElement Element
+        public ICompositionElement? Element
         {
             get { return _element; }
         }
index 9cd179e..05ecb85 100644 (file)
@@ -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; }
         }
index c4bedd8..9f61c68 100644 (file)
@@ -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; }
         }
index 5ee1220..cab7ca7 100644 (file)
@@ -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; }
         }
index 4706b52..8cfdaf6 100644 (file)
@@ -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;
             }
index 7316c22..b8a57d6 100644 (file)
@@ -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<KeyValuePair<string, Type>> _requiredMetadata = Enumerable.Empty<KeyValuePair<string, Type>>();
-        private Expression<Func<ExportDefinition, bool>> _constraint;
+        private Expression<Func<ExportDefinition, bool>>? _constraint;
         private readonly CreationPolicy _requiredCreationPolicy = CreationPolicy.Any;
-        private readonly string _requiredTypeIdentity = null;
+        private readonly string? _requiredTypeIdentity = null;
         private bool _isRequiredMetadataValidated = false;
 
         /// <summary>
@@ -100,7 +100,7 @@ namespace System.ComponentModel.Composition.Primitives
         ///     values.
         /// </exception>
         [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
-        public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+        public ContractBasedImportDefinition(string contractName, string? requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>>? 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.
         /// </exception>
         [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
-        public ContractBasedImportDefinition(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
-            ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy, IDictionary<string, object> metadata)
+        public ContractBasedImportDefinition(string contractName, string? requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
+            ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, CreationPolicy requiredCreationPolicy, IDictionary<string, object?> 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 <see langword="null"/> then this import
         ///     doesn't expect a particular type.
         /// </value>
-        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<string>(CompositionConstants.ExportTypeIdentityMetadataName);
+                string? exportTypeIdentity = definition.Metadata.GetValue<string>(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;
                 }
index a79c23c..d8a7e31 100644 (file)
@@ -16,10 +16,10 @@ namespace System.ComponentModel.Composition.Primitives
     /// </summary>
     public class Export
     {
-        private readonly ExportDefinition _definition;
-        private readonly Func<object> _exportedValueGetter;
+        private readonly ExportDefinition? _definition;
+        private readonly Func<object?>? _exportedValueGetter;
         private static readonly object _EmptyValue = new object();
-        private volatile object _exportedValue = Export._EmptyValue;
+        private volatile object? _exportedValue = Export._EmptyValue;
 
         /// <summary>
         ///     Initializes a new instance of the <see cref="Export"/> class.
@@ -56,8 +56,8 @@ namespace System.ComponentModel.Composition.Primitives
         /// <exception cref="ArgumentException">
         ///     <paramref name="contractName"/> is an empty string ("").
         /// </exception>
-        public Export(string contractName, Func<object> exportedValueGetter)
-            : this(new ExportDefinition(contractName, (IDictionary<string, object>)null), exportedValueGetter)
+        public Export(string contractName, Func<object?> exportedValueGetter)
+            : this(new ExportDefinition(contractName, (IDictionary<string, object?>?)null), exportedValueGetter)
         {
         }
 
@@ -89,7 +89,7 @@ namespace System.ComponentModel.Composition.Primitives
         /// <exception cref="ArgumentException">
         ///     <paramref name="contractName"/> is an empty string ("").
         /// </exception>
-        public Export(string contractName, IDictionary<string, object> metadata, Func<object> exportedValueGetter)
+        public Export(string contractName, IDictionary<string, object?>? metadata, Func<object?> exportedValueGetter)
             : this(new ExportDefinition(contractName, metadata), exportedValueGetter)
         {
         }
@@ -113,7 +113,7 @@ namespace System.ComponentModel.Composition.Primitives
         ///     </para>
         ///     <paramref name="exportedValueGetter"/> is <see langword="null"/>.
         /// </exception>
-        public Export(ExportDefinition definition, Func<object> exportedValueGetter)
+        public Export(ExportDefinition definition, Func<object?> exportedValueGetter)
         {
             Requires.NotNull(definition, nameof(definition));
             Requires.NotNull(exportedValueGetter, nameof(exportedValueGetter));
@@ -167,7 +167,7 @@ namespace System.ComponentModel.Composition.Primitives
         ///         of the <see cref="Definition"/> property.
         ///     </para>
         /// </remarks>
-        public IDictionary<string, object> Metadata
+        public IDictionary<string, object?> Metadata
         {
             get
             {
@@ -194,7 +194,7 @@ namespace System.ComponentModel.Composition.Primitives
         /// <exception cref="NotImplementedException">
         ///     The <see cref="GetExportedValueCore"/> method was not overridden by a derived class.
         /// </exception>
-        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
         ///     </note>
         /// </remarks>
         [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
-        protected virtual object GetExportedValueCore()
+        protected virtual object? GetExportedValueCore()
         {
             if (_exportedValueGetter != null)
             {
index 6256a02..bee7b94 100644 (file)
@@ -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<string, object> _metadata = MetadataServices.EmptyMetadata;
-        private readonly string _contractName;
+        private readonly IDictionary<string, object?> _metadata = MetadataServices.EmptyMetadata;
+        private readonly string? _contractName;
 
         /// <summary>
         ///     Initializes a new instance of the <see cref="ExportDefinition"/> class.
@@ -52,7 +52,7 @@ namespace System.ComponentModel.Composition.Primitives
         /// <exception cref="ArgumentException">
         ///     <paramref name="contractName"/> is an empty string ("").
         /// </exception>
-        public ExportDefinition(string contractName, IDictionary<string, object> metadata)
+        public ExportDefinition(string contractName, IDictionary<string, object?>? metadata)
         {
             Requires.NotNullOrEmpty(contractName, nameof(contractName));
 
@@ -113,7 +113,7 @@ namespace System.ComponentModel.Composition.Primitives
         ///         </note>
         ///     </para>
         /// </remarks>
-        public virtual IDictionary<string, object> Metadata
+        public virtual IDictionary<string, object?> Metadata
         {
             get
             {
index f37d88b..abc2201 100644 (file)
@@ -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));
 
index 1e3ae6e..e2e13a2 100644 (file)
@@ -35,7 +35,7 @@ namespace System.ComponentModel.Composition.Primitives
         ///     <see cref="ICompositionElement"/> originated, or <see langword="null"/>
         ///     if the <see cref="ICompositionElement"/> is the root composition element.
         /// </value>
-        ICompositionElement Origin
+        ICompositionElement? Origin
         {
             get;
         }
index 6d9120d..83ddadf 100644 (file)
@@ -17,13 +17,13 @@ namespace System.ComponentModel.Composition.Primitives
     public class ImportDefinition
     {
         internal static readonly string EmptyContractName = string.Empty;
-        private readonly Expression<Func<ExportDefinition, bool>> _constraint;
+        private readonly Expression<Func<ExportDefinition, bool>>? _constraint;
         private readonly ImportCardinality _cardinality = ImportCardinality.ExactlyOne;
         private readonly string _contractName = EmptyContractName;
         private readonly bool _isRecomposable;
         private readonly bool _isPrerequisite = true;
-        private Func<ExportDefinition, bool> _compiledConstraint;
-        private readonly IDictionary<string, object> _metadata = MetadataServices.EmptyMetadata;
+        private Func<ExportDefinition, bool>? _compiledConstraint;
+        private readonly IDictionary<string, object?> _metadata = MetadataServices.EmptyMetadata;
 
         /// <summary>
         ///     Initializes a new instance of the <see cref="ImportDefinition"/> class.
@@ -80,7 +80,7 @@ namespace System.ComponentModel.Composition.Primitives
         ///     values.
         /// </exception>
         [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
-        public ImportDefinition(Expression<Func<ExportDefinition, bool>> constraint, string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite)
+        public ImportDefinition(Expression<Func<ExportDefinition, bool>> 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<Func<ExportDefinition, bool>> constraint, string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary<string, object> metadata)
+        public ImportDefinition(Expression<Func<ExportDefinition, bool>> constraint, string? contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary<string, object?>? 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<string, object> metadata)
+        internal ImportDefinition(string? contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary<string, object?>? metadata)
         {
             if (
                 (cardinality != ImportCardinality.ExactlyOne) &&
@@ -159,7 +159,7 @@ namespace System.ComponentModel.Composition.Primitives
         ///         </note>
         ///     </para>
         /// </remarks>
-        public virtual IDictionary<string, object> Metadata
+        public virtual IDictionary<string, object?> Metadata
         {
             get
             {
index 1085c17..4e0fcbe 100644 (file)
@@ -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<string>(CompositionConstants.GenericContractMetadataName);
-            int[] importParametersOrder = import.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
+            string? genericContractName = import.Metadata.GetValue<string>(CompositionConstants.GenericContractMetadataName);
+            int[]? importParametersOrder = import.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
             if (importParametersOrder != null)
             {
                 int partArity = part.Metadata.GetValue<int>(CompositionConstants.GenericPartArityMetadataName);
@@ -56,9 +54,7 @@ namespace System.ComponentModel.Composition.Primitives
             import = import.GetProductImportDefinition();
             if (expandGenerics)
             {
-                Tuple<ComposablePartDefinition, ExportDefinition> singleMatch;
-                IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches;
-                return part.TryGetExports(import, out singleMatch, out multipleMatches);
+                return part.TryGetExports(import, out Tuple<ComposablePartDefinition, ExportDefinition>? singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? 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<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
+            int[]? importParametersOrder = contractBasedImport.Metadata.GetValue<int[]>(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,
index 96ac6a2..9e53b49 100644 (file)
@@ -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);
index c6cc44a..d3030da 100644 (file)
@@ -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();
             }
index b6ce9be..847a2dd 100644 (file)
@@ -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();
index 450c29b..da3e3f3 100644 (file)
@@ -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<Export, object> CreateStronglyTypedExportFactoryFactory(Type exportType, Type metadataViewType)
+        public Func<Export, object> 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<T, M>(Export export)
@@ -69,11 +69,11 @@ namespace System.ComponentModel.Composition.ReflectionModel
 
             Func<Tuple<T, Action>> exportLifetimeContextCreator = () => lifetimeContext.GetExportLifetimeContextFromExport<T>(export);
             var metadataView = AttributedModelServices.GetMetadataView<M>(export.Metadata);
-            object[] args = { exportLifetimeContextCreator, metadataView };
+            object?[] args = { exportLifetimeContextCreator, metadataView };
 
             var instance = Activator.CreateInstance(constructed, args);
 
-            return instance;
+            return instance!;
         }
 
     }
index c4d47ea..eaa450d 100644 (file)
@@ -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);
index c9ad48c..d4dfa88 100644 (file)
@@ -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<Type> CreateTypeSpecializations(this Type[] types, Type[] specializationTypes)
+        [return: NotNullIfNotNull("types")]
+        public static IEnumerable<Type>? 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<Type> constraints, GenericParameterAttributes attributes)
+        public static bool CanSpecialize(Type? type, IEnumerable<Type>? constraints, GenericParameterAttributes attributes)
         {
-            return CanSpecialize(type, constraints) && CanSpecialize(type, attributes);
+            return CanSpecialize(type, constraints) && CanSpecialize(type!, attributes);
         }
 
-        public static bool CanSpecialize(Type type, IEnumerable<Type> constraintTypes)
+        public static bool CanSpecialize(Type? type, IEnumerable<Type>? constraintTypes)
         {
             if (constraintTypes == null)
             {
index 4ad040a..00f89e1 100644 (file)
@@ -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<ExportDefinition> _exports;
-        private IEnumerable<ImportDefinition> _imports;
+        private IEnumerable<ExportDefinition>? _exports;
+        private IEnumerable<ImportDefinition>? _imports;
         private readonly Lazy<Type> _lazyPartType;
-        private List<LazyMemberInfo> _members;
-        private List<Lazy<ParameterInfo>> _parameters;
-        private Dictionary<LazyMemberInfo, MemberInfo[]> _membersTable;
-        private Dictionary<Lazy<ParameterInfo>, ParameterInfo> _parametersTable;
-        private ConstructorInfo _constructor;
+        private List<LazyMemberInfo>? _members;
+        private List<Lazy<ParameterInfo>>? _parameters;
+        private Dictionary<LazyMemberInfo, MemberInfo[]>? _membersTable;
+        private Dictionary<Lazy<ParameterInfo>, 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<string, object> GetMetadata()
+        public IDictionary<string, object?> GetMetadata()
         {
-            var originalMetadata = new Dictionary<string, object>(_originalPartCreationInfo.GetMetadata(), StringComparers.MetadataKeyNames);
+            var originalMetadata = new Dictionary<string, object?>(_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<LazyMemberInfo> members = null;
-            List<Lazy<ParameterInfo>> parameters = null;
+            List<LazyMemberInfo>? members = null;
+            List<Lazy<ParameterInfo>>? 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<LazyMemberInfo, MemberInfo[]> membersTable = BuildMembersTable(members);
-            Dictionary<Lazy<ParameterInfo>, ParameterInfo> parametersTable = BuildParametersTable(parameters);
+            Dictionary<LazyMemberInfo, MemberInfo[]> membersTable = BuildMembersTable(members!);
+            Dictionary<Lazy<ParameterInfo>, 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<Lazy<ParameterInfo>, ParameterInfo> BuildParametersTable(List<Lazy<ParameterInfo>> parameters)
+        [return: NotNullIfNotNull("parameters")]
+        private Dictionary<Lazy<ParameterInfo>, ParameterInfo>? BuildParametersTable(List<Lazy<ParameterInfo>>? parameters)
         {
             if (parameters != null)
             {
                 Dictionary<Lazy<ParameterInfo>, ParameterInfo> parametersTable = new Dictionary<Lazy<ParameterInfo>, 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<string, object> metadata = TranslateImportMetadata(productImport);
+            string requiredTypeIdentity = Translate(productImport.RequiredTypeIdentity!);
+            IDictionary<string, object?> 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<LazyMemberInfo> 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<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName));
 
             LazyMemberInfo exportingMember = new LazyMemberInfo(capturedLazyMember.MemberType, () => GetAccessors(capturedLazyMember));
-            Lazy<IDictionary<string, object>> lazyMetadata = new Lazy<IDictionary<string, object>>(() => TranslateExportMetadata(capturedReflectionExport));
+            Lazy<IDictionary<string, object?>> lazyMetadata = new Lazy<IDictionary<string, object?>>(() => 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<string, object> TranslateImportMetadata(ContractBasedImportDefinition originalImport)
+        private IDictionary<string, object?> TranslateImportMetadata(ContractBasedImportDefinition originalImport)
         {
-            int[] importParametersOrder = originalImport.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
+            int[]? importParametersOrder = originalImport.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
             if (importParametersOrder != null)
             {
-                Dictionary<string, object> metadata = new Dictionary<string, object>(originalImport.Metadata, StringComparers.MetadataKeyNames);
+                Dictionary<string, object?> metadata = new Dictionary<string, object?>(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<string, object> TranslateExportMetadata(ReflectionMemberExportDefinition originalExport)
+        private IDictionary<string, object?> TranslateExportMetadata(ReflectionMemberExportDefinition originalExport)
         {
-            Dictionary<string, object> metadata = new Dictionary<string, object>(originalExport.Metadata, StringComparers.MetadataKeyNames);
+            Dictionary<string, object?> metadata = new Dictionary<string, object?>(originalExport.Metadata, StringComparers.MetadataKeyNames);
 
-            string exportTypeIdentity = originalExport.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName);
+            string? exportTypeIdentity = originalExport.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName);
             if (!string.IsNullOrEmpty(exportTypeIdentity))
             {
                 metadata[CompositionConstants.ExportTypeIdentityMetadataName] = Translate(exportTypeIdentity, originalExport.Metadata.GetValue<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName));
@@ -519,13 +519,13 @@ namespace System.ComponentModel.Composition.ReflectionModel
         public IEnumerable<ExportDefinition> GetExports()
         {
             PopulateImportsAndExports();
-            return _exports;
+            return _exports!;
         }
 
         public IEnumerable<ImportDefinition> 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<string, object> partMetadata, Type[] specialization)
+        public static bool CanSpecialize(IDictionary<string, object?> partMetadata, Type[] specialization)
         {
             int partArity = partMetadata.GetValue<int>(CompositionConstants.GenericPartArityMetadataName);
 
@@ -577,8 +571,8 @@ namespace System.ComponentModel.Composition.ReflectionModel
                 return false;
             }
 
-            object[] genericParameterConstraints = partMetadata.GetValue<object[]>(CompositionConstants.GenericParameterConstraintsMetadataName);
-            GenericParameterAttributes[] genericParameterAttributes = partMetadata.GetValue<GenericParameterAttributes[]>(CompositionConstants.GenericParameterAttributesMetadataName);
+            object[]? genericParameterConstraints = partMetadata.GetValue<object[]>(CompositionConstants.GenericParameterConstraintsMetadataName);
+            GenericParameterAttributes[]? genericParameterAttributes = partMetadata.GetValue<GenericParameterAttributes[]>(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;
                 }
index 974891f..1ff705c 100644 (file)
@@ -12,8 +12,8 @@ namespace System.ComponentModel.Composition.ReflectionModel
     {
         Type GetPartType();
         Lazy<Type> GetLazyPartType();
-        ConstructorInfo GetConstructor();
-        IDictionary<string, object> GetMetadata();
+        ConstructorInfo? GetConstructor();
+        IDictionary<string, object?>? GetMetadata();
         IEnumerable<ExportDefinition> GetExports();
         IEnumerable<ImportDefinition> GetImports();
         bool IsDisposalRequired { get; }
index 3b58f81..ebc0705 100644 (file)
@@ -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<Export, object> _castSingleValue;
+        private Type _contractType = null!; // Initialized in Initialize()
+        private Func<Export, object>? _castSingleValue;
         private readonly bool _isOpenGeneric = false;
 
         [ThreadStatic]
-        internal static Dictionary<Type, Func<Export, object>> _castSingleValueCache;
+        internal static Dictionary<Type, Func<Export, object>>? _castSingleValueCache;
 
         private static Dictionary<Type, Func<Export, object>> 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<Export, object> CastExport
+        public Func<Export, object>? 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<Export, object> castFunction)
+        private static bool TryGetCastFunction(Type genericType, bool isOpenGeneric, Type[] arguments, [NotNullWhen(true)] out Func<Export, object>? 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!);
                 }
             }
 
index 98ef7f6..502e6e2 100644 (file)
@@ -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(
index 5f5150b..3e7dfa2 100644 (file)
@@ -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<object> collection = null;
-            Type itemType = CollectionServices.GetCollectionElementType(ImportType.ActualType);
+            ICollection<object>? 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<object> GetNormalizedCollection(Type itemType, object instance)
+        private ICollection<object> 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<object> collection)
+        private void EnsureCollectionIsWritable(ICollection<object>? 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<object> collection, IEnumerable values)
+        private void PopulateCollection(ICollection<object?> 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
                 {
index 3a8367d..333c8a1 100644 (file)
@@ -12,8 +12,8 @@ namespace System.ComponentModel.Composition.ReflectionModel
     public struct LazyMemberInfo
     {
         private readonly MemberTypes _memberType;
-        private MemberInfo[] _accessors;
-        private readonly Func<MemberInfo[]> _accessorsCreator;
+        private MemberInfo?[]? _accessors;
+        private readonly Func<MemberInfo[]>? _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)
index 8c6fd35..ddb37bd 100644 (file)
@@ -11,7 +11,7 @@ namespace System.ComponentModel.Composition.ReflectionModel
     internal class PartCreatorExportDefinition : ExportDefinition
     {
         private readonly ExportDefinition _productDefinition;
-        private IDictionary<string, object> _metadata;
+        private IDictionary<string, object?>? _metadata;
 
         public PartCreatorExportDefinition(ExportDefinition productDefinition)
             : base()
@@ -27,13 +27,13 @@ namespace System.ComponentModel.Composition.ReflectionModel
             }
         }
 
-        public override IDictionary<string, object> Metadata
+        public override IDictionary<string, object?> Metadata
         {
             get
             {
                 if (_metadata == null)
                 {
-                    var metadata = new Dictionary<string, object>(_productDefinition.Metadata);
+                    var metadata = new Dictionary<string, object?>(_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);
                 }
index a66f880..3e0f229 100644 (file)
@@ -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)
index e7b94be..d8917b3 100644 (file)
@@ -16,7 +16,7 @@ namespace System.ComponentModel.Composition.ReflectionModel
 
         public PartCreatorParameterImportDefinition(
             Lazy<ParameterInfo> importingLazyParameter,
-            ICompositionElement origin,
+            ICompositionElement? origin,
             ContractBasedImportDefinition productImportDefinition)
             : base(importingLazyParameter, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity,
                 productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, CreationPolicy.Any, MetadataServices.EmptyMetadata, origin)
index 292eeba..3565756 100644 (file)
@@ -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<ImportDefinition, object> _importValues = null;
-        private volatile Dictionary<ImportDefinition, ImportingItem> _importsCache = null;
-        private volatile Dictionary<int, ExportingMember> _exportsCache = null;
+        private volatile Dictionary<ImportDefinition, object?>? _importValues = null;
+        private volatile Dictionary<ImportDefinition, ImportingItem>? _importsCache = null;
+        private volatile Dictionary<int, ExportingMember>? _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<ImportDefinition, object> ImportValues
+        private Dictionary<ImportDefinition, object?> ImportValues
         {
             get
             {
@@ -69,7 +70,7 @@ namespace System.ComponentModel.Composition.ReflectionModel
                         value = _importValues;
                         if (value == null)
                         {
-                            value = new Dictionary<ImportDefinition, object>();
+                            value = new Dictionary<ImportDefinition, object?>();
                             _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<string, object> Metadata
+        public override IDictionary<string, object?> 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<ReflectionParameterImportDefinition>().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<int, ExportingMember>();
             }
-            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();
             }
index 704c9f1..5cce608 100644 (file)
@@ -16,10 +16,10 @@ namespace System.ComponentModel.Composition.ReflectionModel
     {
         private readonly IReflectionPartCreationInfo _creationInfo;
 
-        private volatile ImportDefinition[] _imports;
-        private volatile ExportDefinition[] _exports;
-        private volatile IDictionary<string, object> _metadata;
-        private volatile ConstructorInfo _constructor;
+        private volatile ImportDefinition[]? _imports;
+        private volatile ExportDefinition[]? _exports;
+        private volatile IDictionary<string, object?>? _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<string, object> Metadata
+        public override IDictionary<string, object?> Metadata
         {
             get
             {
                 if (_metadata == null)
                 {
-                    IDictionary<string, object> metadata = _creationInfo.GetMetadata().AsReadOnly();
+                    IDictionary<string, object?> 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<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
+        internal override bool TryGetExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition>? singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleMatches)
         {
             if (this.IsGeneric())
             {
                 singleMatch = null;
                 multipleMatches = null;
 
-                List<Tuple<ComposablePartDefinition, ExportDefinition>> exports = null;
+                List<Tuple<ComposablePartDefinition, ExportDefinition>>? exports = null;
 
                 var genericParameters = (definition.Metadata.Count > 0) ? definition.Metadata.GetValue<IEnumerable<object>>(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<ComposablePartDefinition> candidates = null;
-                        ComposablePartDefinition candidatePart = null;
-                        ComposablePartDefinition previousPart = null;
+                        HashSet<ComposablePartDefinition>? 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<ComposablePartDefinition, ExportDefinition> candidateSingleMatch;
-                                    IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> candidateMultipleMatches;
-                                    if (candidatePart.TryGetExports(definition, out candidateSingleMatch, out candidateMultipleMatches))
+                                    if (candidatePart.TryGetExports(definition, out Tuple<ComposablePartDefinition, ExportDefinition>? candidateSingleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? 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<ComposablePartDefinition, ExportDefinition> singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> multipleMatches)
+        private bool TryGetNonGenericExports(ImportDefinition definition, out Tuple<ComposablePartDefinition, ExportDefinition>? singleMatch, out IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleMatches)
         {
             singleMatch = null;
             multipleMatches = null;
 
-            List<Tuple<ComposablePartDefinition, ExportDefinition>> multipleExports = null;
-            Tuple<ComposablePartDefinition, ExportDefinition> singleExport = null;
+            List<Tuple<ComposablePartDefinition, ExportDefinition>>? multipleExports = null;
+            Tuple<ComposablePartDefinition, ExportDefinition>? singleExport = null;
             bool matchesFound = false;
 
             foreach (var export in ExportDefinitionsInternal)
@@ -303,7 +298,7 @@ namespace System.ComponentModel.Composition.ReflectionModel
 
         }
 
-        private static bool TryGetGenericTypeParameters(IEnumerable<object> genericParameters, out Type[] genericTypeParameters)
+        private static bool TryGetGenericTypeParameters(IEnumerable<object> 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);
             }
         }
 
index 0b028ad..4548be4 100644 (file)
@@ -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)
index a098321..494795f 100644 (file)
@@ -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);
         }
index ec92b85..c468793 100644 (file)
@@ -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<KeyValuePair<string, Type>> requiredMetadata,
+            string? requiredTypeIdentity,
+            IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
             ImportCardinality cardinality,
             bool isRecomposable,
             bool isPrerequisite,
             CreationPolicy requiredCreationPolicy,
-            IDictionary<string, object> metadata,
-            ICompositionElement origin)
+            IDictionary<string, object?> 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; }
         }
index 6de13a5..8a7419d 100644 (file)
@@ -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; }
index 5da9f84..b74f572 100644 (file)
@@ -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);
     }
 }
index 620ef10..9050a14 100644 (file)
@@ -12,10 +12,10 @@ namespace System.ComponentModel.Composition.ReflectionModel
     {
         private readonly LazyMemberInfo _member;
         private readonly ExportDefinition _exportDefinition;
-        private readonly ICompositionElement _origin;
-        private IDictionary<string, object> _metadata;
+        private readonly ICompositionElement? _origin;
+        private IDictionary<string, object?>? _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<string, object> Metadata
+        public override IDictionary<string, object?> Metadata
         {
             get
             {
@@ -54,7 +54,7 @@ namespace System.ComponentModel.Composition.ReflectionModel
             get { return GetDisplayName(); }
         }
 
-        ICompositionElement ICompositionElement.Origin
+        ICompositionElement? ICompositionElement.Origin
         {
             get { return _origin; }
         }
index 1b91f3b..276d92d 100644 (file)
@@ -15,14 +15,14 @@ namespace System.ComponentModel.Composition.ReflectionModel
         public ReflectionMemberImportDefinition(
             LazyMemberInfo importingLazyMember,
             string contractName,
-            string requiredTypeIdentity,
-            IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+            string? requiredTypeIdentity,
+            IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
             ImportCardinality cardinality,
             bool isRecomposable,
             bool isPrerequisite,
             CreationPolicy requiredCreationPolicy,
-            IDictionary<string, object> metadata,
-            ICompositionElement origin)
+            IDictionary<string, object?> metadata,
+            ICompositionElement? origin)
             : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, metadata, origin)
         {
             if (contractName == null)
index 0f5824e..8cf26b9 100644 (file)
@@ -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);
         }
index 474615b..3b4b6b5 100644 (file)
@@ -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<Type> partType,
             bool isDisposalRequired,
-            Lazy<IEnumerable<ImportDefinition>> imports,
-            Lazy<IEnumerable<ExportDefinition>> exports,
-            Lazy<IDictionary<string, object>> metadata,
-            ICompositionElement origin)
+            Lazy<IEnumerable<ImportDefinition>>? imports,
+            Lazy<IEnumerable<ExportDefinition>>? exports,
+            Lazy<IDictionary<string, object?>>? 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<IDictionary<string, object>> metadata,
-            ICompositionElement origin)
+            Lazy<IDictionary<string, object?>> 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<KeyValuePair<string, Type>> requiredMetadata,
+            string? requiredTypeIdentity,
+            IEnumerable<KeyValuePair<string, Type>>? 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<KeyValuePair<string, Type>> requiredMetadata,
+            string? requiredTypeIdentity,
+            IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
             ImportCardinality cardinality,
             bool isRecomposable,
             CreationPolicy requiredCreationPolicy,
-            IDictionary<string, object> metadata,
+            IDictionary<string, object?> 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<KeyValuePair<string, Type>> requiredMetadata,
+            string? requiredTypeIdentity,
+            IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
             ImportCardinality cardinality,
             bool isRecomposable,
             bool isPreRequisite,
             CreationPolicy requiredCreationPolicy,
-            IDictionary<string, object> metadata,
+            IDictionary<string, object?> 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<ParameterInfo> parameter,
             string contractName,
-            string requiredTypeIdentity,
-            IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+            string? requiredTypeIdentity,
+            IEnumerable<KeyValuePair<string, Type>>? 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<ParameterInfo> parameter,
             string contractName,
-            string requiredTypeIdentity,
-            IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+            string? requiredTypeIdentity,
+            IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
             ImportCardinality cardinality,
             CreationPolicy requiredCreationPolicy,
-            IDictionary<string, object> metadata,
+            IDictionary<string, object?> 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<Type> genericParameters, out ComposablePartDefinition specialization)
+        public static bool TryMakeGenericPartDefinition(ComposablePartDefinition partDefinition, IEnumerable<Type> 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<Type> _partType;
-        private readonly Lazy<IEnumerable<ImportDefinition>> _imports;
-        private readonly Lazy<IEnumerable<ExportDefinition>> _exports;
-        private readonly Lazy<IDictionary<string, object>> _metadata;
-        private readonly ICompositionElement _origin;
-        private ConstructorInfo _constructor;
+        private readonly Lazy<IEnumerable<ImportDefinition>>? _imports;
+        private readonly Lazy<IEnumerable<ExportDefinition>>? _exports;
+        private readonly Lazy<IDictionary<string, object?>>? _metadata;
+        private readonly ICompositionElement? _origin;
+        private ConstructorInfo? _constructor;
         private readonly bool _isDisposalRequired;
 
         public ReflectionPartCreationInfo(
             Lazy<Type> partType,
             bool isDisposalRequired,
-            Lazy<IEnumerable<ImportDefinition>> imports,
-            Lazy<IEnumerable<ExportDefinition>> exports,
-            Lazy<IDictionary<string, object>> metadata,
-            ICompositionElement origin)
+            Lazy<IEnumerable<ImportDefinition>>? imports,
+            Lazy<IEnumerable<ExportDefinition>>? exports,
+            Lazy<IDictionary<string, object?>>? 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<ReflectionParameterImportDefinition>()
                     .Select(parameterImport => parameterImport.ImportingLazyParameter.Value.Member)
@@ -403,7 +403,7 @@ namespace System.ComponentModel.Composition.ReflectionModel
             }
         }
 
-        public IDictionary<string, object> GetMetadata()
+        public IDictionary<string, object?>? 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<IDictionary<string, object>> _metadata;
+        private readonly Lazy<IDictionary<string, object?>> _metadata;
 
-        public LazyExportDefinition(string contractName, Lazy<IDictionary<string, object>> metadata)
-            : base(contractName, (IDictionary<string, object>)null)
+        public LazyExportDefinition(string contractName, Lazy<IDictionary<string, object?>> metadata)
+            : base(contractName, (IDictionary<string, object?>?)null)
         {
             _metadata = metadata;
         }
 
-        public override IDictionary<string, object> Metadata
+        public override IDictionary<string, object?> Metadata
         {
             get
             {
index 190bb7f..8458281 100644 (file)
@@ -27,7 +27,7 @@ namespace System.ComponentModel.Composition.ReflectionModel
             get { return _parameter; }
         }
 
-        public override string Name
+        public override string? Name
         {
             get { return UnderlyingParameter.Name; }
         }
index bd25724..2949cac 100644 (file)
@@ -17,12 +17,12 @@ namespace System.ComponentModel.Composition.ReflectionModel
         public ReflectionParameterImportDefinition(
             Lazy<ParameterInfo> importingLazyParameter,
             string contractName,
-            string requiredTypeIdentity,
-            IEnumerable<KeyValuePair<string, Type>> requiredMetadata,
+            string? requiredTypeIdentity,
+            IEnumerable<KeyValuePair<string, Type>>? requiredMetadata,
             ImportCardinality cardinality,
             CreationPolicy requiredCreationPolicy,
-            IDictionary<string, object> metadata,
-            ICompositionElement origin)
+            IDictionary<string, object?> metadata,
+            ICompositionElement? origin)
             : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, false, true, requiredCreationPolicy, metadata, origin)
         {
             if (importingLazyParameter == null)
index 30890a1..4fa68c9 100644 (file)
@@ -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);
         }
 
     }
index 413a073..3bece66 100644 (file)
@@ -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;
         }
index 8d0eba4..67e4097 100644 (file)
@@ -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);
     }
 }