Nullable annotations for System.Runtime.Serialization.Xml and System.Runtime.Serializ...
authorEric Erhardt <eric.erhardt@microsoft.com>
Fri, 28 Aug 2020 21:55:24 +0000 (16:55 -0500)
committerGitHub <noreply@github.com>
Fri, 28 Aug 2020 21:55:24 +0000 (23:55 +0200)
* Initial nullable annotations of System.Private.DataContractSerialization

Contributes to #2339

* Mark DataMember.Name as non-nullable.

* Fix a few simple nullable compile errors.

* Assert attributes is non-null in XmlObjectSerializerReadContext

* Ensure XmlObjectSerializerContext.serializer is never null

* Fix a few simple nullable errors

* Remove any checks that DataMember.MemberInfo can be null.

* Mark EnumDataContract.Members as non-nullable.

Fix nullable errors in SchemaExporter.

* Correctly annotate CollectionDataContract.IsCollectionOrTryCreate.

* Assert DataContractResolver is non-null.

* Suppress https://github.com/dotnet/runtime/issues/41465

* Update System.Runtime.Serialization.Json ref source for nullable annotations.

* Update System.Runtime.Serializaiton.Xml ref source for nullable annotations.

* Update for Xml.ReaderWriter nullable annotations

* Work around compiler issue.

* Fix test failure.

Reference compiler issue in TODO comment.

* Revert nullable suppression now that XmlSchemaAppInfo.Markup is annotated correctly.

* Fix build for latest annotations in master.

* PR feedback round 1

* Address PR feedback round 2

115 files changed:
src/libraries/Common/src/System/CodeDom/CodeObject.cs
src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs
src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs
src/libraries/System.Private.DataContractSerialization/src/System.Private.DataContractSerialization.csproj
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/AccessorBuilder.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Attributes.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractResolver.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializerExtensions.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializerSettings.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSurrogateCaller.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DiagnosticUtility.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/GenericParameterDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/IExtensibleDataObject.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializerSettings.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/IXmlJsonReaderInitializer.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonByteArrayDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonClassDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonQNameDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonStringDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonUriDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/KnownTypeDataContractResolver.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SpecialTypeDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContextComplex.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/IXmlDictionary.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/PrefixHandle.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/StringHandle.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/ValueHandle.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryAsyncCheckWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlExceptionHelper.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlStreamNodeWriter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs
src/libraries/System.Runtime.Serialization.Json/ref/System.Runtime.Serialization.Json.cs
src/libraries/System.Runtime.Serialization.Json/ref/System.Runtime.Serialization.Json.csproj
src/libraries/System.Runtime.Serialization.Json/src/System.Runtime.Serialization.Json.csproj
src/libraries/System.Runtime.Serialization.Xml/ref/System.Runtime.Serialization.Xml.cs
src/libraries/System.Runtime.Serialization.Xml/ref/System.Runtime.Serialization.Xml.csproj
src/libraries/System.Runtime.Serialization.Xml/src/System.Runtime.Serialization.Xml.csproj

index c20871a..74aa7a9 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Runtime.Serialization
     internal class CodeObject
 #endif
     {
-        private IDictionary _userData;
+        private IDictionary? _userData;
 
         public CodeObject() { }
 
index 7a5f3e7..5144111 100644 (file)
@@ -28,9 +28,9 @@ namespace System.Runtime.Serialization
     internal class CodeTypeReference : CodeObject
 #endif
     {
-        private string _baseType;
+        private string? _baseType;
         private readonly bool _isInterface;
-        private CodeTypeReferenceCollection _typeArguments;
+        private CodeTypeReferenceCollection? _typeArguments;
         private bool _needsFixup;
 
         public CodeTypeReference()
@@ -50,7 +50,7 @@ namespace System.Runtime.Serialization
             if (type.IsArray)
             {
                 ArrayRank = type.GetArrayRank();
-                ArrayElementType = new CodeTypeReference(type.GetElementType());
+                ArrayElementType = new CodeTypeReference(type.GetElementType()!);
                 _baseType = null;
             }
             else
@@ -86,7 +86,7 @@ namespace System.Runtime.Serialization
                 Type currentType = type;
                 while (currentType.IsNested)
                 {
-                    currentType = currentType.DeclaringType;
+                    currentType = currentType.DeclaringType!;
                     _baseType = currentType.Name + "+" + _baseType;
                 }
 
@@ -116,17 +116,17 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private void Initialize(string typeName)
+        private void Initialize(string? typeName)
         {
             Initialize(typeName, Options);
         }
 
-        private void Initialize(string typeName, CodeTypeReferenceOptions options)
+        private void Initialize(string? typeName, CodeTypeReferenceOptions options)
         {
             Options = options;
             if (string.IsNullOrEmpty(typeName))
             {
-                typeName = typeof(void).FullName;
+                typeName = typeof(void).FullName!;
                 _baseType = typeName;
                 ArrayRank = 0;
                 ArrayElementType = null;
@@ -303,7 +303,7 @@ namespace System.Runtime.Serialization
             ArrayElementType = arrayType;
         }
 
-        public CodeTypeReference ArrayElementType { get; set; }
+        public CodeTypeReference? ArrayElementType { get; set; }
 
         public int ArrayRank { get; set; }
 
index 819fa06..7705d99 100644 (file)
@@ -29,7 +29,7 @@ namespace System.Runtime.Serialization
 
         public CodeTypeReference this[int index]
         {
-            get { return ((CodeTypeReference)(List[index])); }
+            get { return ((CodeTypeReference)(List[index]!)); }
             set { List[index] = value; }
         }
 
index 7ab4ab7..0eec0d2 100644 (file)
@@ -1,4 +1,4 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <NoWarn>$(NoWarn);1634;1691;649</NoWarn>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
@@ -7,6 +7,7 @@
     <TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
     <!-- Too much private reflection. Do not bother with trimming -->
     <ILLinkTrimAssembly>false</ILLinkTrimAssembly>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <PropertyGroup>
     <RuntimeSerializationSources>System\Runtime\Serialization</RuntimeSerializationSources>
index 47d02fb..5cbe935 100644 (file)
@@ -13,15 +13,15 @@ namespace System.Runtime.Serialization
 {
     internal static class FastInvokerBuilder
     {
-        public delegate void Setter(ref object obj, object value);
-        public delegate object Getter(object obj);
+        public delegate void Setter(ref object obj, object? value);
+        public delegate object? Getter(object obj);
 
         private delegate void StructSetDelegate<T, TArg>(ref T obj, TArg value);
         private delegate TResult StructGetDelegate<T, out TResult>(ref T obj);
 
-        private static readonly MethodInfo s_createGetterInternal = typeof(FastInvokerBuilder).GetMethod(nameof(CreateGetterInternal), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
-        private static readonly MethodInfo s_createSetterInternal = typeof(FastInvokerBuilder).GetMethod(nameof(CreateSetterInternal), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
-        private static readonly MethodInfo s_make = typeof(FastInvokerBuilder).GetMethod(nameof(Make), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
+        private static readonly MethodInfo s_createGetterInternal = typeof(FastInvokerBuilder).GetMethod(nameof(CreateGetterInternal), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!;
+        private static readonly MethodInfo s_createSetterInternal = typeof(FastInvokerBuilder).GetMethod(nameof(CreateSetterInternal), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!;
+        private static readonly MethodInfo s_make = typeof(FastInvokerBuilder).GetMethod(nameof(Make), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!;
 
         public static Func<object> GetMakeNewInstanceFunc(Type type)
         {
@@ -31,25 +31,23 @@ namespace System.Runtime.Serialization
 
         public static Getter CreateGetter(MemberInfo memberInfo)
         {
-            if (memberInfo is PropertyInfo)
+            if (memberInfo is PropertyInfo propInfo)
             {
-                var propInfo = (PropertyInfo)memberInfo;
-                var createGetterGeneric = s_createGetterInternal.MakeGenericMethod(propInfo.DeclaringType, propInfo.PropertyType).CreateDelegate<Func<PropertyInfo, Getter>>();
+                var createGetterGeneric = s_createGetterInternal.MakeGenericMethod(propInfo.DeclaringType!, propInfo.PropertyType).CreateDelegate<Func<PropertyInfo, Getter>>();
                 Getter accessor = createGetterGeneric(propInfo);
                 return accessor;
             }
-            else if (memberInfo is FieldInfo)
+            else if (memberInfo is FieldInfo fieldInfo)
             {
                 return (obj) =>
                 {
-                    FieldInfo fieldInfo = (FieldInfo)memberInfo;
                     var value = fieldInfo.GetValue(obj);
                     return value;
                 };
             }
             else
             {
-                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(memberInfo.DeclaringType), memberInfo.Name)));
+                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(memberInfo.DeclaringType!), memberInfo.Name)));
             }
         }
 
@@ -60,7 +58,7 @@ namespace System.Runtime.Serialization
                 PropertyInfo propInfo = (PropertyInfo)memberInfo;
                 if (propInfo.CanWrite)
                 {
-                    var buildSetAccessorGeneric = s_createSetterInternal.MakeGenericMethod(propInfo.DeclaringType, propInfo.PropertyType).CreateDelegate<Func<PropertyInfo, Setter>>();
+                    var buildSetAccessorGeneric = s_createSetterInternal.MakeGenericMethod(propInfo.DeclaringType!, propInfo.PropertyType).CreateDelegate<Func<PropertyInfo, Setter>>();
                     Setter accessor = buildSetAccessorGeneric(propInfo);
                     return accessor;
                 }
@@ -72,14 +70,14 @@ namespace System.Runtime.Serialization
             else if (memberInfo is FieldInfo)
             {
                 FieldInfo fieldInfo = (FieldInfo)memberInfo;
-                return (ref object obj, object val) =>
+                return (ref object obj, object? val) =>
                 {
                     fieldInfo.SetValue(obj, val);
                 };
             }
             else
             {
-                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(memberInfo.DeclaringType), memberInfo.Name)));
+                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(memberInfo.DeclaringType!), memberInfo.Name)));
             }
         }
 
@@ -111,7 +109,7 @@ namespace System.Runtime.Serialization
 
             if (typeof(DeclaringType).IsValueType)
             {
-                var getMethod = propInfo.GetMethod.CreateDelegate<StructGetDelegate<DeclaringType, PropertyType>>();
+                var getMethod = propInfo.GetMethod!.CreateDelegate<StructGetDelegate<DeclaringType, PropertyType>>();
 
                 return (obj) =>
                 {
@@ -121,7 +119,7 @@ namespace System.Runtime.Serialization
             }
             else
             {
-                var getMethod = propInfo.GetMethod.CreateDelegate<Func<DeclaringType, PropertyType>>();
+                var getMethod = propInfo.GetMethod!.CreateDelegate<Func<DeclaringType, PropertyType>>();
 
                 return (obj) =>
                 {
@@ -136,14 +134,14 @@ namespace System.Runtime.Serialization
             {
                 if (propInfo.Name == "Key")
                 {
-                    return (ref object obj, object val) =>
+                    return (ref object obj, object? val) =>
                     {
                         ((IKeyValue)obj).Key = val;
                     };
                 }
                 else
                 {
-                    return (ref object obj, object val) =>
+                    return (ref object obj, object? val) =>
                     {
                         ((IKeyValue)obj).Value = val;
                     };
@@ -152,22 +150,22 @@ namespace System.Runtime.Serialization
 
             if (typeof(DeclaringType).IsValueType)
             {
-                var setMethod = propInfo.SetMethod.CreateDelegate<StructSetDelegate<DeclaringType, PropertyType>>();
+                var setMethod = propInfo.SetMethod!.CreateDelegate<StructSetDelegate<DeclaringType, PropertyType>>();
 
-                return (ref object obj, object val) =>
+                return (ref object obj, object? val) =>
                 {
                     var unboxed = (DeclaringType)obj;
-                    setMethod(ref unboxed, (PropertyType)val);
-                    obj = unboxed;
+                    setMethod(ref unboxed, (PropertyType)val!);
+                    obj = unboxed!;
                 };
             }
             else
             {
-                var setMethod = propInfo.SetMethod.CreateDelegate<Action<DeclaringType, PropertyType>>();
+                var setMethod = propInfo.SetMethod!.CreateDelegate<Action<DeclaringType, PropertyType>>();
 
-                return (ref object obj, object val) =>
+                return (ref object obj, object? val) =>
                 {
-                    setMethod((DeclaringType)obj, (PropertyType)val);
+                    setMethod((DeclaringType)obj, (PropertyType)val!);
                 };
             }
         }
@@ -180,11 +178,11 @@ namespace System.Runtime.Serialization
         {
             try
             {
-                return method.CreateDelegate(typeof(T)) as T;
+                return (method.CreateDelegate(typeof(T)) as T)!;
             }
             catch (Exception e)
             {
-                throw new InvalidOperationException(SR.Format(SR.FailedToCreateMethodDelegate, method.Name, method.DeclaringType.FullName), e);
+                throw new InvalidOperationException(SR.Format(SR.FailedToCreateMethodDelegate, method.Name, method.DeclaringType!.FullName), e);
             }
         }
     }
index df50b39..9da0654 100644 (file)
@@ -23,18 +23,18 @@ namespace System.Runtime.Serialization
             DictionaryGlobals.XsiTypeLocalName
         };
 
-        internal string Id;
-        internal string Ref;
-        internal string XsiTypeName;
-        internal string XsiTypeNamespace;
-        internal string XsiTypePrefix;
+        internal string Id = null!; // initialized in Reset
+        internal string Ref = null!; // initialized in Reset
+        internal string? XsiTypeName;
+        internal string? XsiTypeNamespace;
+        internal string? XsiTypePrefix;
         internal bool XsiNil;
-        internal string ClrAssembly;
-        internal string ClrType;
+        internal string? ClrAssembly;
+        internal string? ClrType;
         internal int ArraySZSize;
-        internal string FactoryTypeName;
-        internal string FactoryTypeNamespace;
-        internal string FactoryTypePrefix;
+        internal string? FactoryTypeName;
+        internal string? FactoryTypeNamespace;
+        internal string? FactoryTypePrefix;
         internal bool UnrecognizedAttributesFound;
 
         internal void Read(XmlReaderDelegator reader)
index cf1f749..fd5e9ac 100644 (file)
@@ -17,6 +17,7 @@ namespace System.Runtime.Serialization
     using System.Xml;
     using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
     using System.Linq;
+    using System.Diagnostics.CodeAnalysis;
 
 #if USE_REFEMIT
     public sealed class ClassDataContract : DataContract
@@ -24,13 +25,13 @@ namespace System.Runtime.Serialization
     internal sealed class ClassDataContract : DataContract
 #endif
     {
-        public XmlDictionaryString[] ContractNamespaces;
+        public XmlDictionaryString[]? ContractNamespaces;
 
-        public XmlDictionaryString[] MemberNames;
+        public XmlDictionaryString[]? MemberNames;
 
-        public XmlDictionaryString[] MemberNamespaces;
+        public XmlDictionaryString[]? MemberNamespaces;
 
-        private XmlDictionaryString[] _childElementNamespaces;
+        private XmlDictionaryString?[]? _childElementNamespaces;
 
         private ClassDataContractCriticalHelper _helper;
 
@@ -46,26 +47,27 @@ namespace System.Runtime.Serialization
             InitClassDataContract();
         }
 
+        [MemberNotNull(nameof(_helper))]
         private void InitClassDataContract()
         {
-            _helper = base.Helper as ClassDataContractCriticalHelper;
+            _helper = (base.Helper as ClassDataContractCriticalHelper)!;
             this.ContractNamespaces = _helper.ContractNamespaces;
             this.MemberNames = _helper.MemberNames;
             this.MemberNamespaces = _helper.MemberNamespaces;
             _isScriptObject = _helper.IsScriptObject;
         }
 
-        internal ClassDataContract BaseContract
+        internal ClassDataContract? BaseContract
         {
             get { return _helper.BaseContract; }
         }
 
-        internal List<DataMember> Members
+        internal List<DataMember>? Members
         {
             get { return _helper.Members; }
         }
 
-        public XmlDictionaryString[] ChildElementNamespaces
+        public XmlDictionaryString?[]? ChildElementNamespaces
         {
             get
             {
@@ -77,7 +79,7 @@ namespace System.Runtime.Serialization
                         {
                             if (_helper.ChildElementNamespaces == null)
                             {
-                                XmlDictionaryString[] tempChildElementamespaces = CreateChildElementNamespaces();
+                                XmlDictionaryString?[]? tempChildElementamespaces = CreateChildElementNamespaces();
                                 Interlocked.MemoryBarrier();
                                 _helper.ChildElementNamespaces = tempChildElementamespaces;
                             }
@@ -93,36 +95,36 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal MethodInfo OnSerializing
+        internal MethodInfo? OnSerializing
         {
             get
             { return _helper.OnSerializing; }
         }
 
-        internal MethodInfo OnSerialized
+        internal MethodInfo? OnSerialized
         {
             get
             { return _helper.OnSerialized; }
         }
 
-        internal MethodInfo OnDeserializing
+        internal MethodInfo? OnDeserializing
         {
             get
             { return _helper.OnDeserializing; }
         }
 
-        internal MethodInfo OnDeserialized
+        internal MethodInfo? OnDeserialized
         {
             get
             { return _helper.OnDeserialized; }
         }
 
-        internal MethodInfo ExtensionDataSetMethod
+        internal MethodInfo? ExtensionDataSetMethod
         {
             get { return _helper.ExtensionDataSetMethod; }
         }
 
-        public override DataContractDictionary KnownDataContracts
+        public override DataContractDictionary? KnownDataContracts
         {
             get
             { return _helper.KnownDataContracts; }
@@ -147,38 +149,43 @@ namespace System.Runtime.Serialization
             set { _helper.HasExtensionData = value; }
         }
 
+        [MemberNotNullWhen(true, nameof(KeyValuePairGenericArguments))]
+        [MemberNotNullWhen(true, nameof(KeyValuePairAdapterConstructorInfo))]
+        [MemberNotNullWhen(true, nameof(GetKeyValuePairMethodInfo))]
         internal bool IsKeyValuePairAdapter
         {
             get
+#pragma warning disable CS8775 // Member must have a non-null value when exiting in some condition.
             { return _helper.IsKeyValuePairAdapter; }
+#pragma warning restore CS8775 // Member must have a non-null value when exiting in some condition.
         }
 
-        internal Type[] KeyValuePairGenericArguments
+        internal Type[]? KeyValuePairGenericArguments
         {
             get
             { return _helper.KeyValuePairGenericArguments; }
         }
 
-        internal ConstructorInfo KeyValuePairAdapterConstructorInfo
+        internal ConstructorInfo? KeyValuePairAdapterConstructorInfo
         {
             get
             { return _helper.KeyValuePairAdapterConstructorInfo; }
         }
 
-        internal MethodInfo GetKeyValuePairMethodInfo
+        internal MethodInfo? GetKeyValuePairMethodInfo
         {
             get
             { return _helper.GetKeyValuePairMethodInfo; }
         }
 
-        internal ConstructorInfo GetISerializableConstructor()
+        internal ConstructorInfo? GetISerializableConstructor()
         {
             return _helper.GetISerializableConstructor();
         }
 
-        private ConstructorInfo _nonAttributedTypeConstructor;
+        private ConstructorInfo? _nonAttributedTypeConstructor;
 
-        internal ConstructorInfo GetNonAttributedTypeConstructor()
+        internal ConstructorInfo? GetNonAttributedTypeConstructor()
         {
             if (_nonAttributedTypeConstructor == null)
             {
@@ -189,7 +196,7 @@ namespace System.Runtime.Serialization
             return _nonAttributedTypeConstructor;
         }
 
-        private Func<object> _makeNewInstance;
+        private Func<object>? _makeNewInstance;
         private Func<object> MakeNewInstance
         {
             get
@@ -203,9 +210,9 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal bool CreateNewInstanceViaDefaultConstructor(out object obj)
+        internal bool CreateNewInstanceViaDefaultConstructor([NotNullWhen(true)] out object? obj)
         {
-            ConstructorInfo ci = GetNonAttributedTypeConstructor();
+            ConstructorInfo? ci = GetNonAttributedTypeConstructor();
             if (ci == null)
             {
                 obj = null;
@@ -283,7 +290,7 @@ namespace System.Runtime.Serialization
 
         internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames)
         {
-            ClassDataContract cdc = (ClassDataContract)DataContract.GetDataContractFromGeneratedAssembly(type);
+            ClassDataContract? cdc = (ClassDataContract?)DataContract.GetDataContractFromGeneratedAssembly(type);
             if (cdc == null)
             {
                 return new ClassDataContract(type, ns, memberNames);
@@ -298,10 +305,10 @@ namespace System.Runtime.Serialization
 
         internal static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable)
         {
-            DataMember existingMemberContract;
+            DataMember? existingMemberContract;
             if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract))
             {
-                Type declaringType = memberContract.MemberInfo.DeclaringType;
+                Type declaringType = memberContract.MemberInfo.DeclaringType!;
                 DataContract.ThrowInvalidDataContractException(
                     SR.Format((declaringType.IsEnum ? SR.DupEnumMemberValue : SR.DupMemberName),
                         existingMemberContract.MemberInfo.Name,
@@ -314,7 +321,7 @@ namespace System.Runtime.Serialization
             members.Add(memberContract);
         }
 
-        internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary)
+        internal static XmlDictionaryString? GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary)
         {
             childType = DataContract.UnwrapNullableType(childType);
             if (!childType.IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType)
@@ -412,8 +419,8 @@ namespace System.Runtime.Serialization
         private static string GetGeneralTypeName(Type type)
         {
             return type.IsGenericType && !type.IsGenericParameter
-                ? type.GetGenericTypeDefinition().FullName
-                : type.FullName;
+                ? type.GetGenericTypeDefinition().FullName!
+                : type.FullName!;
         }
 
         internal static bool IsKnownSerializableType(Type type)
@@ -429,23 +436,23 @@ namespace System.Runtime.Serialization
         {
             string typeFullName = GetGeneralTypeName(type);
 
-            string[] members;
+            string[]? members;
             return s_knownSerializableTypeInfos.TryGetValue(typeFullName, out members)
                 && members.Contains(memberName);
         }
 
-        private XmlDictionaryString[] CreateChildElementNamespaces()
+        private XmlDictionaryString?[]? CreateChildElementNamespaces()
         {
             if (Members == null)
                 return null;
 
-            XmlDictionaryString[] baseChildElementNamespaces = null;
+            XmlDictionaryString?[]? baseChildElementNamespaces = null;
             if (this.BaseContract != null)
                 baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces;
             int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0;
-            XmlDictionaryString[] childElementNamespaces = new XmlDictionaryString[Members.Count + baseChildElementNamespaceCount];
+            XmlDictionaryString?[] childElementNamespaces = new XmlDictionaryString?[Members.Count + baseChildElementNamespaceCount];
             if (baseChildElementNamespaceCount > 0)
-                Array.Copy(baseChildElementNamespaces, childElementNamespaces, baseChildElementNamespaces.Length);
+                Array.Copy(baseChildElementNamespaces!, childElementNamespaces, baseChildElementNamespaces!.Length);
 
             XmlDictionary dictionary = new XmlDictionary();
             for (int i = 0; i < this.Members.Count; i++)
@@ -461,8 +468,10 @@ namespace System.Runtime.Serialization
             _helper.EnsureMethodsImported();
         }
 
-        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context)
         {
+            Debug.Assert(context != null);
+
             if (_isScriptObject)
             {
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
@@ -470,14 +479,14 @@ namespace System.Runtime.Serialization
             XmlFormatWriterDelegate(xmlWriter, obj, context, this);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context)
         {
             if (_isScriptObject)
             {
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
             }
             xmlReader.Read();
-            object o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces);
+            object? o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces);
             xmlReader.ReadEndElement();
             return o;
         }
@@ -487,7 +496,7 @@ namespace System.Runtime.Serialization
         ///          since this information is used to determine whether to give the generated code access
         ///          permissions to private members, any changes to the logic should be reviewed.
         /// </SecurityNote>
-        internal bool RequiresMemberAccessForRead(SecurityException securityException)
+        internal bool RequiresMemberAccessForRead(SecurityException? securityException)
         {
             EnsureMethodsImported();
             if (!IsTypeVisible(UnderlyingType))
@@ -530,7 +539,7 @@ namespace System.Runtime.Serialization
                         new SecurityException(SR.Format(
                                 SR.PartialTrustDataContractOnDeserializingNotPublic,
                                 DataContract.GetClrTypeFullName(UnderlyingType),
-                                this.OnDeserializing.Name),
+                                this.OnDeserializing!.Name),
                             securityException));
                 }
                 return true;
@@ -544,7 +553,7 @@ namespace System.Runtime.Serialization
                         new SecurityException(SR.Format(
                                 SR.PartialTrustDataContractOnDeserializedNotPublic,
                                 DataContract.GetClrTypeFullName(UnderlyingType),
-                                this.OnDeserialized.Name),
+                                this.OnDeserialized!.Name),
                             securityException));
                 }
                 return true;
@@ -590,7 +599,7 @@ namespace System.Runtime.Serialization
         ///          since this information is used to determine whether to give the generated code access
         ///          permissions to private members, any changes to the logic should be reviewed.
         /// </SecurityNote>
-        internal bool RequiresMemberAccessForWrite(SecurityException securityException)
+        internal bool RequiresMemberAccessForWrite(SecurityException? securityException)
         {
             EnsureMethodsImported();
 
@@ -618,7 +627,7 @@ namespace System.Runtime.Serialization
                         new SecurityException(SR.Format(
                                 SR.PartialTrustDataContractOnSerializingNotPublic,
                                 DataContract.GetClrTypeFullName(this.UnderlyingType),
-                                this.OnSerializing.Name),
+                                this.OnSerializing!.Name),
                             securityException));
                 }
                 return true;
@@ -632,7 +641,7 @@ namespace System.Runtime.Serialization
                         new SecurityException(SR.Format(
                                 SR.PartialTrustDataContractOnSerializedNotPublic,
                                 DataContract.GetClrTypeFullName(UnderlyingType),
-                                this.OnSerialized.Name),
+                                this.OnSerialized!.Name),
                             securityException));
                 }
                 return true;
@@ -675,14 +684,14 @@ namespace System.Runtime.Serialization
 
         private class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper
         {
-            private static Type[] s_serInfoCtorArgs;
-
-            private ClassDataContract _baseContract;
-            private List<DataMember> _members;
-            private MethodInfo _onSerializing, _onSerialized;
-            private MethodInfo _onDeserializing, _onDeserialized;
-            private MethodInfo _extensionDataSetMethod;
-            private DataContractDictionary _knownDataContracts;
+            private static Type[]? s_serInfoCtorArgs;
+
+            private ClassDataContract? _baseContract;
+            private List<DataMember>? _members;
+            private MethodInfo? _onSerializing, _onSerialized;
+            private MethodInfo? _onDeserializing, _onDeserialized;
+            private MethodInfo? _extensionDataSetMethod;
+            private DataContractDictionary? _knownDataContracts;
             private bool _isISerializable;
             private bool _isKnownTypeAttributeChecked;
             private bool _isMethodChecked;
@@ -698,17 +707,13 @@ namespace System.Runtime.Serialization
             private bool _hasExtensionData;
             private readonly bool _isScriptObject;
 
-            private XmlDictionaryString[] _childElementNamespaces;
-            private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate;
-            private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate;
-
-            public XmlDictionaryString[] ContractNamespaces;
-            public XmlDictionaryString[] MemberNames;
-            public XmlDictionaryString[] MemberNamespaces;
+            private XmlDictionaryString?[]? _childElementNamespaces;
+            private XmlFormatClassReaderDelegate? _xmlFormatReaderDelegate;
+            private XmlFormatClassWriterDelegate? _xmlFormatWriterDelegate;
 
-            internal ClassDataContractCriticalHelper() : base()
-            {
-            }
+            public XmlDictionaryString[]? ContractNamespaces;
+            public XmlDictionaryString[]? MemberNames;
+            public XmlDictionaryString[]? MemberNamespaces;
 
             internal ClassDataContractCriticalHelper(Type type) : base(type)
             {
@@ -724,7 +729,7 @@ namespace System.Runtime.Serialization
                     EnsureMethodsImported();
                     return;
                 }
-                Type baseType = type.BaseType;
+                Type? baseType = type.BaseType;
                 _isISerializable = (Globals.TypeOfISerializable.IsAssignableFrom(type));
                 SetIsNonAttributedType(type);
                 if (_isISerializable)
@@ -800,12 +805,12 @@ namespace System.Runtime.Serialization
                     }
                     else
                     {
-                        baseMemberCount = BaseContract.MemberNames.Length;
+                        baseMemberCount = BaseContract.MemberNames!.Length;
                         MemberNames = new XmlDictionaryString[Members.Count + baseMemberCount];
                         Array.Copy(BaseContract.MemberNames, MemberNames, baseMemberCount);
                         MemberNamespaces = new XmlDictionaryString[Members.Count + baseMemberCount];
-                        Array.Copy(BaseContract.MemberNamespaces, MemberNamespaces, baseMemberCount);
-                        baseContractCount = BaseContract.ContractNamespaces.Length;
+                        Array.Copy(BaseContract.MemberNamespaces!, MemberNamespaces, baseMemberCount);
+                        baseContractCount = BaseContract.ContractNamespaces!.Length;
                         ContractNamespaces = new XmlDictionaryString[1 + baseContractCount];
                         Array.Copy(BaseContract.ContractNamespaces, ContractNamespaces, baseContractCount);
                     }
@@ -843,13 +848,13 @@ namespace System.Runtime.Serialization
 
             private void EnsureIsReferenceImported(Type type)
             {
-                DataContractAttribute dataContractAttribute;
+                DataContractAttribute? dataContractAttribute;
                 bool isReference = false;
                 bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute);
 
                 if (BaseContract != null)
                 {
-                    if (hasDataContractAttribute && dataContractAttribute.IsReferenceSetExplicitly)
+                    if (hasDataContractAttribute && dataContractAttribute!.IsReferenceSetExplicitly)
                     {
                         bool baseIsReference = this.BaseContract.IsReference;
                         if ((baseIsReference && !dataContractAttribute.IsReference) ||
@@ -875,7 +880,7 @@ namespace System.Runtime.Serialization
                 }
                 else if (hasDataContractAttribute)
                 {
-                    if (dataContractAttribute.IsReference)
+                    if (dataContractAttribute!.IsReference)
                         isReference = dataContractAttribute.IsReference;
                 }
 
@@ -893,6 +898,8 @@ namespace System.Runtime.Serialization
                 this.IsReference = isReference;
             }
 
+            [MemberNotNull(nameof(_members))]
+            [MemberNotNull(nameof(Members))]
             private void ImportDataMembers()
             {
                 Type type = this.UnderlyingType;
@@ -922,7 +929,7 @@ namespace System.Runtime.Serialization
                         if (memberAttributes != null && memberAttributes.Length > 0)
                         {
                             if (memberAttributes.Length > 1)
-                                ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name));
+                                ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType!), member.Name));
 
                             DataMember memberContract = new DataMember(member);
 
@@ -930,10 +937,10 @@ namespace System.Runtime.Serialization
                             {
                                 PropertyInfo property = (PropertyInfo)member;
 
-                                MethodInfo getMethod = property.GetMethod;
+                                MethodInfo? getMethod = property.GetMethod;
                                 if (getMethod != null && IsMethodOverriding(getMethod))
                                     continue;
-                                MethodInfo setMethod = property.SetMethod;
+                                MethodInfo? setMethod = property.SetMethod;
                                 if (setMethod != null && IsMethodOverriding(setMethod))
                                     continue;
                                 if (getMethod == null)
@@ -968,7 +975,7 @@ namespace System.Runtime.Serialization
                             {
                                 ThrowInvalidDataContractException(
                                     SR.Format(SR.IsRequiredDataMemberOnIsReferenceDataContractType,
-                                    DataContract.GetClrTypeFullName(member.DeclaringType),
+                                    DataContract.GetClrTypeFullName(member.DeclaringType!),
                                     member.Name, true), type);
                             }
                             memberContract.EmitDefaultValue = memberAttribute.EmitDefaultValue;
@@ -978,8 +985,8 @@ namespace System.Runtime.Serialization
                     }
                     else if (!isPodSerializable)
                     {
-                        FieldInfo field = member as FieldInfo;
-                        PropertyInfo property = member as PropertyInfo;
+                        FieldInfo? field = member as FieldInfo;
+                        PropertyInfo? property = member as PropertyInfo;
                         if ((field == null && property == null) || (field != null && field.IsInitOnly))
                             continue;
 
@@ -987,18 +994,18 @@ namespace System.Runtime.Serialization
                         if (memberAttributes != null && memberAttributes.Length > 0)
                         {
                             if (memberAttributes.Length > 1)
-                                ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name));
+                                ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType!), member.Name));
                             else
                                 continue;
                         }
                         DataMember memberContract = new DataMember(member);
                         if (property != null)
                         {
-                            MethodInfo getMethod = property.GetGetMethod();
+                            MethodInfo? getMethod = property.GetGetMethod();
                             if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0)
                                 continue;
 
-                            MethodInfo setMethod = property.SetMethod;
+                            MethodInfo? setMethod = property.SetMethod;
                             if (setMethod == null)
                             {
                                 if (!SetIfGetOnlyCollection(memberContract))
@@ -1017,7 +1024,7 @@ namespace System.Runtime.Serialization
                     }
                     else
                     {
-                        FieldInfo field = member as FieldInfo;
+                        FieldInfo? field = member as FieldInfo;
 
                         bool canSerializeMember;
 
@@ -1040,14 +1047,14 @@ namespace System.Runtime.Serialization
                             DataMember memberContract = new DataMember(member);
 
                             memberContract.Name = DataContract.EncodeLocalName(member.Name);
-                            object[] optionalFields = field.GetCustomAttributes(Globals.TypeOfOptionalFieldAttribute, false);
+                            object[] optionalFields = field!.GetCustomAttributes(Globals.TypeOfOptionalFieldAttribute, false);
                             if (optionalFields == null || optionalFields.Length == 0)
                             {
                                 if (this.IsReference)
                                 {
                                     ThrowInvalidDataContractException(
                                         SR.Format(SR.NonOptionalFieldMemberOnIsReferenceSerializableType,
-                                        DataContract.GetClrTypeFullName(member.DeclaringType),
+                                        DataContract.GetClrTypeFullName(member.DeclaringType!),
                                         member.Name, true), type);
                                 }
                                 memberContract.IsRequired = true;
@@ -1064,11 +1071,12 @@ namespace System.Runtime.Serialization
 
                 Interlocked.MemoryBarrier();
                 _members = tempMembers;
+                Debug.Assert(Members != null);
             }
 
-            private static bool CanSerializeMember(FieldInfo field)
+            private static bool CanSerializeMember(FieldInfo? field)
             {
-                return field != null && !ClassDataContract.IsNonSerializedMember(field.DeclaringType, field.Name);
+                return field != null && !ClassDataContract.IsNonSerializedMember(field.DeclaringType!, field.Name);
             }
 
             private bool SetIfGetOnlyCollection(DataMember memberContract)
@@ -1091,16 +1099,16 @@ namespace System.Runtime.Serialization
                 List<Member> membersInHierarchy = new List<Member>();
                 foreach (DataMember member in members)
                 {
-                    membersInHierarchy.Add(new Member(member, this.StableName.Namespace, baseTypeIndex));
+                    membersInHierarchy.Add(new Member(member, this.StableName!.Namespace, baseTypeIndex));
                 }
-                ClassDataContract currContract = BaseContract;
+                ClassDataContract? currContract = BaseContract;
                 while (currContract != null)
                 {
                     baseTypeIndex++;
 
-                    foreach (DataMember member in currContract.Members)
+                    foreach (DataMember member in currContract.Members!)
                     {
-                        membersInHierarchy.Add(new Member(member, currContract.StableName.Namespace, baseTypeIndex));
+                        membersInHierarchy.Add(new Member(member, currContract.StableName!.Namespace, baseTypeIndex));
                     }
                     currContract = currContract.BaseContract;
                 }
@@ -1179,7 +1187,7 @@ namespace System.Runtime.Serialization
                             for (int i = 0; i < methods.Length; i++)
                             {
                                 MethodInfo method = methods[i];
-                                Type prevAttributeType = null;
+                                Type? prevAttributeType = null;
                                 ParameterInfo[] parameters = method.GetParameters();
                                 if (HasExtensionData && IsValidExtensionDataSetMethod(method, parameters))
                                 {
@@ -1208,6 +1216,8 @@ namespace System.Runtime.Serialization
             {
                 if (method.Name == Globals.ExtensionDataSetExplicitMethod || method.Name == Globals.ExtensionDataSetMethod)
                 {
+                    Debug.Assert(method.DeclaringType != null);
+
                     if (_extensionDataSetMethod != null)
                         ThrowInvalidDataContractException(SR.Format(SR.DuplicateExtensionDataSetMethod, method, _extensionDataSetMethod, DataContract.GetClrTypeFullName(method.DeclaringType)));
                     if (method.ReturnType != Globals.TypeOfVoid)
@@ -1219,10 +1229,12 @@ namespace System.Runtime.Serialization
                 return false;
             }
 
-            private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType)
+            private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo? currentCallback, ref Type? prevAttributeType)
             {
                 if (method.IsDefined(attributeType, false))
                 {
+                    Debug.Assert(method.DeclaringType != null);
+
                     if (currentCallback != null)
                         DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType);
                     else if (prevAttributeType != null)
@@ -1243,23 +1255,23 @@ namespace System.Runtime.Serialization
                 return false;
             }
 
-            internal ClassDataContract BaseContract
+            internal ClassDataContract? BaseContract
             {
                 get { return _baseContract; }
                 set
                 {
                     _baseContract = value;
                     if (_baseContract != null && IsValueType)
-                        ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName.Name, StableName.Namespace, _baseContract.StableName.Name, _baseContract.StableName.Namespace));
+                        ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName!.Name, StableName.Namespace, _baseContract.StableName!.Name, _baseContract.StableName.Namespace));
                 }
             }
 
-            internal List<DataMember> Members
+            internal List<DataMember>? Members
             {
                 get { return _members; }
             }
 
-            internal MethodInfo OnSerializing
+            internal MethodInfo? OnSerializing
             {
                 get
                 {
@@ -1268,7 +1280,7 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            internal MethodInfo OnSerialized
+            internal MethodInfo? OnSerialized
             {
                 get
                 {
@@ -1277,7 +1289,7 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            internal MethodInfo OnDeserializing
+            internal MethodInfo? OnDeserializing
             {
                 get
                 {
@@ -1286,7 +1298,7 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            internal MethodInfo OnDeserialized
+            internal MethodInfo? OnDeserialized
             {
                 get
                 {
@@ -1295,7 +1307,7 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            internal MethodInfo ExtensionDataSetMethod
+            internal MethodInfo? ExtensionDataSetMethod
             {
                 get
                 {
@@ -1304,7 +1316,7 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            internal override DataContractDictionary KnownDataContracts
+            internal override DataContractDictionary? KnownDataContracts
             {
                 get
                 {
@@ -1361,14 +1373,14 @@ namespace System.Runtime.Serialization
                     _isKeyValuePairAdapter = true;
                     _keyValuePairGenericArguments = type.GetGenericArguments();
                     _keyValuePairCtorInfo = type.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfKeyValuePair.MakeGenericType(_keyValuePairGenericArguments) });
-                    _getKeyValuePairMethodInfo = type.GetMethod("GetKeyValuePair", Globals.ScanAllMembers);
+                    _getKeyValuePairMethodInfo = type.GetMethod("GetKeyValuePair", Globals.ScanAllMembers)!;
                 }
             }
 
             private bool _isKeyValuePairAdapter;
-            private Type[] _keyValuePairGenericArguments;
-            private ConstructorInfo _keyValuePairCtorInfo;
-            private MethodInfo _getKeyValuePairMethodInfo;
+            private Type[]? _keyValuePairGenericArguments;
+            private ConstructorInfo? _keyValuePairCtorInfo;
+            private MethodInfo? _getKeyValuePairMethodInfo;
 
             internal bool IsKeyValuePairAdapter
             {
@@ -1380,34 +1392,34 @@ namespace System.Runtime.Serialization
                 get { return _isScriptObject; }
             }
 
-            internal Type[] KeyValuePairGenericArguments
+            internal Type[]? KeyValuePairGenericArguments
             {
                 get { return _keyValuePairGenericArguments; }
             }
 
-            internal ConstructorInfo KeyValuePairAdapterConstructorInfo
+            internal ConstructorInfo? KeyValuePairAdapterConstructorInfo
             {
                 get { return _keyValuePairCtorInfo; }
             }
 
-            internal MethodInfo GetKeyValuePairMethodInfo
+            internal MethodInfo? GetKeyValuePairMethodInfo
             {
                 get { return _getKeyValuePairMethodInfo; }
             }
 
-            internal ConstructorInfo GetISerializableConstructor()
+            internal ConstructorInfo? GetISerializableConstructor()
             {
                 if (!IsISerializable)
                     return null;
 
-                ConstructorInfo ctor = UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, SerInfoCtorArgs, null);
+                ConstructorInfo? ctor = UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, SerInfoCtorArgs, null);
                 if (ctor == null)
                     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(UnderlyingType))));
 
                 return ctor;
             }
 
-            internal ConstructorInfo GetNonAttributedTypeConstructor()
+            internal ConstructorInfo? GetNonAttributedTypeConstructor()
             {
                 if (!this.IsNonAttributedType)
                     return null;
@@ -1417,26 +1429,26 @@ namespace System.Runtime.Serialization
                 if (type.IsValueType)
                     return null;
 
-                ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>());
+                ConstructorInfo? ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>());
                 if (ctor == null)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type))));
 
                 return ctor;
             }
 
-            internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate
+            internal XmlFormatClassWriterDelegate? XmlFormatWriterDelegate
             {
                 get { return _xmlFormatWriterDelegate; }
                 set { _xmlFormatWriterDelegate = value; }
             }
 
-            internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate
+            internal XmlFormatClassReaderDelegate? XmlFormatReaderDelegate
             {
                 get { return _xmlFormatReaderDelegate; }
                 set { _xmlFormatReaderDelegate = value; }
             }
 
-            public XmlDictionaryString[] ChildElementNamespaces
+            public XmlDictionaryString?[]? ChildElementNamespaces
             {
                 get { return _childElementNamespaces; }
                 set { _childElementNamespaces = value; }
@@ -1516,9 +1528,9 @@ namespace System.Runtime.Serialization
 
         internal class DataMemberComparer : IComparer<DataMember>
         {
-            public int Compare(DataMember x, DataMember y)
+            public int Compare(DataMember? x, DataMember? y)
             {
-                int orderCompare = x.Order - y.Order;
+                int orderCompare = x!.Order - y!.Order;
                 if (orderCompare != 0)
                     return orderCompare;
 
index 9cbf641..42bee7c 100644 (file)
@@ -11,12 +11,13 @@ using System.Reflection.Emit;
 using System.IO;
 using System.Security;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization
 {
     internal class CodeGenerator
     {
-        private static MethodInfo s_getTypeFromHandle;
+        private static MethodInfo? s_getTypeFromHandle;
         private static MethodInfo GetTypeFromHandle
         {
             get
@@ -30,7 +31,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_objectEquals;
+        private static MethodInfo? s_objectEquals;
         private static MethodInfo ObjectEquals
         {
             get
@@ -44,7 +45,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_arraySetValue;
+        private static MethodInfo? s_arraySetValue;
         private static MethodInfo ArraySetValue
         {
             get
@@ -58,7 +59,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_objectToString;
+        private static MethodInfo? s_objectToString;
         private static MethodInfo ObjectToString
         {
             get
@@ -72,7 +73,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_stringFormat;
+        private static MethodInfo? s_stringFormat;
         private static MethodInfo StringFormat
         {
             get
@@ -86,7 +87,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private Type _delegateType;
+        private Type _delegateType = null!; // initialized in BeginMethod
 
 #if USE_REFEMIT
         AssemblyBuilder assemblyBuilder;
@@ -95,7 +96,7 @@ namespace System.Runtime.Serialization
         static int typeCounter;
         MethodBuilder methodBuilder;
 #else
-        private static Module s_serializationModule;
+        private static Module? s_serializationModule;
         private static Module SerializationModule
         {
             get
@@ -107,19 +108,19 @@ namespace System.Runtime.Serialization
                 return s_serializationModule;
             }
         }
-        private DynamicMethod _dynamicMethod;
+        private DynamicMethod _dynamicMethod = null!; // initialized in BeginMethod
 #endif
 
-        private ILGenerator _ilGen;
-        private List<ArgBuilder> _argList;
-        private Stack<object> _blockStack;
+        private ILGenerator _ilGen = null!; // initialized in BeginMethod
+        private List<ArgBuilder> _argList = null!; // initialized in BeginMethod
+        private Stack<object> _blockStack = null!; // initialized in BeginMethod
         private Label _methodEndLabel;
 
         private readonly Dictionary<LocalBuilder, string> _localNames = new Dictionary<LocalBuilder, string>();
 
         private enum CodeGenTrace { None, Save, Tron };
         private readonly CodeGenTrace _codeGenTrace;
-        private LocalBuilder _stringFormatArray;
+        private LocalBuilder? _stringFormatArray;
 
         internal CodeGenerator()
         {
@@ -140,7 +141,7 @@ namespace System.Runtime.Serialization
 
         internal void BeginMethod(string methodName, Type delegateType, bool allowPrivateMemberAccess)
         {
-            MethodInfo signature = delegateType.GetMethod("Invoke");
+            MethodInfo signature = delegateType.GetMethod("Invoke")!;
             ParameterInfo[] parameters = signature.GetParameters();
             Type[] paramTypes = new Type[parameters.Length];
             for (int i = 0; i < parameters.Length; i++)
@@ -184,7 +185,7 @@ namespace System.Runtime.Serialization
                 EmitSourceLabel("} End method");
             Ret();
 
-            Delegate retVal = null;
+            Delegate? retVal = null;
 #if USE_REFEMIT
             Type type = typeBuilder.CreateType();
             MethodInfo method = type.GetMethod(methodBuilder.Name);
@@ -192,13 +193,13 @@ namespace System.Runtime.Serialization
             methodBuilder = null;
 #else
             retVal = _dynamicMethod.CreateDelegate(_delegateType);
-            _dynamicMethod = null;
+            _dynamicMethod = null!;
 #endif
-            _delegateType = null;
+            _delegateType = null!;
 
-            _ilGen = null;
-            _blockStack = null;
-            _argList = null;
+            _ilGen = null!;
+            _blockStack = null!;
+            _argList = null!;
             return retVal;
         }
 
@@ -259,7 +260,7 @@ namespace System.Runtime.Serialization
             Store(local);
         }
 
-        internal object For(LocalBuilder local, object start, object end)
+        internal object For(LocalBuilder? local, object? start, object? end)
         {
             ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end);
             if (forState.Index != null)
@@ -276,7 +277,7 @@ namespace System.Runtime.Serialization
         internal void EndFor()
         {
             object stackTop = _blockStack.Pop();
-            ForState forState = stackTop as ForState;
+            ForState? forState = stackTop as ForState;
             if (forState == null)
                 ThrowMismatchException(stackTop);
 
@@ -289,7 +290,7 @@ namespace System.Runtime.Serialization
                 MarkLabel(forState.TestLabel);
                 Ldloc(forState.Index);
                 Load(forState.End);
-                if (GetVariableType(forState.End).IsArray)
+                if (GetVariableType(forState.End!).IsArray)
                     Ldlen();
                 Blt(forState.BeginLabel);
             }
@@ -313,7 +314,7 @@ namespace System.Runtime.Serialization
         {
             foreach (object block in _blockStack)
             {
-                ForState forState = block as ForState;
+                ForState? forState = block as ForState;
                 if (forState != null && (object)forState == userForState)
                 {
                     if (!forState.RequiresEndLabel)
@@ -347,13 +348,13 @@ namespace System.Runtime.Serialization
         internal void EndForEach(MethodInfo moveNextMethod)
         {
             object stackTop = _blockStack.Pop();
-            ForState forState = stackTop as ForState;
+            ForState? forState = stackTop as ForState;
             if (forState == null)
                 ThrowMismatchException(stackTop);
 
             MarkLabel(forState.TestLabel);
 
-            object enumerator = forState.End;
+            object? enumerator = forState.End;
             Call(enumerator, moveNextMethod);
 
 
@@ -424,7 +425,7 @@ namespace System.Runtime.Serialization
         }
 
 
-        internal void If(object value1, Cmp cmpOp, object value2)
+        internal void If(object value1, Cmp cmpOp, object? value2)
         {
             Load(value1);
             Load(value2);
@@ -469,14 +470,14 @@ namespace System.Runtime.Serialization
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ParameterCountMismatch, methodInfo.Name, methodInfo.GetParameters().Length, expectedCount)));
         }
 
-        internal void Call(object thisObj, MethodInfo methodInfo)
+        internal void Call(object? thisObj, MethodInfo methodInfo)
         {
             VerifyParameterCount(methodInfo, 0);
             LoadThis(thisObj, methodInfo);
             Call(methodInfo);
         }
 
-        internal void Call(object thisObj, MethodInfo methodInfo, object param1)
+        internal void Call(object? thisObj, MethodInfo methodInfo, object? param1)
         {
             VerifyParameterCount(methodInfo, 1);
             LoadThis(thisObj, methodInfo);
@@ -484,7 +485,7 @@ namespace System.Runtime.Serialization
             Call(methodInfo);
         }
 
-        internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2)
+        internal void Call(object? thisObj, MethodInfo methodInfo, object? param1, object? param2)
         {
             VerifyParameterCount(methodInfo, 2);
             LoadThis(thisObj, methodInfo);
@@ -493,7 +494,7 @@ namespace System.Runtime.Serialization
             Call(methodInfo);
         }
 
-        internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3)
+        internal void Call(object? thisObj, MethodInfo methodInfo, object? param1, object? param2, object? param3)
         {
             VerifyParameterCount(methodInfo, 3);
             LoadThis(thisObj, methodInfo);
@@ -503,7 +504,7 @@ namespace System.Runtime.Serialization
             Call(methodInfo);
         }
 
-        internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4)
+        internal void Call(object? thisObj, MethodInfo methodInfo, object? param1, object? param2, object? param3, object? param4)
         {
             VerifyParameterCount(methodInfo, 4);
             LoadThis(thisObj, methodInfo);
@@ -514,7 +515,7 @@ namespace System.Runtime.Serialization
             Call(methodInfo);
         }
 
-        internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5)
+        internal void Call(object? thisObj, MethodInfo methodInfo, object? param1, object? param2, object? param3, object? param4, object? param5)
         {
             VerifyParameterCount(methodInfo, 5);
             LoadThis(thisObj, methodInfo);
@@ -526,7 +527,7 @@ namespace System.Runtime.Serialization
             Call(methodInfo);
         }
 
-        internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5, object param6)
+        internal void Call(object? thisObj, MethodInfo methodInfo, object? param1, object? param2, object? param3, object? param4, object? param5, object? param6)
         {
             VerifyParameterCount(methodInfo, 6);
             LoadThis(thisObj, methodInfo);
@@ -541,7 +542,7 @@ namespace System.Runtime.Serialization
 
         internal void Call(MethodInfo methodInfo)
         {
-            if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType)
+            if (methodInfo.IsVirtual && !methodInfo.DeclaringType!.IsValueType)
             {
                 if (_codeGenTrace != CodeGenTrace.None)
                     EmitSourceInstruction("Callvirt " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
@@ -550,13 +551,13 @@ namespace System.Runtime.Serialization
             else if (methodInfo.IsStatic)
             {
                 if (_codeGenTrace != CodeGenTrace.None)
-                    EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
+                    EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType!.ToString());
                 _ilGen.Emit(OpCodes.Call, methodInfo);
             }
             else
             {
                 if (_codeGenTrace != CodeGenTrace.None)
-                    EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
+                    EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType!.ToString());
                 _ilGen.Emit(OpCodes.Call, methodInfo);
             }
         }
@@ -564,14 +565,14 @@ namespace System.Runtime.Serialization
         internal void Call(ConstructorInfo ctor)
         {
             if (_codeGenTrace != CodeGenTrace.None)
-                EmitSourceInstruction("Call " + ctor.ToString() + " on type " + ctor.DeclaringType.ToString());
+                EmitSourceInstruction("Call " + ctor.ToString() + " on type " + ctor.DeclaringType!.ToString());
             _ilGen.Emit(OpCodes.Call, ctor);
         }
 
         internal void New(ConstructorInfo constructorInfo)
         {
             if (_codeGenTrace != CodeGenTrace.None)
-                EmitSourceInstruction("Newobj " + constructorInfo.ToString() + " on type " + constructorInfo.DeclaringType.ToString());
+                EmitSourceInstruction("Newobj " + constructorInfo.ToString() + " on type " + constructorInfo.DeclaringType!.ToString());
             _ilGen.Emit(OpCodes.Newobj, constructorInfo);
         }
 
@@ -591,9 +592,9 @@ namespace System.Runtime.Serialization
             _ilGen.Emit(OpCodes.Newarr, elementType);
         }
 
-        internal void LoadArrayElement(object obj, object arrayIndex)
+        internal void LoadArrayElement(object obj, object? arrayIndex)
         {
-            Type objType = GetVariableType(obj).GetElementType();
+            Type objType = GetVariableType(obj).GetElementType()!;
             Load(obj);
             Load(arrayIndex);
             if (IsStruct(objType))
@@ -614,7 +615,7 @@ namespace System.Runtime.Serialization
             }
             else
             {
-                Type objType = arrayType.GetElementType();
+                Type objType = arrayType.GetElementType()!;
                 Load(obj);
                 Load(arrayIndex);
                 if (IsStruct(objType))
@@ -635,7 +636,7 @@ namespace System.Runtime.Serialization
 
         internal Type LoadMember(MemberInfo memberInfo)
         {
-            Type memberType = null;
+            Type? memberType = null;
             if (memberInfo is FieldInfo)
             {
                 FieldInfo fieldInfo = (FieldInfo)memberInfo;
@@ -653,13 +654,12 @@ namespace System.Runtime.Serialization
                     _ilGen.Emit(OpCodes.Ldfld, fieldInfo);
                 }
             }
-            else if (memberInfo is PropertyInfo)
+            else if (memberInfo is PropertyInfo property)
             {
-                PropertyInfo property = memberInfo as PropertyInfo;
                 memberType = property.PropertyType;
                 if (property != null)
                 {
-                    MethodInfo getMethod = property.GetMethod;
+                    MethodInfo? getMethod = property.GetMethod;
                     if (getMethod == null)
                         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property)));
                     Call(getMethod);
@@ -698,10 +698,10 @@ namespace System.Runtime.Serialization
             }
             else if (memberInfo is PropertyInfo)
             {
-                PropertyInfo property = memberInfo as PropertyInfo;
+                PropertyInfo? property = memberInfo as PropertyInfo;
                 if (property != null)
                 {
-                    MethodInfo setMethod = property.SetMethod;
+                    MethodInfo? setMethod = property.SetMethod;
                     if (setMethod == null)
                         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property)));
                     Call(setMethod);
@@ -755,7 +755,7 @@ namespace System.Runtime.Serialization
                 Load(null);
         }
 
-        internal void Load(object obj)
+        internal void Load(object? obj)
         {
             if (obj == null)
             {
@@ -860,7 +860,7 @@ namespace System.Runtime.Serialization
             if (!opCode.Equals(OpCodes.Nop))
             {
                 if (_codeGenTrace != CodeGenTrace.None)
-                    EmitSourceInstruction(opCode.ToString());
+                    EmitSourceInstruction(opCode.ToString()!);
                 _ilGen.Emit(opCode);
             }
             else
@@ -1134,7 +1134,7 @@ namespace System.Runtime.Serialization
                 if (opCode.Equals(OpCodes.Nop))
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported_GeneratingCode, DataContract.GetClrTypeFullName(arrayElementType))));
                 if (_codeGenTrace != CodeGenTrace.None)
-                    EmitSourceInstruction(opCode.ToString());
+                    EmitSourceInstruction(opCode.ToString()!);
                 _ilGen.Emit(opCode);
                 EmitStackTop(arrayElementType);
             }
@@ -1143,7 +1143,7 @@ namespace System.Runtime.Serialization
         {
             OpCode opCode = OpCodes.Ldelema;
             if (_codeGenTrace != CodeGenTrace.None)
-                EmitSourceInstruction(opCode.ToString());
+                EmitSourceInstruction(opCode.ToString()!);
             _ilGen.Emit(opCode, arrayElementType);
 
             EmitStackTop(arrayElementType);
@@ -1179,7 +1179,7 @@ namespace System.Runtime.Serialization
                 if (opCode.Equals(OpCodes.Nop))
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported_GeneratingCode, DataContract.GetClrTypeFullName(arrayElementType))));
                 if (_codeGenTrace != CodeGenTrace.None)
-                    EmitSourceInstruction(opCode.ToString());
+                    EmitSourceInstruction(opCode.ToString()!);
                 EmitStackTop(arrayElementType);
                 _ilGen.Emit(opCode);
             }
@@ -1282,16 +1282,16 @@ namespace System.Runtime.Serialization
             _ilGen.Emit(OpCodes.Dup);
         }
 
-        private void LoadThis(object thisObj, MethodInfo methodInfo)
+        private void LoadThis(object? thisObj, MethodInfo methodInfo)
         {
             if (thisObj != null && !methodInfo.IsStatic)
             {
                 LoadAddress(thisObj);
-                ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType);
+                ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType!);
             }
         }
 
-        private void LoadParam(object arg, int oneBasedArgIndex, MethodBase methodInfo)
+        private void LoadParam(object? arg, int oneBasedArgIndex, MethodBase methodInfo)
         {
             Load(arg);
             if (arg != null)
@@ -1342,7 +1342,7 @@ namespace System.Runtime.Serialization
                     else
                     {
                         if (_codeGenTrace != CodeGenTrace.None)
-                            EmitSourceInstruction(opCode.ToString());
+                            EmitSourceInstruction(opCode.ToString()!);
                         _ilGen.Emit(opCode);
                     }
                 }
@@ -1379,7 +1379,7 @@ namespace System.Runtime.Serialization
         private IfState PopIfState()
         {
             object stackTop = _blockStack.Pop();
-            IfState ifState = stackTop as IfState;
+            IfState? ifState = stackTop as IfState;
             if (ifState == null)
                 ThrowMismatchException(stackTop);
             return ifState;
@@ -1396,6 +1396,7 @@ namespace System.Runtime.Serialization
         }
 #endif
 
+        [DoesNotReturn]
         private void ThrowMismatchException(object expected)
         {
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExpectingEnd, expected.ToString())));
@@ -1443,7 +1444,7 @@ namespace System.Runtime.Serialization
         internal void EndCase()
         {
             object stackTop = _blockStack.Peek();
-            SwitchState switchState = stackTop as SwitchState;
+            SwitchState? switchState = stackTop as SwitchState;
             if (switchState == null)
                 ThrowMismatchException(stackTop);
             Br(switchState.EndOfSwitchLabel);
@@ -1454,7 +1455,7 @@ namespace System.Runtime.Serialization
         internal void EndSwitch()
         {
             object stackTop = _blockStack.Pop();
-            SwitchState switchState = stackTop as SwitchState;
+            SwitchState? switchState = stackTop as SwitchState;
             if (switchState == null)
                 ThrowMismatchException(stackTop);
             if (_codeGenTrace != CodeGenTrace.None)
@@ -1464,7 +1465,7 @@ namespace System.Runtime.Serialization
             MarkLabel(switchState.EndOfSwitchLabel);
         }
 
-        private static readonly MethodInfo s_stringLength = typeof(string).GetProperty("Length").GetMethod;
+        private static readonly MethodInfo s_stringLength = typeof(string).GetProperty("Length")!.GetMethod!;
         internal void ElseIfIsEmptyString(LocalBuilder strLocal)
         {
             IfState ifState = (IfState)_blockStack.Pop();
@@ -1548,14 +1549,14 @@ namespace System.Runtime.Serialization
 
     internal class ForState
     {
-        private readonly LocalBuilder _indexVar;
+        private readonly LocalBuilder? _indexVar;
         private readonly Label _beginLabel;
         private readonly Label _testLabel;
         private Label _endLabel;
         private bool _requiresEndLabel;
-        private readonly object _end;
+        private readonly object? _end;
 
-        internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end)
+        internal ForState(LocalBuilder? indexVar, Label beginLabel, Label testLabel, object? end)
         {
             _indexVar = indexVar;
             _beginLabel = beginLabel;
@@ -1563,7 +1564,7 @@ namespace System.Runtime.Serialization
             _end = end;
         }
 
-        internal LocalBuilder Index
+        internal LocalBuilder? Index
         {
             get
             {
@@ -1611,7 +1612,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal object End
+        internal object? End
         {
             get
             {
index c62688c..7c23c21 100644 (file)
@@ -15,6 +15,7 @@ namespace System.Runtime.Serialization
     using System.Linq;
     using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
     using System.Security;
+    using System.Diagnostics.CodeAnalysis;
 
     // The interface is a perf optimization.
     // Only KeyValuePairAdapter should implement the interface.
@@ -70,8 +71,8 @@ namespace System.Runtime.Serialization
     internal interface IKeyValue
 #endif
     {
-        object Key { get; set; }
-        object Value { get; set; }
+        object? Key { get; set; }
+        object? Value { get; set; }
     }
 
     [DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
@@ -104,16 +105,16 @@ namespace System.Runtime.Serialization
             set { _value = value; }
         }
 
-        object IKeyValue.Key
+        object? IKeyValue.Key
         {
             get { return _key; }
-            set { _key = (K)value; }
+            set { _key = (K)value!; }
         }
 
-        object IKeyValue.Value
+        object? IKeyValue.Value
         {
             get { return _value; }
-            set { _value = (V)value; }
+            set { _value = (V)value!; }
         }
     }
 
@@ -139,35 +140,30 @@ namespace System.Runtime.Serialization
     {
         private XmlDictionaryString _collectionItemName;
 
-        private XmlDictionaryString _childElementNamespace;
+        private XmlDictionaryString? _childElementNamespace;
 
-        private DataContract _itemContract;
+        private DataContract? _itemContract;
 
         private CollectionDataContractCriticalHelper _helper;
 
-        public CollectionDataContract(CollectionKind kind) : base(new CollectionDataContractCriticalHelper(kind))
-        {
-            InitCollectionDataContract(this);
-        }
-
         internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type))
         {
             InitCollectionDataContract(this);
         }
 
-        private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string deserializationExceptionMessage)
+        private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string? deserializationExceptionMessage)
                     : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage))
         {
             InitCollectionDataContract(GetSharedTypeContract(type));
         }
 
-        private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor)
+        private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor)
                     : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor))
         {
             InitCollectionDataContract(GetSharedTypeContract(type));
         }
 
-        private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
+        private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor, bool isConstructorCheckRequired)
                     : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired))
         {
             InitCollectionDataContract(GetSharedTypeContract(type));
@@ -178,9 +174,11 @@ namespace System.Runtime.Serialization
             InitCollectionDataContract(GetSharedTypeContract(type));
         }
 
-        private void InitCollectionDataContract(DataContract sharedTypeContract)
+        [MemberNotNull(nameof(_helper))]
+        [MemberNotNull(nameof(_collectionItemName))]
+        private void InitCollectionDataContract(DataContract? sharedTypeContract)
         {
-            _helper = base.Helper as CollectionDataContractCriticalHelper;
+            _helper = (base.Helper as CollectionDataContractCriticalHelper)!;
             _collectionItemName = _helper.CollectionItemName;
             if (_helper.Kind == CollectionKind.Dictionary || _helper.Kind == CollectionKind.GenericDictionary)
             {
@@ -222,7 +220,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal DataContract SharedTypeContract
+        internal DataContract? SharedTypeContract
         {
             get
             { return _helper.SharedTypeContract; }
@@ -243,7 +241,7 @@ namespace System.Runtime.Serialization
             set { _collectionItemName = value; }
         }
 
-        public string KeyName
+        public string? KeyName
         {
             get
             { return _helper.KeyName; }
@@ -252,7 +250,7 @@ namespace System.Runtime.Serialization
             { _helper.KeyName = value; }
         }
 
-        public string ValueName
+        public string? ValueName
         {
             get
             { return _helper.ValueName; }
@@ -266,7 +264,7 @@ namespace System.Runtime.Serialization
             get { return KeyName != null; }
         }
 
-        public XmlDictionaryString ChildElementNamespace
+        public XmlDictionaryString? ChildElementNamespace
         {
             get
             {
@@ -278,7 +276,7 @@ namespace System.Runtime.Serialization
                         {
                             if (_helper.ChildElementNamespace == null && !IsDictionary)
                             {
-                                XmlDictionaryString tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary());
+                                XmlDictionaryString? tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary());
                                 Interlocked.MemoryBarrier();
                                 _helper.ChildElementNamespace = tempChildElementNamespace;
                             }
@@ -305,25 +303,25 @@ namespace System.Runtime.Serialization
             { _helper.IsConstructorCheckRequired = value; }
         }
 
-        internal MethodInfo GetEnumeratorMethod
+        internal MethodInfo? GetEnumeratorMethod
         {
             get
             { return _helper.GetEnumeratorMethod; }
         }
 
-        internal MethodInfo AddMethod
+        internal MethodInfo? AddMethod
         {
             get
             { return _helper.AddMethod; }
         }
 
-        internal ConstructorInfo Constructor
+        internal ConstructorInfo? Constructor
         {
             get
             { return _helper.Constructor; }
         }
 
-        public override DataContractDictionary KnownDataContracts
+        public override DataContractDictionary? KnownDataContracts
         {
             get
             { return _helper.KnownDataContracts; }
@@ -332,13 +330,13 @@ namespace System.Runtime.Serialization
             { _helper.KnownDataContracts = value; }
         }
 
-        internal string InvalidCollectionInSharedContractMessage
+        internal string? InvalidCollectionInSharedContractMessage
         {
             get
             { return _helper.InvalidCollectionInSharedContractMessage; }
         }
 
-        internal string DeserializationExceptionMessage
+        internal string? DeserializationExceptionMessage
         {
             get { return _helper.DeserializationExceptionMessage; }
         }
@@ -470,28 +468,29 @@ namespace System.Runtime.Serialization
 
         private class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper
         {
-            private static Type[] s_knownInterfaces;
+            private static Type[]? s_knownInterfaces;
 
-            private Type _itemType;
+            private Type _itemType = null!; // _itemType is always set except for the "invalid" CollectionDataContract
             private bool _isItemTypeNullable;
             private CollectionKind _kind;
-            private readonly MethodInfo _getEnumeratorMethod, _addMethod;
-            private readonly ConstructorInfo _constructor;
-            private readonly string _deserializationExceptionMessage;
-            private DataContract _itemContract;
-            private DataContract _sharedTypeContract;
-            private DataContractDictionary _knownDataContracts;
+            private readonly MethodInfo? _getEnumeratorMethod;
+            private readonly MethodInfo? _addMethod;
+            private readonly ConstructorInfo? _constructor;
+            private readonly string? _deserializationExceptionMessage;
+            private DataContract? _itemContract;
+            private DataContract? _sharedTypeContract;
+            private DataContractDictionary? _knownDataContracts;
             private bool _isKnownTypeAttributeChecked;
-            private string _itemName;
+            private string _itemName = null!; // _itemName is always set except for the "invalid" CollectionDataContract
             private bool _itemNameSetExplicit;
-            private XmlDictionaryString _collectionItemName;
-            private string _keyName;
-            private string _valueName;
-            private XmlDictionaryString _childElementNamespace;
-            private readonly string _invalidCollectionInSharedContractMessage;
-            private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate;
-            private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate;
-            private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate;
+            private XmlDictionaryString _collectionItemName = null!; // _itemName is always set except for the "invalid" CollectionDataContract
+            private string? _keyName;
+            private string? _valueName;
+            private XmlDictionaryString? _childElementNamespace;
+            private readonly string? _invalidCollectionInSharedContractMessage;
+            private XmlFormatCollectionReaderDelegate? _xmlFormatReaderDelegate;
+            private XmlFormatGetOnlyCollectionReaderDelegate? _xmlFormatGetOnlyCollectionReaderDelegate;
+            private XmlFormatCollectionWriterDelegate? _xmlFormatWriterDelegate;
             private bool _isConstructorCheckRequired;
 
             internal static Type[] KnownInterfaces
@@ -517,7 +516,7 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute)
+            private void Init(CollectionKind kind, Type? itemType, CollectionDataContractAttribute? collectionContractAttribute)
             {
                 _kind = kind;
                 if (itemType != null)
@@ -526,7 +525,7 @@ namespace System.Runtime.Serialization
                     _isItemTypeNullable = DataContract.IsTypeNullable(itemType);
 
                     bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary);
-                    string itemName = null, keyName = null, valueName = null;
+                    string? itemName = null, keyName = null, valueName = null;
                     if (collectionContractAttribute != null)
                     {
                         if (collectionContractAttribute.IsItemNameSetExplicitly)
@@ -571,12 +570,6 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            internal CollectionDataContractCriticalHelper(CollectionKind kind)
-                : base()
-            {
-                Init(kind, null, null);
-            }
-
             // array
             internal CollectionDataContractCriticalHelper(Type type) : base(type)
             {
@@ -589,7 +582,7 @@ namespace System.Runtime.Serialization
             }
 
             // read-only collection
-            internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string deserializationExceptionMessage)
+            internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string? deserializationExceptionMessage)
                 : base(type)
             {
                 if (getEnumeratorMethod == null)
@@ -597,7 +590,7 @@ namespace System.Runtime.Serialization
                 if (itemType == null)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, GetClrTypeFullName(type))));
 
-                CollectionDataContractAttribute collectionContractAttribute;
+                CollectionDataContractAttribute? collectionContractAttribute;
                 this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute);
 
                 Init(kind, itemType, collectionContractAttribute);
@@ -606,7 +599,7 @@ namespace System.Runtime.Serialization
             }
 
             // collection
-            internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(type)
+            internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor) : base(type)
             {
                 if (getEnumeratorMethod == null)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type))));
@@ -615,7 +608,7 @@ namespace System.Runtime.Serialization
                 if (itemType == null)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type))));
 
-                CollectionDataContractAttribute collectionContractAttribute;
+                CollectionDataContractAttribute? collectionContractAttribute;
                 this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute);
 
                 Init(kind, itemType, collectionContractAttribute);
@@ -625,7 +618,7 @@ namespace System.Runtime.Serialization
             }
 
             // collection
-            internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
+            internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor, bool isConstructorCheckRequired)
                 : this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)
             {
                 _isConstructorCheckRequired = isConstructorCheckRequired;
@@ -652,7 +645,7 @@ namespace System.Runtime.Serialization
             {
                 get
                 {
-                    if (_itemContract == null && UnderlyingType != null)
+                    if (_itemContract == null)
                     {
                         if (IsDictionary)
                         {
@@ -662,6 +655,8 @@ namespace System.Runtime.Serialization
                                     SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName),
                                     UnderlyingType);
                             }
+                            Debug.Assert(KeyName != null);
+                            Debug.Assert(ValueName != null);
                             _itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName });
                             // Ensure that DataContract gets added to the static DataContract cache for dictionary items
                             DataContract.GetDataContract(ItemType);
@@ -683,7 +678,7 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            internal DataContract SharedTypeContract
+            internal DataContract? SharedTypeContract
             {
                 get { return _sharedTypeContract; }
                 set { _sharedTypeContract = value; }
@@ -706,13 +701,13 @@ namespace System.Runtime.Serialization
                 get { return _collectionItemName; }
             }
 
-            internal string KeyName
+            internal string? KeyName
             {
                 get { return _keyName; }
                 set { _keyName = value; }
             }
 
-            internal string ValueName
+            internal string? ValueName
             {
                 get { return _valueName; }
                 set { _valueName = value; }
@@ -720,9 +715,9 @@ namespace System.Runtime.Serialization
 
             internal bool IsDictionary => KeyName != null;
 
-            public string DeserializationExceptionMessage => _deserializationExceptionMessage;
+            public string? DeserializationExceptionMessage => _deserializationExceptionMessage;
 
-            public XmlDictionaryString ChildElementNamespace
+            public XmlDictionaryString? ChildElementNamespace
             {
                 get { return _childElementNamespace; }
                 set { _childElementNamespace = value; }
@@ -734,13 +729,13 @@ namespace System.Runtime.Serialization
                 set { _isItemTypeNullable = value; }
             }
 
-            internal MethodInfo GetEnumeratorMethod => _getEnumeratorMethod;
+            internal MethodInfo? GetEnumeratorMethod => _getEnumeratorMethod;
 
-            internal MethodInfo AddMethod => _addMethod;
+            internal MethodInfo? AddMethod => _addMethod;
 
-            internal ConstructorInfo Constructor => _constructor;
+            internal ConstructorInfo? Constructor => _constructor;
 
-            internal override DataContractDictionary KnownDataContracts
+            internal override DataContractDictionary? KnownDataContracts
             {
                 get
                 {
@@ -763,23 +758,23 @@ namespace System.Runtime.Serialization
                 { _knownDataContracts = value; }
             }
 
-            internal string InvalidCollectionInSharedContractMessage => _invalidCollectionInSharedContractMessage;
+            internal string? InvalidCollectionInSharedContractMessage => _invalidCollectionInSharedContractMessage;
 
             internal bool ItemNameSetExplicit => _itemNameSetExplicit;
 
-            internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
+            internal XmlFormatCollectionWriterDelegate? XmlFormatWriterDelegate
             {
                 get { return _xmlFormatWriterDelegate; }
                 set { _xmlFormatWriterDelegate = value; }
             }
 
-            internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
+            internal XmlFormatCollectionReaderDelegate? XmlFormatReaderDelegate
             {
                 get { return _xmlFormatReaderDelegate; }
                 set { _xmlFormatReaderDelegate = value; }
             }
 
-            internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
+            internal XmlFormatGetOnlyCollectionReaderDelegate? XmlFormatGetOnlyCollectionReaderDelegate
             {
                 get { return _xmlFormatGetOnlyCollectionReaderDelegate; }
                 set { _xmlFormatGetOnlyCollectionReaderDelegate = value; }
@@ -787,7 +782,7 @@ namespace System.Runtime.Serialization
 
             private delegate void IncrementCollectionCountDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context);
 
-            private IncrementCollectionCountDelegate _incrementCollectionCountDelegate;
+            private IncrementCollectionCountDelegate? _incrementCollectionCountDelegate;
 
             private static void DummyIncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { }
 
@@ -811,13 +806,13 @@ namespace System.Runtime.Serialization
                         case CollectionKind.GenericList:
                             {
                                 var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(ItemType);
-                                _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>());
+                                _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>())!;
                             }
                             break;
                         case CollectionKind.GenericDictionary:
                             {
                                 var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(ItemType.GetGenericArguments()));
-                                _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>());
+                                _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>())!;
                             }
                             break;
                         default:
@@ -830,7 +825,7 @@ namespace System.Runtime.Serialization
                 _incrementCollectionCountDelegate(xmlWriter, obj, context);
             }
 
-            private static MethodInfo s_buildIncrementCollectionCountDelegateMethod;
+            private static MethodInfo? s_buildIncrementCollectionCountDelegateMethod;
 
             private static MethodInfo BuildIncrementCollectionCountDelegateMethod
             {
@@ -838,7 +833,7 @@ namespace System.Runtime.Serialization
                 {
                     if (s_buildIncrementCollectionCountDelegateMethod == null)
                     {
-                        s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers);
+                        s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers)!;
                     }
 
                     return s_buildIncrementCollectionCountDelegateMethod;
@@ -856,7 +851,7 @@ namespace System.Runtime.Serialization
 
             private delegate IEnumerator CreateGenericDictionaryEnumeratorDelegate(IEnumerator enumerator);
 
-            private CreateGenericDictionaryEnumeratorDelegate _createGenericDictionaryEnumeratorDelegate;
+            private CreateGenericDictionaryEnumeratorDelegate? _createGenericDictionaryEnumeratorDelegate;
 
             internal IEnumerator GetEnumeratorForCollection(object obj)
             {
@@ -866,8 +861,8 @@ namespace System.Runtime.Serialization
                     if (_createGenericDictionaryEnumeratorDelegate == null)
                     {
                         var keyValueTypes = ItemType.GetGenericArguments();
-                        var buildCreateGenericDictionaryEnumerator = BuildCreateGenericDictionaryEnumerato.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]);
-                        _createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty<object>());
+                        MethodInfo buildCreateGenericDictionaryEnumerator = BuildCreateGenericDictionaryEnumerato.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]);
+                        _createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty<object>())!;
                     }
 
                     enumerator = _createGenericDictionaryEnumeratorDelegate(enumerator);
@@ -882,7 +877,10 @@ namespace System.Runtime.Serialization
 
             internal Type GetCollectionElementType()
             {
-                Type enumeratorType = null;
+                Debug.Assert(Kind != CollectionKind.Array, "GetCollectionElementType should not be called on Arrays");
+                Debug.Assert(GetEnumeratorMethod != null, "GetEnumeratorMethod should be non-null for non-Arrays");
+
+                Type? enumeratorType = null;
                 if (Kind == CollectionKind.GenericDictionary)
                 {
                     Type[] keyValueTypes = ItemType.GetGenericArguments();
@@ -897,7 +895,7 @@ namespace System.Runtime.Serialization
                     enumeratorType = GetEnumeratorMethod.ReturnType;
                 }
 
-                MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
+                MethodInfo? getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
                 if (getCurrentMethod == null)
                 {
                     if (enumeratorType.IsInterface)
@@ -922,7 +920,7 @@ namespace System.Runtime.Serialization
                             }
                         }
 
-                        getCurrentMethod = GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
+                        getCurrentMethod = GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!;
                     }
                 }
 
@@ -930,7 +928,7 @@ namespace System.Runtime.Serialization
                 return elementType;
             }
 
-            private static MethodInfo s_buildCreateGenericDictionaryEnumerator;
+            private static MethodInfo? s_buildCreateGenericDictionaryEnumerator;
 
             private static MethodInfo BuildCreateGenericDictionaryEnumerato
             {
@@ -938,7 +936,7 @@ namespace System.Runtime.Serialization
                 {
                     if (s_buildCreateGenericDictionaryEnumerator == null)
                     {
-                        s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers);
+                        s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers)!;
                     }
 
                     return s_buildCreateGenericDictionaryEnumerator;
@@ -954,7 +952,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private DataContract GetSharedTypeContract(Type type)
+        private DataContract? GetSharedTypeContract(Type type)
         {
             if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
             {
@@ -976,39 +974,39 @@ namespace System.Runtime.Serialization
 
         internal static bool IsCollection(Type type)
         {
-            Type itemType;
+            Type? itemType;
             return IsCollection(type, out itemType);
         }
 
-        internal static bool IsCollection(Type type, out Type itemType)
+        internal static bool IsCollection(Type type, [NotNullWhen(true)] out Type? itemType)
         {
             return IsCollectionHelper(type, out itemType, true /*constructorRequired*/);
         }
 
         internal static bool IsCollection(Type type, bool constructorRequired)
         {
-            Type itemType;
+            Type? itemType;
             return IsCollectionHelper(type, out itemType, constructorRequired);
         }
 
-        private static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired)
+        private static bool IsCollectionHelper(Type type, [NotNullWhen(true)] out Type? itemType, bool constructorRequired)
         {
             if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null)
             {
-                itemType = type.GetElementType();
+                itemType = type.GetElementType()!;
                 return true;
             }
-            DataContract dataContract;
+            DataContract? dataContract;
             return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired);
         }
 
-        internal static bool TryCreate(Type type, out DataContract dataContract)
+        internal static bool TryCreate(Type type, [NotNullWhen(true)] out DataContract? dataContract)
         {
             Type itemType;
-            return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, true /*constructorRequired*/);
+            return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract!, out itemType, true /*constructorRequired*/);
         }
 
-        internal static bool CreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
+        internal static bool CreateGetOnlyCollectionDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract)
         {
             Type itemType;
             if (type.IsArray)
@@ -1018,11 +1016,11 @@ namespace System.Runtime.Serialization
             }
             else
             {
-                return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
+                return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract!, out itemType, false /*constructorRequired*/);
             }
         }
 
-        internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
+        internal static bool TryCreateGetOnlyCollectionDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract)
         {
             dataContract = DataContract.GetDataContractFromGeneratedAssembly(type);
             if (dataContract == null)
@@ -1035,7 +1033,7 @@ namespace System.Runtime.Serialization
                 }
                 else
                 {
-                    return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
+                    return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract!, out itemType, false /*constructorRequired*/);
                 }
             }
             else
@@ -1052,9 +1050,9 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType)
+        internal static MethodInfo? GetTargetMethodWithName(string name, Type type, Type interfaceType)
         {
-            Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
+            Type? t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
             return t?.GetMethod(name);
         }
 
@@ -1063,7 +1061,7 @@ namespace System.Runtime.Serialization
             return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
         }
 
-        private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired)
+        private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract? dataContract, out Type itemType, bool constructorRequired)
         {
             dataContract = null;
             itemType = Globals.TypeOfObject;
@@ -1074,11 +1072,11 @@ namespace System.Runtime.Serialization
                     SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract);
             }
 
-            MethodInfo addMethod, getEnumeratorMethod;
+            MethodInfo? addMethod, getEnumeratorMethod;
             bool hasCollectionDataContract = IsCollectionDataContract(type);
             bool isReadOnlyContract = false;
-            string deserializationExceptionMessage = null;
-            Type baseType = type.BaseType;
+            string? deserializationExceptionMessage = null;
+            Type? baseType = type.BaseType;
             bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject
                 && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false;
 
@@ -1118,7 +1116,7 @@ namespace System.Runtime.Serialization
                             {
                                 itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs);
                                 addMethod = type.GetMethod(Globals.AddMethodName);
-                                getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName);
+                                getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName)!;
                             }
                             else
                             {
@@ -1127,7 +1125,7 @@ namespace System.Runtime.Serialization
                                 {
                                     addMethod = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType).GetMethod(Globals.AddMethodName);
                                 }
-                                getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName);
+                                getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName)!;
                             }
                         }
                         else
@@ -1148,7 +1146,7 @@ namespace System.Runtime.Serialization
                                 }
                             }
 
-                            getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName);
+                            getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName)!;
                         }
                         if (tryCreate)
                             dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/);
@@ -1156,7 +1154,7 @@ namespace System.Runtime.Serialization
                     }
                 }
             }
-            ConstructorInfo defaultCtor = null;
+            ConstructorInfo? defaultCtor = null;
             if (!type.IsValueType)
             {
                 defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Array.Empty<Type>(), null);
@@ -1178,7 +1176,7 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            Type knownInterfaceType = null;
+            Type? knownInterfaceType = null;
             CollectionKind kind = CollectionKind.None;
             bool multipleDefinitions = false;
             Type[] interfaceTypes = type.GetInterfaces();
@@ -1210,6 +1208,7 @@ namespace System.Runtime.Serialization
                     SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
             }
 
+            Debug.Assert(knownInterfaceType != null);
             if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable)
             {
                 if (multipleDefinitions)
@@ -1218,6 +1217,9 @@ namespace System.Runtime.Serialization
                 GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType },
                                      false /*addMethodOnInterface*/,
                                      out getEnumeratorMethod, out addMethod);
+
+                Debug.Assert(getEnumeratorMethod != null);
+
                 if (addMethod == null)
                 {
                     // All collection types could be considered read-only collections except collection types that are marked [Serializable].
@@ -1249,7 +1251,7 @@ namespace System.Runtime.Serialization
                     return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException,
                         SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract);
                 }
-                Type[] addMethodTypeArray = null;
+                Type[]? addMethodTypeArray = null;
                 switch (kind)
                 {
                     case CollectionKind.GenericDictionary:
@@ -1275,10 +1277,13 @@ namespace System.Runtime.Serialization
 
                 if (tryCreate)
                 {
+                    Debug.Assert(addMethodTypeArray != null);
                     GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray,
                                      true /*addMethodOnInterface*/,
                                      out getEnumeratorMethod, out addMethod);
 
+                    Debug.Assert(getEnumeratorMethod != null);
+
                     dataContract = isReadOnlyContract ?
                         new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage) :
                         new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
@@ -1293,7 +1298,7 @@ namespace System.Runtime.Serialization
             return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false);
         }
 
-        private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract)
+        private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string? param, ref DataContract? dataContract)
         {
             if (hasCollectionDataContract)
             {
@@ -1312,19 +1317,19 @@ namespace System.Runtime.Serialization
             return false;
         }
 
-        private static void GetReadOnlyCollectionExceptionMessages(Type type, string message, string param, out string deserializationExceptionMessage)
+        private static void GetReadOnlyCollectionExceptionMessages(Type type, string message, string? param, out string deserializationExceptionMessage)
         {
             deserializationExceptionMessage = GetInvalidCollectionMessage(message, SR.Format(SR.ReadOnlyCollectionDeserialization, GetClrTypeFullName(type)), param);
         }
 
-        private static string GetInvalidCollectionMessage(string message, string nestedMessage, string param)
+        private static string GetInvalidCollectionMessage(string message, string nestedMessage, string? param)
         {
             return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param);
         }
 
-        private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod)
+        private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo? addMethod, ref MethodInfo? getEnumeratorMethod)
         {
-            Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
+            Type? t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
             if (t != null)
             {
                 addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod;
@@ -1332,7 +1337,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod)
+        private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo? getEnumeratorMethod, out MethodInfo? addMethod)
         {
             addMethod = getEnumeratorMethod = null;
 
@@ -1374,7 +1379,7 @@ namespace System.Runtime.Serialization
                 getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
                 if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType))
                 {
-                    Type ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault();
+                    Type? ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName!.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault();
                     if (ienumerableInterface == null)
                         ienumerableInterface = Globals.TypeOfIEnumerable;
                     getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface);
@@ -1434,7 +1439,7 @@ namespace System.Runtime.Serialization
         ///          since this information is used to determine whether to give the generated code access
         ///          permissions to private members, any changes to the logic should be reviewed.
         /// </SecurityNote>
-        internal bool RequiresMemberAccessForRead(SecurityException securityException)
+        internal bool RequiresMemberAccessForRead(SecurityException? securityException)
         {
             if (!IsTypeVisible(UnderlyingType))
             {
@@ -1480,7 +1485,7 @@ namespace System.Runtime.Serialization
                            new SecurityException(SR.Format(
                                    SR.PartialTrustCollectionContractAddMethodNotPublic,
                                    DataContract.GetClrTypeFullName(UnderlyingType),
-                                   this.AddMethod.Name),
+                                   this.AddMethod!.Name),
                                securityException));
                 }
                 return true;
@@ -1494,7 +1499,7 @@ namespace System.Runtime.Serialization
         ///          since this information is used to determine whether to give the generated code access
         ///          permissions to private members, any changes to the logic should be reviewed.
         /// </SecurityNote>
-        internal bool RequiresMemberAccessForWrite(SecurityException securityException)
+        internal bool RequiresMemberAccessForWrite(SecurityException? securityException)
         {
             if (!IsTypeVisible(UnderlyingType))
             {
@@ -1524,17 +1529,21 @@ namespace System.Runtime.Serialization
             return false;
         }
 
-        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context)
         {
+            Debug.Assert(context != null);
+
             // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
             context.IsGetOnlyCollection = false;
             XmlFormatWriterDelegate(xmlWriter, obj, context, this);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context)
         {
+            Debug.Assert(context != null);
+
             xmlReader.Read();
-            object o = null;
+            object? o = null;
             if (context.IsGetOnlyCollection)
             {
                 // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
@@ -1549,7 +1558,7 @@ namespace System.Runtime.Serialization
             return o;
         }
 
-        internal class DictionaryEnumerator : IEnumerator<KeyValue<object, object>>
+        internal class DictionaryEnumerator : IEnumerator<KeyValue<object, object?>>
         {
             private readonly IDictionaryEnumerator _enumerator;
 
@@ -1568,9 +1577,9 @@ namespace System.Runtime.Serialization
                 return _enumerator.MoveNext();
             }
 
-            public KeyValue<object, object> Current
+            public KeyValue<object, object?> Current
             {
-                get { return new KeyValue<object, object>(_enumerator.Key, _enumerator.Value); }
+                get { return new KeyValue<object, object?>(_enumerator.Key, _enumerator.Value); }
             }
 
             object System.Collections.IEnumerator.Current
index 935223f..93c069a 100644 (file)
@@ -15,6 +15,8 @@ namespace System.Runtime.Serialization
     using System.Linq;
     using Xml.Schema;
     using System.Collections.Concurrent;
+    using System.Diagnostics.CodeAnalysis;
+    using System.Diagnostics;
 
 #if USE_REFEMIT
     public abstract class DataContract
@@ -43,26 +45,26 @@ namespace System.Runtime.Serialization
             _ns = helper.Namespace;
         }
 
-        private static DataContract GetGeneratedDataContract(Type type)
+        private static DataContract? GetGeneratedDataContract(Type type)
         {
             // this method used to be rewritten by an IL transform
             // with the restructuring for multi-file, it has become a regular method
-            DataContract result;
+            DataContract? result;
             return s_dataContracts.TryGetValue(type, out result) ? result : null;
         }
 
-        internal static bool TryGetDataContractFromGeneratedAssembly(Type type, out DataContract dataContract)
+        internal static bool TryGetDataContractFromGeneratedAssembly(Type type, out DataContract? dataContract)
         {
             dataContract = GetGeneratedDataContract(type);
             return dataContract != null;
         }
 
-        internal static DataContract GetDataContractFromGeneratedAssembly(Type type)
+        internal static DataContract? GetDataContractFromGeneratedAssembly(Type? type)
         {
             return null;
         }
 
-        internal MethodInfo ParseMethod
+        internal MethodInfo? ParseMethod
         {
             get { return _helper.ParseMethod; }
         }
@@ -77,7 +79,7 @@ namespace System.Runtime.Serialization
             return GetDataContract(typeHandle, type, SerializationMode.SharedContract);
         }
 
-        internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
+        internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type? type, SerializationMode mode)
         {
             int id = GetId(typeHandle);
             DataContract dataContract = GetDataContractSkipValidation(id, typeHandle, null);
@@ -90,12 +92,12 @@ namespace System.Runtime.Serialization
             return dataContract.GetValidContract(mode);
         }
 
-        internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
+        internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type)
         {
             return DataContractCriticalHelper.GetDataContractSkipValidation(id, typeHandle, type);
         }
 
-        internal static DataContract GetGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
+        internal static DataContract GetGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type? type, SerializationMode mode)
         {
             DataContract dataContract = GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type);
             dataContract = dataContract.GetValidContract(mode);
@@ -106,7 +108,7 @@ namespace System.Runtime.Serialization
             return dataContract;
         }
 
-        internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
+        internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type)
         {
             return DataContractCriticalHelper.GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type);
         }
@@ -126,17 +128,17 @@ namespace System.Runtime.Serialization
             return DataContractCriticalHelper.GetId(typeHandle);
         }
 
-        public static DataContract GetBuiltInDataContract(Type type)
+        public static DataContract? GetBuiltInDataContract(Type type)
         {
             return DataContractCriticalHelper.GetBuiltInDataContract(type);
         }
 
-        public static DataContract GetBuiltInDataContract(string name, string ns)
+        public static DataContract? GetBuiltInDataContract(string name, string ns)
         {
             return DataContractCriticalHelper.GetBuiltInDataContract(name, ns);
         }
 
-        public static DataContract GetBuiltInDataContract(string typeName)
+        public static DataContract? GetBuiltInDataContract(string typeName)
         {
             return DataContractCriticalHelper.GetBuiltInDataContract(typeName);
         }
@@ -151,7 +153,8 @@ namespace System.Runtime.Serialization
             return DataContractCriticalHelper.GetClrTypeString(key);
         }
 
-        internal static void ThrowInvalidDataContractException(string message, Type type)
+        [DoesNotReturn]
+        internal static void ThrowInvalidDataContractException(string? message, Type? type)
         {
             DataContractCriticalHelper.ThrowInvalidDataContractException(message, type);
         }
@@ -192,17 +195,17 @@ namespace System.Runtime.Serialization
             { return _helper.TypeForInitialization; }
         }
 
-        public virtual void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
+        public virtual void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context)
         {
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
         }
 
-        public virtual object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
+        public virtual object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context)
         {
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
         }
 
-        public virtual void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public virtual void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
         }
@@ -239,7 +242,7 @@ namespace System.Runtime.Serialization
             { _helper.StableName = value; }
         }
 
-        public virtual DataContractDictionary KnownDataContracts
+        public virtual DataContractDictionary? KnownDataContracts
         {
             get
             { return _helper.KnownDataContracts; }
@@ -278,7 +281,7 @@ namespace System.Runtime.Serialization
             { }
         }
 
-        public virtual XmlDictionaryString TopLevelElementName
+        public virtual XmlDictionaryString? TopLevelElementName
         {
             get
             { return _helper.TopLevelElementName; }
@@ -287,7 +290,7 @@ namespace System.Runtime.Serialization
             { _helper.TopLevelElementName = value; }
         }
 
-        public virtual XmlDictionaryString TopLevelElementNamespace
+        public virtual XmlDictionaryString? TopLevelElementNamespace
         {
             get
             { return _helper.TopLevelElementNamespace; }
@@ -306,7 +309,7 @@ namespace System.Runtime.Serialization
             get { return false; }
         }
 
-        internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns)
+        internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString? ns)
         {
             if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace) && !IsPrimitive)
                 writer.WriteStartElement(Globals.SerPrefix, name, ns);
@@ -334,11 +337,11 @@ namespace System.Runtime.Serialization
             private static readonly Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer());
             private static DataContract[] s_dataContractCache = new DataContract[32];
             private static int s_dataContractID;
-            private static Dictionary<Type, DataContract> s_typeToBuiltInContract;
-            private static Dictionary<XmlQualifiedName, DataContract> s_nameToBuiltInContract;
-            private static Dictionary<string, string> s_namespaces;
-            private static Dictionary<string, XmlDictionaryString> s_clrTypeStrings;
-            private static XmlDictionary s_clrTypeStringsDictionary;
+            private static Dictionary<Type, DataContract?>? s_typeToBuiltInContract;
+            private static Dictionary<XmlQualifiedName, DataContract?>? s_nameToBuiltInContract;
+            private static Dictionary<string, string>? s_namespaces;
+            private static Dictionary<string, XmlDictionaryString>? s_clrTypeStrings;
+            private static XmlDictionary? s_clrTypeStringsDictionary;
             private static readonly TypeHandleRef s_typeHandleRef = new TypeHandleRef();
 
             private static readonly object s_cacheLock = new object();
@@ -348,14 +351,14 @@ namespace System.Runtime.Serialization
             private static readonly object s_clrTypeStringsLock = new object();
 
             private Type _underlyingType;
-            private Type _originalUnderlyingType;
+            private Type? _originalUnderlyingType;
             private bool _isReference;
             private bool _isValueType;
-            private XmlQualifiedName _stableName;
-            private XmlDictionaryString _name;
-            private XmlDictionaryString _ns;
+            private XmlQualifiedName _stableName = null!; // StableName is always set in concrete ctors set except for the "invalid" CollectionDataContract
+            private XmlDictionaryString _name = null!; // Name is always set in concrete ctors set except for the "invalid" CollectionDataContract
+            private XmlDictionaryString _ns = null!; // Namespace is always set in concrete ctors set except for the "invalid" CollectionDataContract
 
-            private MethodInfo _parseMethod;
+            private MethodInfo? _parseMethod;
             private bool _parseMethodSet;
 
             /// <SecurityNote>
@@ -363,7 +366,7 @@ namespace System.Runtime.Serialization
             /// </SecurityNote>
             private Type _typeForInitialization;
 
-            internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
+            internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type)
             {
                 DataContract dataContract = s_dataContractCache[id];
                 if (dataContract == null)
@@ -378,7 +381,7 @@ namespace System.Runtime.Serialization
                 return dataContract;
             }
 
-            internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
+            internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type)
             {
                 DataContract dataContract = s_dataContractCache[id];
                 if (dataContract == null)
@@ -401,7 +404,7 @@ namespace System.Runtime.Serialization
 
             internal static int GetIdForInitialization(ClassDataContract classContract)
             {
-                int id = DataContract.GetId(classContract.TypeForInitialization.TypeHandle);
+                int id = DataContract.GetId(classContract.TypeForInitialization!.TypeHandle);
                 if (id < s_dataContractCache.Length && ContractMatches(classContract, s_dataContractCache[id]))
                 {
                     return id;
@@ -426,7 +429,7 @@ namespace System.Runtime.Serialization
             {
                 lock (s_cacheLock)
                 {
-                    IntRef id;
+                    IntRef? id;
                     typeHandle = GetDataContractAdapterTypeHandle(typeHandle);
                     s_typeHandleRef.Value = typeHandle;
                     if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id))
@@ -461,9 +464,9 @@ namespace System.Runtime.Serialization
             }
 
             // check whether a corresponding update is required in ClassDataContract.IsNonAttributedTypeValidForSerialization
-            private static DataContract CreateDataContract(int id, RuntimeTypeHandle typeHandle, Type type)
+            private static DataContract CreateDataContract(int id, RuntimeTypeHandle typeHandle, Type? type)
             {
-                DataContract dataContract = s_dataContractCache[id];
+                DataContract? dataContract = s_dataContractCache[id];
                 if (dataContract == null)
                 {
                     lock (s_createDataContractLock)
@@ -497,7 +500,7 @@ namespace System.Runtime.Serialization
                 Type originalType = type;
                 type = GetDataContractAdapterType(type);
 
-                DataContract dataContract = GetBuiltInDataContract(type);
+                DataContract? dataContract = GetBuiltInDataContract(type);
                 if (dataContract == null)
                 {
                     if (type.IsArray)
@@ -545,9 +548,9 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            private static DataContract CreateGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type type)
+            private static DataContract CreateGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type? type)
             {
-                DataContract dataContract = null;
+                DataContract? dataContract = null;
                 lock (s_createDataContractLock)
                 {
                     dataContract = s_dataContractCache[id];
@@ -602,7 +605,7 @@ namespace System.Runtime.Serialization
                 return typeHandle;
             }
 
-            public static DataContract GetBuiltInDataContract(Type type)
+            public static DataContract? GetBuiltInDataContract(Type type)
             {
                 if (type.IsInterface && !CollectionDataContract.IsCollectionInterface(type))
                     type = Globals.TypeOfObject;
@@ -610,9 +613,9 @@ namespace System.Runtime.Serialization
                 lock (s_initBuiltInContractsLock)
                 {
                     if (s_typeToBuiltInContract == null)
-                        s_typeToBuiltInContract = new Dictionary<Type, DataContract>();
+                        s_typeToBuiltInContract = new Dictionary<Type, DataContract?>();
 
-                    DataContract dataContract = null;
+                    DataContract? dataContract;
                     if (!s_typeToBuiltInContract.TryGetValue(type, out dataContract))
                     {
                         TryCreateBuiltInDataContract(type, out dataContract);
@@ -622,14 +625,14 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            public static DataContract GetBuiltInDataContract(string name, string ns)
+            public static DataContract? GetBuiltInDataContract(string name, string ns)
             {
                 lock (s_initBuiltInContractsLock)
                 {
                     if (s_nameToBuiltInContract == null)
-                        s_nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract>();
+                        s_nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract?>();
 
-                    DataContract dataContract = null;
+                    DataContract? dataContract;
                     XmlQualifiedName qname = new XmlQualifiedName(name, ns);
                     if (!s_nameToBuiltInContract.TryGetValue(qname, out dataContract))
                     {
@@ -640,7 +643,7 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            public static DataContract GetBuiltInDataContract(string typeName)
+            public static DataContract? GetBuiltInDataContract(string typeName)
             {
                 if (!typeName.StartsWith("System.", StringComparison.Ordinal))
                     return null;
@@ -648,13 +651,13 @@ namespace System.Runtime.Serialization
                 lock (s_initBuiltInContractsLock)
                 {
                     if (s_nameToBuiltInContract == null)
-                        s_nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract>();
+                        s_nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract?>();
 
-                    DataContract dataContract = null;
+                    DataContract? dataContract;
                     XmlQualifiedName qname = new XmlQualifiedName(typeName);
                     if (!s_nameToBuiltInContract.TryGetValue(qname, out dataContract))
                     {
-                        Type type = null;
+                        Type? type = null;
                         string name = typeName.Substring(7);
                         if (name == "Char")
                             type = typeof(char);
@@ -718,7 +721,7 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            public static bool TryCreateBuiltInDataContract(Type type, out DataContract dataContract)
+            public static bool TryCreateBuiltInDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract)
             {
                 if (type.IsEnum) // Type.GetTypeCode will report Enums as TypeCode.IntXX
                 {
@@ -799,7 +802,7 @@ namespace System.Runtime.Serialization
                 return dataContract != null;
             }
 
-            public static bool TryCreateBuiltInDataContract(string name, string ns, out DataContract dataContract)
+            public static bool TryCreateBuiltInDataContract(string name, string ns, [NotNullWhen(true)] out DataContract? dataContract)
             {
                 dataContract = null;
                 if (ns == DictionaryGlobals.SchemaNamespace.Value)
@@ -927,7 +930,7 @@ namespace System.Runtime.Serialization
                 {
                     if (s_namespaces == null)
                         s_namespaces = new Dictionary<string, string>();
-                    string value;
+                    string? value;
                     if (s_namespaces.TryGetValue(key, out value))
                         return value;
                     try
@@ -956,7 +959,7 @@ namespace System.Runtime.Serialization
                         s_clrTypeStrings = new Dictionary<string, XmlDictionaryString>();
                         try
                         {
-                            s_clrTypeStrings.Add(Globals.TypeOfInt.Assembly.FullName, s_clrTypeStringsDictionary.Add(Globals.MscorlibAssemblyName));
+                            s_clrTypeStrings.Add(Globals.TypeOfInt.Assembly.FullName!, s_clrTypeStringsDictionary.Add(Globals.MscorlibAssemblyName));
                         }
                         catch (Exception ex)
                         {
@@ -967,10 +970,10 @@ namespace System.Runtime.Serialization
                             throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
                         }
                     }
-                    XmlDictionaryString value;
+                    XmlDictionaryString? value;
                     if (s_clrTypeStrings.TryGetValue(key, out value))
                         return value;
-                    value = s_clrTypeStringsDictionary.Add(key);
+                    value = s_clrTypeStringsDictionary!.Add(key);
                     try
                     {
                         s_clrTypeStrings.Add(key, value);
@@ -987,7 +990,8 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            internal static void ThrowInvalidDataContractException(string message, Type type)
+            [DoesNotReturn]
+            internal static void ThrowInvalidDataContractException(string? message, Type? type)
             {
                 if (type != null)
                 {
@@ -1012,10 +1016,6 @@ namespace System.Runtime.Serialization
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(message));
             }
 
-            internal DataContractCriticalHelper()
-            {
-            }
-
             internal DataContractCriticalHelper(Type type)
             {
                 _underlyingType = type;
@@ -1057,6 +1057,7 @@ namespace System.Runtime.Serialization
                 get { return _typeForInitialization; }
             }
 
+            [MemberNotNull(nameof(_typeForInitialization))]
             private void SetTypeForInitialization(Type classType)
             {
                 //if (classType.IsSerializable || classType.IsDefined(Globals.TypeOfDataContractAttribute, false))
@@ -1086,7 +1087,7 @@ namespace System.Runtime.Serialization
                 set { _stableName = value; }
             }
 
-            internal virtual DataContractDictionary KnownDataContracts
+            internal virtual DataContractDictionary? KnownDataContracts
             {
                 get { return null; }
                 set { /* do nothing */ }
@@ -1116,16 +1117,24 @@ namespace System.Runtime.Serialization
                 set { }
             }
 
-            internal virtual XmlDictionaryString TopLevelElementName
+            internal virtual XmlDictionaryString? TopLevelElementName
             {
                 get { return _name; }
-                set { _name = value; }
+                set
+                {
+                    Debug.Assert(value != null);
+                    _name = value;
+                }
             }
 
-            internal virtual XmlDictionaryString TopLevelElementNamespace
+            internal virtual XmlDictionaryString? TopLevelElementNamespace
             {
                 get { return _ns; }
-                set { _ns = value; }
+                set
+                {
+                    Debug.Assert(value != null);
+                    _ns = value;
+                }
             }
 
             internal virtual bool CanContainReferences
@@ -1138,13 +1147,13 @@ namespace System.Runtime.Serialization
                 get { return false; }
             }
 
-            internal MethodInfo ParseMethod
+            internal MethodInfo? ParseMethod
             {
                 get
                 {
                     if (!_parseMethodSet)
                     {
-                        MethodInfo method = UnderlyingType.GetMethod(Globals.ParseMethodName, BindingFlags.Public | BindingFlags.Static, new Type[] { typeof(string) });
+                        MethodInfo? method = UnderlyingType.GetMethod(Globals.ParseMethodName, BindingFlags.Public | BindingFlags.Static, new Type[] { typeof(string) });
 
                         if (method != null && method.ReturnType == UnderlyingType)
                         {
@@ -1172,6 +1181,7 @@ namespace System.Runtime.Serialization
                 this.StableName = CreateQualifiedName(name.Value, ns.Value);
             }
 
+            [DoesNotReturn]
             internal void ThrowInvalidDataContractException(string message)
             {
                 ThrowInvalidDataContractException(message, UnderlyingType);
@@ -1185,7 +1195,7 @@ namespace System.Runtime.Serialization
 
         private static bool IsTypeSerializable(Type type, HashSet<Type> previousCollectionTypes)
         {
-            Type itemType;
+            Type? itemType;
 
             if (type.IsSerializable ||
                 type.IsEnum ||
@@ -1215,7 +1225,7 @@ namespace System.Runtime.Serialization
             previousCollectionTypes.Add(collectionType);
             while (itemType.IsArray)
             {
-                itemType = itemType.GetElementType();
+                itemType = itemType.GetElementType()!;
             }
             if (previousCollectionTypes.Contains(itemType))
             {
@@ -1307,14 +1317,14 @@ namespace System.Runtime.Serialization
         internal static XmlQualifiedName GetStableName(Type type, out bool hasDataContract)
         {
             type = UnwrapRedundantNullableType(type);
-            XmlQualifiedName stableName;
+            XmlQualifiedName? stableName;
             if (TryGetBuiltInXmlAndArrayTypeStableName(type, out stableName))
             {
                 hasDataContract = false;
             }
             else
             {
-                DataContractAttribute dataContractAttribute;
+                DataContractAttribute? dataContractAttribute;
                 if (TryGetDCAttribute(type, out dataContractAttribute))
                 {
                     stableName = GetDCTypeStableName(type, dataContractAttribute);
@@ -1332,7 +1342,7 @@ namespace System.Runtime.Serialization
 
         private static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttribute dataContractAttribute)
         {
-            string name = null, ns = null;
+            string? name = null, ns = null;
             if (dataContractAttribute.IsNameSetExplicitly)
             {
                 name = dataContractAttribute.Name;
@@ -1360,10 +1370,10 @@ namespace System.Runtime.Serialization
 
         private static XmlQualifiedName GetNonDCTypeStableName(Type type)
         {
-            string name = null, ns = null;
+            string? name = null, ns = null;
 
-            Type itemType;
-            CollectionDataContractAttribute collectionContractAttribute;
+            Type? itemType;
+            CollectionDataContractAttribute? collectionContractAttribute;
             if (CollectionDataContract.IsCollection(type, out itemType))
                 return GetCollectionStableName(type, itemType, out collectionContractAttribute);
             name = GetDefaultStableLocalName(type);
@@ -1380,11 +1390,11 @@ namespace System.Runtime.Serialization
             return CreateQualifiedName(name, ns);
         }
 
-        private static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, out XmlQualifiedName stableName)
+        private static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, [NotNullWhen(true)] out XmlQualifiedName? stableName)
         {
             stableName = null;
 
-            DataContract builtInContract = GetBuiltInDataContract(type);
+            DataContract? builtInContract = GetBuiltInDataContract(type);
             if (builtInContract != null)
             {
                 stableName = builtInContract.StableName;
@@ -1392,20 +1402,20 @@ namespace System.Runtime.Serialization
             else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))
             {
                 bool hasRoot;
-                XmlSchemaType xsdType;
+                XmlSchemaType? xsdType;
                 XmlQualifiedName xmlTypeStableName;
                 SchemaExporter.GetXmlTypeInfo(type, out xmlTypeStableName, out xsdType, out hasRoot);
                 stableName = xmlTypeStableName;
             }
             else if (type.IsArray)
             {
-                CollectionDataContractAttribute collectionContractAttribute;
-                stableName = GetCollectionStableName(type, type.GetElementType(), out collectionContractAttribute);
+                CollectionDataContractAttribute? collectionContractAttribute;
+                stableName = GetCollectionStableName(type, type.GetElementType()!, out collectionContractAttribute);
             }
             return stableName != null;
         }
 
-        internal static bool TryGetDCAttribute(Type type, out DataContractAttribute dataContractAttribute)
+        internal static bool TryGetDCAttribute(Type type, [NotNullWhen(true)] out DataContractAttribute? dataContractAttribute)
         {
             dataContractAttribute = null;
 
@@ -1422,9 +1432,9 @@ namespace System.Runtime.Serialization
             return dataContractAttribute != null;
         }
 
-        internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, out CollectionDataContractAttribute collectionContractAttribute)
+        internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, out CollectionDataContractAttribute? collectionContractAttribute)
         {
-            string name, ns;
+            string? name, ns;
             object[] collectionContractAttributes = type.GetCustomAttributes(Globals.TypeOfCollectionDataContractAttribute, false).ToArray();
             if (collectionContractAttributes != null && collectionContractAttributes.Length > 0)
             {
@@ -1474,7 +1484,7 @@ namespace System.Runtime.Serialization
                 if (DataContract.GetBuiltInDataContract(itemType) != null)
                     break;
                 arrayOfPrefix += Globals.ArrayPrefix;
-                itemType = itemType.GetElementType();
+                itemType = itemType.GetElementType()!;
             }
             return arrayOfPrefix;
         }
@@ -1494,7 +1504,7 @@ namespace System.Runtime.Serialization
             if (type.IsGenericParameter)
                 return "{" + type.GenericParameterPosition + "}";
             string typeName;
-            string arrayPrefix = null;
+            string? arrayPrefix = null;
             if (type.IsArray)
                 arrayPrefix = GetArrayPrefix(ref type);
             if (type.DeclaringType == null)
@@ -1548,10 +1558,10 @@ namespace System.Runtime.Serialization
 
         private static string GetDefaultDataContractNamespace(Type type)
         {
-            string clrNs = type.Namespace;
+            string? clrNs = type.Namespace;
             if (clrNs == null)
                 clrNs = string.Empty;
-            string ns = GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray());
+            string? ns = GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray());
             if (ns == null)
                 ns = GetGlobalDataContractNamespace(clrNs, type.Assembly.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray());
 
@@ -1562,7 +1572,7 @@ namespace System.Runtime.Serialization
             return ns;
         }
 
-        internal static List<int> GetDataContractNameForGenericName(string typeName, StringBuilder localName)
+        internal static List<int> GetDataContractNameForGenericName(string typeName, StringBuilder? localName)
         {
             List<int> nestedParamCounts = new List<int>();
             for (int startIndex = 0, endIndex; ;)
@@ -1613,7 +1623,7 @@ namespace System.Runtime.Serialization
             return new XmlQualifiedName(localName, GetNamespace(ns));
         }
 
-        internal static string GetDefaultStableNamespace(string clrNs)
+        internal static string GetDefaultStableNamespace(string? clrNs)
         {
             if (clrNs == null) clrNs = string.Empty;
             return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs).AbsoluteUri;
@@ -1628,7 +1638,7 @@ namespace System.Runtime.Serialization
         private static void GetDefaultStableName(CodeTypeReference typeReference, out string localName, out string ns)
         {
             string fullTypeName = typeReference.BaseType;
-            DataContract dataContract = GetBuiltInDataContract(fullTypeName);
+            DataContract? dataContract = GetBuiltInDataContract(fullTypeName);
             if (dataContract != null)
             {
                 localName = dataContract.StableName.Name;
@@ -1682,7 +1692,7 @@ namespace System.Runtime.Serialization
                     ThrowInvalidDataContractException(SR.Format(SR.DataContractNamespaceIsNotValid, dataContractNs), type);
                 dataContractNs = trimmedNs;
             }
-            Uri uri;
+            Uri? uri;
             if (Uri.TryCreate(dataContractNs, UriKind.RelativeOrAbsolute, out uri))
             {
                 if (uri.ToString() == Globals.SerializationNamespace)
@@ -1694,7 +1704,7 @@ namespace System.Runtime.Serialization
 
         internal static string GetClrTypeFullName(Type type)
         {
-            return !type.IsGenericTypeDefinition && type.ContainsGenericParameters ? type.Namespace + "." + type.Name : type.FullName;
+            return !type.IsGenericTypeDefinition && type.ContainsGenericParameters ? type.Namespace + "." + type.Name : type.FullName!;
         }
 
         internal static void GetClrNameAndNamespace(string fullTypeName, out string localName, out string ns)
@@ -1720,13 +1730,13 @@ namespace System.Runtime.Serialization
             return uriString.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal) ? uriString.Substring(Globals.DataContractXsdBaseNamespace.Length) : uriString;
         }
 
-        private static string GetGlobalDataContractNamespace(string clrNs, object[] nsAttributes)
+        private static string? GetGlobalDataContractNamespace(string clrNs, object[] nsAttributes)
         {
-            string dataContractNs = null;
+            string? dataContractNs = null;
             for (int i = 0; i < nsAttributes.Length; i++)
             {
                 ContractNamespaceAttribute nsAttribute = (ContractNamespaceAttribute)nsAttributes[i];
-                string clrNsInAttribute = nsAttribute.ClrNamespace;
+                string? clrNsInAttribute = nsAttribute.ClrNamespace;
                 if (clrNsInAttribute == null)
                     clrNsInAttribute = string.Empty;
                 if (clrNsInAttribute == clrNs)
@@ -1898,7 +1908,7 @@ namespace System.Runtime.Serialization
 
         internal static string ExpandGenericParameters(string format, IGenericNameProvider genericNameProvider)
         {
-            string digest = null;
+            string? digest = null;
             StringBuilder typeName = new StringBuilder();
             IList<int> nestedParameterCounts = genericNameProvider.GetNestedParameterCounts();
             for (int i = 0; i < format.Length; i++)
@@ -1950,15 +1960,15 @@ namespace System.Runtime.Serialization
 
 
 
-        internal static DataContractDictionary ImportKnownTypeAttributes(Type type)
+        internal static DataContractDictionary? ImportKnownTypeAttributes(Type type)
         {
-            DataContractDictionary knownDataContracts = null;
+            DataContractDictionary? knownDataContracts = null;
             Dictionary<Type, Type> typesChecked = new Dictionary<Type, Type>();
             ImportKnownTypeAttributes(type, typesChecked, ref knownDataContracts);
             return knownDataContracts;
         }
 
-        private static void ImportKnownTypeAttributes(Type type, Dictionary<Type, Type> typesChecked, ref DataContractDictionary knownDataContracts)
+        private static void ImportKnownTypeAttributes(Type? type, Dictionary<Type, Type> typesChecked, ref DataContractDictionary? knownDataContracts)
         {
             while (type != null && DataContract.IsTypeSerializable(type))
             {
@@ -1991,7 +2001,7 @@ namespace System.Runtime.Serialization
                                 DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeOneScheme, DataContract.GetClrTypeFullName(type)), type);
                             }
 
-                            string methodName = kt.MethodName;
+                            string? methodName = kt.MethodName;
                             if (methodName == null)
                             {
                                 DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeNoData, DataContract.GetClrTypeFullName(type)), type);
@@ -2000,14 +2010,14 @@ namespace System.Runtime.Serialization
                             if (methodName.Length == 0)
                                 DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeEmptyString, DataContract.GetClrTypeFullName(type)), type);
 
-                            MethodInfo method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>());
+                            MethodInfo? method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>());
                             if (method == null)
                                 DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeUnknownMethod, methodName, DataContract.GetClrTypeFullName(type)), type);
 
                             if (!Globals.TypeOfTypeEnumerable.IsAssignableFrom(method.ReturnType))
                                 DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeReturnType, DataContract.GetClrTypeFullName(type), methodName), type);
 
-                            object types = method.Invoke(null, Array.Empty<object>());
+                            object? types = method.Invoke(null, Array.Empty<object>());
                             if (types == null)
                             {
                                 DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeMethodNull, DataContract.GetClrTypeFullName(type)), type);
@@ -2029,7 +2039,7 @@ namespace System.Runtime.Serialization
                 //For Json we need to add KeyValuePair<K,T> to KnownTypes if the UnderLyingType is a Dictionary<K,T>
                 try
                 {
-                    CollectionDataContract collectionDataContract = DataContract.GetDataContract(type) as CollectionDataContract;
+                    CollectionDataContract? collectionDataContract = DataContract.GetDataContract(type) as CollectionDataContract;
                     if (collectionDataContract != null && collectionDataContract.IsDictionary &&
                         collectionDataContract.ItemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue)
                     {
@@ -2054,11 +2064,11 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal static void CheckAndAdd(Type type, Dictionary<Type, Type> typesChecked, ref DataContractDictionary nameToDataContractTable)
+        internal static void CheckAndAdd(Type type, Dictionary<Type, Type> typesChecked, [NotNullIfNotNull("nameToDataContractTable")] ref DataContractDictionary? nameToDataContractTable)
         {
             type = DataContract.UnwrapNullableType(type);
             DataContract dataContract = DataContract.GetDataContract(type);
-            DataContract alreadyExistingContract;
+            DataContract? alreadyExistingContract;
             if (nameToDataContractTable == null)
             {
                 nameToDataContractTable = new DataContractDictionary();
@@ -2100,7 +2110,7 @@ namespace System.Runtime.Serialization
         ///          since this information is used to determine whether to give the generated code access
         ///          permissions to private members, any changes to the logic should be reviewed.
         /// </SecurityNote>
-        internal static bool ConstructorRequiresMemberAccess(ConstructorInfo ctor)
+        internal static bool ConstructorRequiresMemberAccess(ConstructorInfo? ctor)
         {
             return ctor != null && !ctor.IsPublic && !IsMemberVisibleInSerializationModule(ctor);
         }
@@ -2111,7 +2121,7 @@ namespace System.Runtime.Serialization
         ///          since this information is used to determine whether to give the generated code access
         ///          permissions to private members, any changes to the logic should be reviewed.
         /// </SecurityNote>
-        internal static bool MethodRequiresMemberAccess(MethodInfo method)
+        internal static bool MethodRequiresMemberAccess(MethodInfo? method)
         {
             return method != null && !method.IsPublic && !IsMemberVisibleInSerializationModule(method);
         }
@@ -2122,7 +2132,7 @@ namespace System.Runtime.Serialization
         ///          since this information is used to determine whether to give the generated code access
         ///          permissions to private members, any changes to the logic should be reviewed.
         /// </SecurityNote>
-        internal static bool FieldRequiresMemberAccess(FieldInfo field)
+        internal static bool FieldRequiresMemberAccess(FieldInfo? field)
         {
             return field != null && !field.IsPublic && !IsMemberVisibleInSerializationModule(field);
         }
@@ -2144,7 +2154,7 @@ namespace System.Runtime.Serialization
         /// </SecurityNote>
         private static bool IsMemberVisibleInSerializationModule(MemberInfo member)
         {
-            if (!IsTypeVisibleInSerializationModule(member.DeclaringType))
+            if (!IsTypeVisibleInSerializationModule(member.DeclaringType!))
                 return false;
 
             if (member is MethodInfo)
@@ -2271,10 +2281,10 @@ namespace System.Runtime.Serialization
         private XmlQualifiedName GetStableName(int i)
         {
             object o = _genericParams[i];
-            XmlQualifiedName qname = o as XmlQualifiedName;
+            XmlQualifiedName? qname = o as XmlQualifiedName;
             if (qname == null)
             {
-                Type paramType = o as Type;
+                Type? paramType = o as Type;
                 if (paramType != null)
                     _genericParams[i] = qname = DataContract.GetStableName(paramType);
                 else
@@ -2288,9 +2298,9 @@ namespace System.Runtime.Serialization
 
     internal class TypeHandleRefEqualityComparer : IEqualityComparer<TypeHandleRef>
     {
-        public bool Equals(TypeHandleRef x, TypeHandleRef y)
+        public bool Equals(TypeHandleRef? x, TypeHandleRef? y)
         {
-            return x.Value.Equals(y.Value);
+            return x!.Value.Equals(y!.Value);
         }
 
         public int GetHashCode(TypeHandleRef obj)
index 6cfc5ef..ea96105 100644 (file)
@@ -8,7 +8,7 @@ namespace System.Runtime.Serialization
 {
     public abstract class DataContractResolver
     {
-        public abstract bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace);
-        public abstract Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver);
+        public abstract bool TryResolveType(Type type, Type? declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString? typeName, out XmlDictionaryString? typeNamespace);
+        public abstract Type? ResolveName(string typeName, string? typeNamespace, Type? declaredType, DataContractResolver knownTypeResolver);
     }
 }
index 61dbc2c..53a1840 100644 (file)
@@ -15,22 +15,23 @@ namespace System.Runtime.Serialization
     using System.Collections.ObjectModel;
     using System.Runtime.CompilerServices;
     using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
+    using System.Diagnostics.CodeAnalysis;
 
     public sealed class DataContractSerializer : XmlObjectSerializer
     {
         private Type _rootType;
-        private DataContract _rootContract; // post-surrogate
+        private DataContract? _rootContract; // post-surrogate
         private bool _needsContractNsAtRoot;
-        private XmlDictionaryString _rootName;
-        private XmlDictionaryString _rootNamespace;
+        private XmlDictionaryString? _rootName;
+        private XmlDictionaryString? _rootNamespace;
         private int _maxItemsInObjectGraph;
         private bool _ignoreExtensionDataObject;
         private bool _preserveObjectReferences;
-        private ReadOnlyCollection<Type> _knownTypeCollection;
-        internal IList<Type> knownTypeList;
-        internal DataContractDictionary knownDataContracts;
-        private DataContractResolver _dataContractResolver;
-        private ISerializationSurrogateProvider _serializationSurrogateProvider;
+        private ReadOnlyCollection<Type>? _knownTypeCollection;
+        internal IList<Type>? knownTypeList;
+        internal DataContractDictionary? knownDataContracts;
+        private DataContractResolver? _dataContractResolver;
+        private ISerializationSurrogateProvider? _serializationSurrogateProvider;
         private bool _serializeReadOnlyTypes;
 
         private static SerializationOption _option = IsReflectionBackupAllowed() ? SerializationOption.ReflectionAsBackup : SerializationOption.CodeGenOnly;
@@ -55,11 +56,11 @@ namespace System.Runtime.Serialization
         }
 
         public DataContractSerializer(Type type)
-            : this(type, (IEnumerable<Type>)null)
+            : this(type, (IEnumerable<Type>?)null)
         {
         }
 
-        public DataContractSerializer(Type type, IEnumerable<Type> knownTypes)
+        public DataContractSerializer(Type type, IEnumerable<Type>? knownTypes)
         {
             Initialize(type, knownTypes, int.MaxValue, false, false, null, false);
         }
@@ -70,7 +71,7 @@ namespace System.Runtime.Serialization
         {
         }
 
-        public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable<Type> knownTypes)
+        public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable<Type>? knownTypes)
         {
             XmlDictionary dictionary = new XmlDictionary(2);
             Initialize(type, dictionary.Add(rootName), dictionary.Add(DataContract.GetNamespace(rootNamespace)), knownTypes, int.MaxValue, false, false, null, false);
@@ -82,7 +83,7 @@ namespace System.Runtime.Serialization
         {
         }
 
-        public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes)
+        public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type>? knownTypes)
         {
             Initialize(type, rootName, rootNamespace, knownTypes, int.MaxValue, false, false, null, false);
         }
@@ -92,7 +93,7 @@ namespace System.Runtime.Serialization
             Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, null, false);
         }
 
-        public DataContractSerializer(Type type, DataContractSerializerSettings settings)
+        public DataContractSerializer(Type type, DataContractSerializerSettings? settings)
         {
             if (settings == null)
             {
@@ -102,12 +103,13 @@ namespace System.Runtime.Serialization
                 settings.PreserveObjectReferences, settings.DataContractResolver, settings.SerializeReadOnlyTypes);
         }
 
+        [MemberNotNull(nameof(_rootType))]
         private void Initialize(Type type,
-            IEnumerable<Type> knownTypes,
+            IEnumerable<Type>? knownTypes,
             int maxItemsInObjectGraph,
             bool ignoreExtensionDataObject,
             bool preserveObjectReferences,
-            DataContractResolver dataContractResolver,
+            DataContractResolver? dataContractResolver,
             bool serializeReadOnlyTypes)
         {
             CheckNull(type, nameof(type));
@@ -132,12 +134,13 @@ namespace System.Runtime.Serialization
             _serializeReadOnlyTypes = serializeReadOnlyTypes;
         }
 
-        private void Initialize(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace,
-            IEnumerable<Type> knownTypes,
+        [MemberNotNull(nameof(_rootType))]
+        private void Initialize(Type type, XmlDictionaryString? rootName, XmlDictionaryString? rootNamespace,
+            IEnumerable<Type>? knownTypes,
             int maxItemsInObjectGraph,
             bool ignoreExtensionDataObject,
             bool preserveObjectReferences,
-            DataContractResolver dataContractResolver,
+            DataContractResolver? dataContractResolver,
             bool serializeReadOnlyTypes)
         {
             Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractResolver, serializeReadOnlyTypes);
@@ -166,7 +169,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal override DataContractDictionary KnownDataContracts
+        internal override DataContractDictionary? KnownDataContracts
         {
             get
             {
@@ -187,7 +190,7 @@ namespace System.Runtime.Serialization
             get { return _maxItemsInObjectGraph; }
         }
 
-        internal ISerializationSurrogateProvider SerializationSurrogateProvider
+        internal ISerializationSurrogateProvider? SerializationSurrogateProvider
         {
             get { return _serializationSurrogateProvider; }
             set { _serializationSurrogateProvider = value; }
@@ -203,7 +206,7 @@ namespace System.Runtime.Serialization
             get { return _ignoreExtensionDataObject; }
         }
 
-        public DataContractResolver DataContractResolver
+        public DataContractResolver? DataContractResolver
         {
             get { return _dataContractResolver; }
         }
@@ -226,29 +229,29 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal override void InternalWriteObject(XmlWriterDelegator writer, object graph)
+        internal override void InternalWriteObject(XmlWriterDelegator writer, object? graph)
         {
             InternalWriteObject(writer, graph, null);
         }
 
-        internal override void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
+        internal override void InternalWriteObject(XmlWriterDelegator writer, object? graph, DataContractResolver? dataContractResolver)
         {
             InternalWriteStartObject(writer, graph);
             InternalWriteObjectContent(writer, graph, dataContractResolver);
             InternalWriteEndObject(writer);
         }
 
-        public override void WriteObject(XmlWriter writer, object graph)
+        public override void WriteObject(XmlWriter writer, object? graph)
         {
             WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
         }
 
-        public override void WriteStartObject(XmlWriter writer, object graph)
+        public override void WriteStartObject(XmlWriter writer, object? graph)
         {
             WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
         }
 
-        public override void WriteObjectContent(XmlWriter writer, object graph)
+        public override void WriteObjectContent(XmlWriter writer, object? graph)
         {
             WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph);
         }
@@ -258,12 +261,12 @@ namespace System.Runtime.Serialization
             WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer));
         }
 
-        public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
+        public override void WriteStartObject(XmlDictionaryWriter writer, object? graph)
         {
             WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
         }
 
-        public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
+        public override void WriteObjectContent(XmlDictionaryWriter writer, object? graph)
         {
             WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph);
         }
@@ -273,17 +276,17 @@ namespace System.Runtime.Serialization
             WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer));
         }
 
-        public void WriteObject(XmlDictionaryWriter writer, object graph, DataContractResolver dataContractResolver)
+        public void WriteObject(XmlDictionaryWriter writer, object? graph, DataContractResolver? dataContractResolver)
         {
             WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph, dataContractResolver);
         }
 
-        public override object ReadObject(XmlReader reader)
+        public override object? ReadObject(XmlReader reader)
         {
             return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/);
         }
 
-        public override object ReadObject(XmlReader reader, bool verifyObjectName)
+        public override object? ReadObject(XmlReader reader, bool verifyObjectName)
         {
             return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName);
         }
@@ -293,7 +296,7 @@ namespace System.Runtime.Serialization
             return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader));
         }
 
-        public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
+        public override object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
         {
             return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName);
         }
@@ -303,22 +306,22 @@ namespace System.Runtime.Serialization
             return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader));
         }
 
-        public object ReadObject(XmlDictionaryReader reader, bool verifyObjectName, DataContractResolver dataContractResolver)
+        public object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName, DataContractResolver? dataContractResolver)
         {
             return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName, dataContractResolver);
         }
 
-        internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph)
+        internal override void InternalWriteStartObject(XmlWriterDelegator writer, object? graph)
         {
             WriteRootElement(writer, RootContract, _rootName, _rootNamespace, _needsContractNsAtRoot);
         }
 
-        internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph)
+        internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object? graph)
         {
             InternalWriteObjectContent(writer, graph, null);
         }
 
-        internal void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
+        internal void InternalWriteObjectContent(XmlWriterDelegator writer, object? graph, DataContractResolver? dataContractResolver)
         {
             if (MaxItemsInObjectGraph == 0)
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
@@ -358,7 +361,7 @@ namespace System.Runtime.Serialization
                 }
                 else
                 {
-                    XmlObjectSerializerWriteContext context = null;
+                    XmlObjectSerializerWriteContext? context = null;
                     if (IsRootXmlAny(_rootName, contract))
                         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeSerializedAsDerivedType, graphType, contract.UnderlyingType)));
 
@@ -398,12 +401,12 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName)
+        internal override object? InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName)
         {
             return InternalReadObject(xmlReader, verifyObjectName, null);
         }
 
-        internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName, DataContractResolver dataContractResolver)
+        internal override object? InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName, DataContractResolver? dataContractResolver)
         {
             if (MaxItemsInObjectGraph == 0)
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
@@ -415,8 +418,8 @@ namespace System.Runtime.Serialization
             {
                 if (!InternalIsStartObject(xmlReader))
                 {
-                    XmlDictionaryString expectedName;
-                    XmlDictionaryString expectedNs;
+                    XmlDictionaryString? expectedName;
+                    XmlDictionaryString? expectedNs;
                     if (_rootName == null)
                     {
                         expectedName = RootContract.TopLevelElementName;
@@ -443,7 +446,7 @@ namespace System.Runtime.Serialization
 
             if (IsRootXmlAny(_rootName, contract))
             {
-                return XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, contract as XmlDataContract, false /*isMemberType*/);
+                return XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, (contract as XmlDataContract)!, false /*isMemberType*/);
             }
 
             XmlObjectSerializerReadContext context = XmlObjectSerializerReadContext.CreateContext(this, contract, dataContractResolver);
@@ -456,19 +459,20 @@ namespace System.Runtime.Serialization
             return IsRootElement(reader, RootContract, _rootName, _rootNamespace);
         }
 
-        internal override Type GetSerializeType(object graph)
+        internal override Type? GetSerializeType(object? graph)
         {
             return (graph == null) ? _rootType : graph.GetType();
         }
 
-        internal override Type GetDeserializeType()
+        internal override Type? GetDeserializeType()
         {
             return _rootType;
         }
 
-        internal static object SurrogateToDataContractType(ISerializationSurrogateProvider serializationSurrogateProvider, object oldObj, Type surrogatedDeclaredType, ref Type objType)
+        [return: NotNullIfNotNull("oldObj")]
+        internal static object? SurrogateToDataContractType(ISerializationSurrogateProvider serializationSurrogateProvider, object? oldObj, Type surrogatedDeclaredType, ref Type objType)
         {
-            object obj = DataContractSurrogateCaller.GetObjectToSerialize(serializationSurrogateProvider, oldObj, objType, surrogatedDeclaredType);
+            object? obj = DataContractSurrogateCaller.GetObjectToSerialize(serializationSurrogateProvider, oldObj, objType, surrogatedDeclaredType);
             if (obj != oldObj)
             {
                 objType = obj != null ? obj.GetType() : Globals.TypeOfObject;
index 33e0ed5..87f2b60 100644 (file)
@@ -5,12 +5,12 @@ namespace System.Runtime.Serialization
 {
     public static class DataContractSerializerExtensions
     {
-        public static ISerializationSurrogateProvider GetSerializationSurrogateProvider(this DataContractSerializer serializer)
+        public static ISerializationSurrogateProvider? GetSerializationSurrogateProvider(this DataContractSerializer serializer)
         {
             return serializer.SerializationSurrogateProvider;
         }
 
-        public static void SetSerializationSurrogateProvider(this DataContractSerializer serializer, ISerializationSurrogateProvider provider)
+        public static void SetSerializationSurrogateProvider(this DataContractSerializer serializer, ISerializationSurrogateProvider? provider)
         {
             serializer.SerializationSurrogateProvider = provider;
         }
index a9db9bf..4adb039 100644 (file)
@@ -17,17 +17,17 @@ namespace System.Runtime.Serialization
         /// <summary>
         /// Gets or sets Dummy documentation
         /// </summary>
-        public XmlDictionaryString RootName { get; set; }
+        public XmlDictionaryString? RootName { get; set; }
 
         /// <summary>
         /// Gets or sets Dummy documentation
         /// </summary>
-        public XmlDictionaryString RootNamespace { get; set; }
+        public XmlDictionaryString? RootNamespace { get; set; }
 
         /// <summary>
         /// Gets or sets Dummy documentation
         /// </summary>
-        public IEnumerable<Type> KnownTypes { get; set; }
+        public IEnumerable<Type>? KnownTypes { get; set; }
 
         /// <summary>
         /// Gets or sets Dummy documentation
@@ -52,7 +52,7 @@ namespace System.Runtime.Serialization
         /// <summary>
         /// Gets or sets Dummy documentation
         /// </summary>
-        public DataContractResolver DataContractResolver { get; set; }
+        public DataContractResolver? DataContractResolver { get; set; }
 
         /// <summary>
         /// Gets or sets a value indicating whether Dummy documentation
index 0fee2c3..69f1004 100644 (file)
@@ -11,8 +11,8 @@ namespace System.Runtime.Serialization
 {
     internal sealed class DataContractSet
     {
-        private Dictionary<XmlQualifiedName, DataContract> _contracts;
-        private Dictionary<DataContract, object> _processedContracts;
+        private Dictionary<XmlQualifiedName, DataContract>? _contracts;
+        private Dictionary<DataContract, object>? _processedContracts;
         private readonly ICollection<Type> _referencedTypes;
         private readonly ICollection<Type> _referencedCollectionTypes;
 
@@ -115,7 +115,7 @@ namespace System.Runtime.Serialization
 
         internal void InternalAdd(XmlQualifiedName name, DataContract dataContract)
         {
-            DataContract dataContractInSet = null;
+            DataContract? dataContractInSet = null;
             if (Contracts.TryGetValue(name, out dataContractInSet))
             {
                 if (!dataContractInSet.Equals(dataContract))
@@ -184,7 +184,7 @@ namespace System.Runtime.Serialization
         {
             if (collectionDataContract.IsDictionary)
             {
-                ClassDataContract keyValueContract = collectionDataContract.ItemContract as ClassDataContract;
+                ClassDataContract keyValueContract = (collectionDataContract.ItemContract as ClassDataContract)!;
                 AddClassDataContract(keyValueContract);
             }
             else
@@ -201,7 +201,7 @@ namespace System.Runtime.Serialization
             AddKnownDataContracts(xmlDataContract.KnownDataContracts);
         }
 
-        private void AddKnownDataContracts(DataContractDictionary knownDataContracts)
+        private void AddKnownDataContracts(DataContractDictionary? knownDataContracts)
         {
             if (knownDataContracts != null)
             {
@@ -218,7 +218,7 @@ namespace System.Runtime.Serialization
             if (_dataContractSurrogate == null)
                 return DataContract.GetDataContract(clrType);
 #endif
-            DataContract dataContract = DataContract.GetBuiltInDataContract(clrType);
+            DataContract? dataContract = DataContract.GetBuiltInDataContract(clrType);
             if (dataContract != null)
                 return dataContract;
 
@@ -243,11 +243,9 @@ namespace System.Runtime.Serialization
 
         internal DataContract GetMemberTypeDataContract(DataMember dataMember)
         {
-            if (dataMember.MemberInfo != null)
+            Type dataMemberType = dataMember.MemberType;
+            if (dataMember.IsGetOnlyCollection)
             {
-                Type dataMemberType = dataMember.MemberType;
-                if (dataMember.IsGetOnlyCollection)
-                {
 #if SUPPORT_SURROGATE
                     if (_dataContractSurrogate != null)
                     {
@@ -259,14 +257,12 @@ namespace System.Runtime.Serialization
                         }
                     }
 #endif
-                    return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(dataMemberType.TypeHandle), dataMemberType.TypeHandle, dataMemberType, SerializationMode.SharedContract);
-                }
-                else
-                {
-                    return GetDataContract(dataMemberType);
-                }
+                return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(dataMemberType.TypeHandle), dataMemberType.TypeHandle, dataMemberType, SerializationMode.SharedContract);
+            }
+            else
+            {
+                return GetDataContract(dataMemberType);
             }
-            return dataMember.MemberTypeContract;
         }
 
         internal DataContract GetItemTypeDataContract(CollectionDataContract collectionContract)
index 9e59d3b..2ef49f1 100644 (file)
@@ -7,6 +7,7 @@ namespace System.Runtime.Serialization
     using System.CodeDom;
     using System.Reflection;
     using System.Collections.ObjectModel;
+    using System.Diagnostics.CodeAnalysis;
 
     internal static class DataContractSurrogateCaller
     {
@@ -17,7 +18,8 @@ namespace System.Runtime.Serialization
             return surrogateProvider.GetSurrogateType(type) ?? type;
         }
 
-        internal static object GetObjectToSerialize(ISerializationSurrogateProvider surrogateProvider, object obj, Type objType, Type membertype)
+        [return: NotNullIfNotNull("obj")]
+        internal static object? GetObjectToSerialize(ISerializationSurrogateProvider surrogateProvider, object? obj, Type objType, Type membertype)
         {
             if (obj == null)
                 return null;
@@ -26,7 +28,8 @@ namespace System.Runtime.Serialization
             return surrogateProvider.GetObjectToSerialize(obj, membertype);
         }
 
-        internal static object GetDeserializedObject(ISerializationSurrogateProvider surrogateProvider, object obj, Type objType, Type memberType)
+        [return: NotNullIfNotNull("obj")]
+        internal static object? GetDeserializedObject(ISerializationSurrogateProvider surrogateProvider, object? obj, Type objType, Type memberType)
         {
             if (obj == null)
                 return null;
index 6c5f3e6..b2ddbd1 100644 (file)
@@ -16,11 +16,6 @@ namespace System.Runtime.Serialization
     {
         private readonly CriticalHelper _helper;
 
-        public DataMember()
-        {
-            _helper = new CriticalHelper();
-        }
-
         internal DataMember(MemberInfo memberInfo)
         {
             _helper = new CriticalHelper(memberInfo);
@@ -98,7 +93,7 @@ namespace System.Runtime.Serialization
             { return _helper.MemberTypeContract; }
         }
 
-        internal PrimitiveDataContract MemberPrimitiveContract
+        internal PrimitiveDataContract? MemberPrimitiveContract
         {
             get
             {
@@ -115,7 +110,7 @@ namespace System.Runtime.Serialization
             { _helper.HasConflictingNameAndType = value; }
         }
 
-        internal DataMember ConflictingMember
+        internal DataMember? ConflictingMember
         {
             get
             { return _helper.ConflictingMember; }
@@ -124,7 +119,7 @@ namespace System.Runtime.Serialization
             { _helper.ConflictingMember = value; }
         }
 
-        private FastInvokerBuilder.Getter _getter;
+        private FastInvokerBuilder.Getter? _getter;
         internal FastInvokerBuilder.Getter Getter
         {
             get
@@ -138,7 +133,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private FastInvokerBuilder.Setter _setter;
+        private FastInvokerBuilder.Setter? _setter;
         internal FastInvokerBuilder.Setter Setter
         {
             get
@@ -154,8 +149,8 @@ namespace System.Runtime.Serialization
 
         private class CriticalHelper
         {
-            private DataContract _memberTypeContract;
-            private string _name;
+            private DataContract? _memberTypeContract;
+            private string _name = null!; // Name is always initialized right after construction
             private int _order;
             private bool _isRequired;
             private bool _emitDefaultValue;
@@ -163,12 +158,7 @@ namespace System.Runtime.Serialization
             private bool _isGetOnlyCollection;
             private readonly MemberInfo _memberInfo;
             private bool _hasConflictingNameAndType;
-            private DataMember _conflictingMember;
-
-            internal CriticalHelper()
-            {
-                _emitDefaultValue = Globals.DefaultEmitDefaultValue;
-            }
+            private DataMember? _conflictingMember;
 
             internal CriticalHelper(MemberInfo memberInfo)
             {
@@ -217,7 +207,7 @@ namespace System.Runtime.Serialization
                 set { _isGetOnlyCollection = value; }
             }
 
-            private Type _memberType;
+            private Type? _memberType;
 
             internal Type MemberType
             {
@@ -225,7 +215,7 @@ namespace System.Runtime.Serialization
                 {
                     if (_memberType == null)
                     {
-                        FieldInfo field = MemberInfo as FieldInfo;
+                        FieldInfo? field = MemberInfo as FieldInfo;
                         if (field != null)
                             _memberType = field.FieldType;
                         else
@@ -254,7 +244,9 @@ namespace System.Runtime.Serialization
                             }
                         }
                     }
-                    return _memberTypeContract;
+
+                    // TODO-NULLABLE - MemberInfo is never null, so this can never return null
+                    return _memberTypeContract!;
                 }
                 set
                 {
@@ -268,15 +260,15 @@ namespace System.Runtime.Serialization
                 set { _hasConflictingNameAndType = value; }
             }
 
-            internal DataMember ConflictingMember
+            internal DataMember? ConflictingMember
             {
                 get { return _conflictingMember; }
                 set { _conflictingMember = value; }
             }
 
-            private PrimitiveDataContract _memberPrimitiveContract = PrimitiveDataContract.NullContract;
+            private PrimitiveDataContract? _memberPrimitiveContract = PrimitiveDataContract.NullContract;
 
-            internal PrimitiveDataContract MemberPrimitiveContract
+            internal PrimitiveDataContract? MemberPrimitiveContract
             {
                 get
                 {
@@ -298,7 +290,7 @@ namespace System.Runtime.Serialization
         internal bool RequiresMemberAccessForGet()
         {
             MemberInfo memberInfo = MemberInfo;
-            FieldInfo field = memberInfo as FieldInfo;
+            FieldInfo? field = memberInfo as FieldInfo;
             if (field != null)
             {
                 return DataContract.FieldRequiresMemberAccess(field);
@@ -306,7 +298,7 @@ namespace System.Runtime.Serialization
             else
             {
                 PropertyInfo property = (PropertyInfo)memberInfo;
-                MethodInfo getMethod = property.GetMethod;
+                MethodInfo? getMethod = property.GetMethod;
                 if (getMethod != null)
                 {
                     return DataContract.MethodRequiresMemberAccess(getMethod) || !DataContract.IsTypeVisible(property.PropertyType);
@@ -323,7 +315,7 @@ namespace System.Runtime.Serialization
         internal bool RequiresMemberAccessForSet()
         {
             MemberInfo memberInfo = MemberInfo;
-            FieldInfo field = memberInfo as FieldInfo;
+            FieldInfo? field = memberInfo as FieldInfo;
             if (field != null)
             {
                 return DataContract.FieldRequiresMemberAccess(field);
@@ -331,7 +323,7 @@ namespace System.Runtime.Serialization
             else
             {
                 PropertyInfo property = (PropertyInfo)memberInfo;
-                MethodInfo setMethod = property.SetMethod;
+                MethodInfo? setMethod = property.SetMethod;
                 if (setMethod != null)
                 {
                     return DataContract.MethodRequiresMemberAccess(setMethod) || !DataContract.IsTypeVisible(property.PropertyType);
index 9ac0106..0196143 100644 (file)
@@ -2,19 +2,20 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 using System.Diagnostics;
-
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization
 {
     internal static class Fx
     {
         [Conditional("DEBUG")]
-        public static void Assert(bool condition, string message)
+        public static void Assert([DoesNotReturnIf(false)] bool condition, string message)
         {
             System.Diagnostics.Debug.Assert(condition, message);
         }
 
         [Conditional("DEBUG")]
+        [DoesNotReturn]
         public static void Assert(string message)
         {
             Assert(false, message);
@@ -24,18 +25,19 @@ namespace System.Runtime.Serialization
     internal class DiagnosticUtility
     {
         [Conditional("DEBUG")]
+        [DoesNotReturn]
         public static void DebugAssert(string message)
         {
             DebugAssert(false, message);
         }
 
         [Conditional("DEBUG")]
-        public static void DebugAssert(bool condition, string message)
+        public static void DebugAssert([DoesNotReturnIf(false)] bool condition, string message)
         {
             Debug.Assert(condition, message);
         }
 
-        internal static bool IsFatal(Exception exception)
+        internal static bool IsFatal(Exception? exception)
         {
             while (exception != null)
             {
index dcbd70c..e6d46aa 100644 (file)
@@ -11,7 +11,7 @@ using System.Text;
 using System.Xml;
 using System.Security;
 using System.Linq;
-
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization
 {
@@ -19,16 +19,11 @@ namespace System.Runtime.Serialization
     {
         private readonly EnumDataContractCriticalHelper _helper;
 
-        public EnumDataContract() : base(new EnumDataContractCriticalHelper())
-        {
-            _helper = base.Helper as EnumDataContractCriticalHelper;
-        }
-
-        public XmlQualifiedName BaseContractName { get; set; }
+        public XmlQualifiedName? BaseContractName { get; set; }
 
         internal EnumDataContract(Type type) : base(new EnumDataContractCriticalHelper(type))
         {
-            _helper = base.Helper as EnumDataContractCriticalHelper;
+            _helper = (base.Helper as EnumDataContractCriticalHelper)!;
         }
         public List<DataMember> Members
         {
@@ -37,7 +32,7 @@ namespace System.Runtime.Serialization
             set { _helper.Members = value; }
         }
 
-        public List<long> Values
+        public List<long>? Values
         {
             get
             { return _helper.Values; }
@@ -58,7 +53,7 @@ namespace System.Runtime.Serialization
             set { _helper.IsULong = value; }
         }
 
-        public XmlDictionaryString[] ChildElementNames
+        public XmlDictionaryString[]? ChildElementNames
         {
             get
             { return _helper.ChildElementNames; }
@@ -76,11 +71,11 @@ namespace System.Runtime.Serialization
             private static readonly Dictionary<XmlQualifiedName, Type> s_nameToType = new Dictionary<XmlQualifiedName, Type>();
 
             private List<DataMember> _members;
-            private List<long> _values;
+            private List<long>? _values;
             private bool _isULong;
             private bool _isFlags;
             private readonly bool _hasDataContract;
-            private XmlDictionaryString[] _childElementNames;
+            private XmlDictionaryString[]? _childElementNames;
 
             static EnumDataContractCriticalHelper()
             {
@@ -101,11 +96,6 @@ namespace System.Runtime.Serialization
                 s_nameToType.Add(stableName, type);
             }
 
-            internal EnumDataContractCriticalHelper()
-            {
-                IsValueType = true;
-            }
-
             internal EnumDataContractCriticalHelper(Type type) : base(type)
             {
                 this.StableName = DataContract.GetStableName(type, out _hasDataContract);
@@ -120,7 +110,7 @@ namespace System.Runtime.Serialization
                 _childElementNames = new XmlDictionaryString[Members.Count];
                 for (int i = 0; i < Members.Count; i++)
                     _childElementNames[i] = dictionary.Add(Members[i].Name);
-                DataContractAttribute dataContractAttribute;
+                DataContractAttribute? dataContractAttribute;
                 if (TryGetDCAttribute(type, out dataContractAttribute))
                 {
                     if (dataContractAttribute.IsReference)
@@ -140,7 +130,7 @@ namespace System.Runtime.Serialization
                 set { _members = value; }
             }
 
-            internal List<long> Values
+            internal List<long>? Values
             {
                 get { return _values; }
                 set { _values = value; }
@@ -158,7 +148,7 @@ namespace System.Runtime.Serialization
                 set { _isULong = value; }
             }
 
-            internal XmlDictionaryString[] ChildElementNames
+            internal XmlDictionaryString[]? ChildElementNames
             {
                 get { return _childElementNames; }
                 set { _childElementNames = value; }
@@ -169,6 +159,7 @@ namespace System.Runtime.Serialization
                 _isULong = (baseType == Globals.TypeOfULong);
             }
 
+            [MemberNotNull(nameof(_members))]
             private void ImportDataMembers()
             {
                 Type type = this.UnderlyingType;
@@ -187,7 +178,7 @@ namespace System.Runtime.Serialization
                         if (memberAttributes != null && memberAttributes.Length > 0)
                         {
                             if (memberAttributes.Length > 1)
-                                ThrowInvalidDataContractException(SR.Format(SR.TooManyEnumMembers, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name));
+                                ThrowInvalidDataContractException(SR.Format(SR.TooManyEnumMembers, DataContract.GetClrTypeFullName(field.DeclaringType!), field.Name));
                             EnumMemberAttribute memberAttribute = (EnumMemberAttribute)memberAttributes[0];
 
                             DataMember memberContract = new DataMember(field);
@@ -205,7 +196,7 @@ namespace System.Runtime.Serialization
 
                         object[] dataMemberAttributes = field.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, false).ToArray();
                         if (dataMemberAttributes != null && dataMemberAttributes.Length > 0)
-                            ThrowInvalidDataContractException(SR.Format(SR.DataMemberOnEnumField, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name));
+                            ThrowInvalidDataContractException(SR.Format(SR.DataMemberOnEnumField, DataContract.GetClrTypeFullName(field.DeclaringType!), field.Name));
                     }
                     else
                     {
@@ -220,7 +211,7 @@ namespace System.Runtime.Serialization
 
                     if (enumMemberValid)
                     {
-                        object enumValue = field.GetValue(null);
+                        object? enumValue = field.GetValue(null);
                         if (_isULong)
                             tempValues.Add((long)Convert.ToUInt64(enumValue, null));
                         else
@@ -237,11 +228,11 @@ namespace System.Runtime.Serialization
         internal void WriteEnumValue(XmlWriterDelegator writer, object value)
         {
             long longValue = IsULong ? (long)Convert.ToUInt64(value, null) : Convert.ToInt64(value, null);
-            for (int i = 0; i < Values.Count; i++)
+            for (int i = 0; i < Values!.Count; i++)
             {
                 if (longValue == Values[i])
                 {
-                    writer.WriteString(ChildElementNames[i].Value);
+                    writer.WriteString(ChildElementNames![i].Value);
                     return;
                 }
             }
@@ -266,7 +257,7 @@ namespace System.Runtime.Serialization
                         else
                             writer.WriteString(DictionaryGlobals.Space.Value);
 
-                        writer.WriteString(ChildElementNames[i].Value);
+                        writer.WriteString(ChildElementNames![i].Value);
                         longValue &= ~current;
                     }
                 }
@@ -275,7 +266,7 @@ namespace System.Runtime.Serialization
                     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType))));
 
                 if (noneWritten && zeroIndex >= 0)
-                    writer.WriteString(ChildElementNames[zeroIndex].Value);
+                    writer.WriteString(ChildElementNames![zeroIndex].Value);
             }
             else
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType))));
@@ -334,7 +325,7 @@ namespace System.Runtime.Serialization
                 string memberName = Members[i].Name;
                 if (memberName.Length == count && string.CompareOrdinal(value, index, memberName, 0, count) == 0)
                 {
-                    return Values[i];
+                    return Values![i];
                 }
             }
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidEnumValueOnRead, value.Substring(index, count), DataContract.GetClrTypeFullName(UnderlyingType))));
@@ -364,12 +355,12 @@ namespace System.Runtime.Serialization
             }
         }
 
-        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context)
         {
             WriteEnumValue(xmlWriter, obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
+        public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context)
         {
             object obj = ReadEnumValue(xmlReader);
             if (context != null)
index dfe3813..c1c60b5 100644 (file)
@@ -7,17 +7,17 @@ namespace System.Runtime.Serialization
 {
     public class ExportOptions
     {
-        private Collection<Type> _knownTypes;
+        private Collection<Type>? _knownTypes;
 #if SUPPORT_SURROGATE
-        private IDataContractSurrogate _dataContractSurrogate;
+        private IDataContractSurrogate? _dataContractSurrogate;
 
-        public IDataContractSurrogate DataContractSurrogate
+        public IDataContractSurrogate? DataContractSurrogate
         {
             get { return _dataContractSurrogate; }
             set { _dataContractSurrogate = value; }
         }
 
-        internal IDataContractSurrogate GetSurrogate()
+        internal IDataContractSurrogate? GetSurrogate()
         {
             return _dataContractSurrogate;
         }
index 4dc77fb..1ba1ff2 100644 (file)
@@ -10,7 +10,7 @@ namespace System.Runtime.Serialization
 {
     public sealed class ExtensionDataObject
     {
-        private IList<ExtensionDataMember> _members;
+        private IList<ExtensionDataMember>? _members;
 
 #if USE_REFEMIT
         public ExtensionDataObject()
@@ -21,9 +21,9 @@ namespace System.Runtime.Serialization
         }
 
 #if USE_REFEMIT
-        public IList<ExtensionDataMember> Members
+        public IList<ExtensionDataMember>? Members
 #else
-        internal IList<ExtensionDataMember> Members
+        internal IList<ExtensionDataMember>? Members
 #endif
         {
             get { return _members; }
@@ -37,23 +37,20 @@ namespace System.Runtime.Serialization
     internal class ExtensionDataMember
 #endif
     {
-        private string _name;
-        private string _ns;
-        private IDataNode _value;
+        private IDataNode? _value;
         private int _memberIndex;
-        public string Name
-        {
-            get { return _name; }
-            set { _name = value; }
-        }
 
-        public string Namespace
+        public ExtensionDataMember(string name, string ns)
         {
-            get { return _ns; }
-            set { _ns = value; }
+            Name = name;
+            Namespace = ns;
         }
 
-        public IDataNode Value
+        public string Name { get; }
+
+        public string? Namespace { get; }
+
+        public IDataNode? Value
         {
             get { return _value; }
             set { _value = value; }
@@ -73,11 +70,11 @@ namespace System.Runtime.Serialization
 #endif
     {
         Type DataType { get; }
-        object Value { get; set; }  // boxes for primitives
-        string DataContractName { get; set; }
-        string DataContractNamespace { get; set; }
-        string ClrTypeName { get; set; }
-        string ClrAssemblyName { get; set; }
+        object? Value { get; set; }  // boxes for primitives
+        string? DataContractName { get; set; }
+        string? DataContractNamespace { get; set; }
+        string? ClrTypeName { get; set; }
+        string? ClrAssemblyName { get; set; }
         string Id { get; set; }
         bool PreservesReferences { get; }
 
@@ -90,11 +87,11 @@ namespace System.Runtime.Serialization
     internal class DataNode<T> : IDataNode
     {
         protected Type dataType;
-        private T _value;
-        private string _dataContractName;
-        private string _dataContractNamespace;
-        private string _clrTypeName;
-        private string _clrAssemblyName;
+        private T _value = default!;
+        private string? _dataContractName;
+        private string? _dataContractNamespace;
+        private string? _clrTypeName;
+        private string? _clrAssemblyName;
         private string _id = Globals.NewObjectId;
         private bool _isFinalValue;
 
@@ -115,10 +112,10 @@ namespace System.Runtime.Serialization
             get { return dataType; }
         }
 
-        public object Value
+        public object? Value
         {
             get { return _value; }
-            set { _value = (T)value; }
+            set { _value = (T)value!; }
         }
 
         bool IDataNode.IsFinalValue
@@ -139,25 +136,25 @@ namespace System.Runtime.Serialization
         }
 #endif
 
-        public string DataContractName
+        public string? DataContractName
         {
             get { return _dataContractName; }
             set { _dataContractName = value; }
         }
 
-        public string DataContractNamespace
+        public string? DataContractNamespace
         {
             get { return _dataContractNamespace; }
             set { _dataContractNamespace = value; }
         }
 
-        public string ClrTypeName
+        public string? ClrTypeName
         {
             get { return _clrTypeName; }
             set { _clrTypeName = value; }
         }
 
-        public string ClrAssemblyName
+        public string? ClrAssemblyName
         {
             get { return _clrAssemblyName; }
             set { _clrAssemblyName = value; }
@@ -194,7 +191,7 @@ namespace System.Runtime.Serialization
             _clrTypeName = _clrAssemblyName = null;
         }
 
-        internal void AddQualifiedNameAttribute(ElementData element, string elementPrefix, string elementName, string elementNs, string valueName, string valueNs)
+        internal void AddQualifiedNameAttribute(ElementData element, string elementPrefix, string elementName, string elementNs, string valueName, string? valueNs)
         {
             string prefix = ExtensionDataReader.GetPrefix(valueNs);
             element.AddAttribute(elementPrefix, elementNs, elementName, prefix + ":" + valueName);
@@ -219,14 +216,14 @@ namespace System.Runtime.Serialization
 
     internal class ClassDataNode : DataNode<object>
     {
-        private IList<ExtensionDataMember> _members;
+        private IList<ExtensionDataMember>? _members;
 
         internal ClassDataNode()
         {
             dataType = Globals.TypeOfClassDataNode;
         }
 
-        internal IList<ExtensionDataMember> Members
+        internal IList<ExtensionDataMember>? Members
         {
             get { return _members; }
             set { _members = value; }
@@ -241,28 +238,28 @@ namespace System.Runtime.Serialization
 
     internal class XmlDataNode : DataNode<object>
     {
-        private IList<XmlAttribute> _xmlAttributes;
-        private IList<XmlNode> _xmlChildNodes;
-        private XmlDocument _ownerDocument;
+        private IList<XmlAttribute>? _xmlAttributes;
+        private IList<XmlNode>? _xmlChildNodes;
+        private XmlDocument? _ownerDocument;
 
         internal XmlDataNode()
         {
             dataType = Globals.TypeOfXmlDataNode;
         }
 
-        internal IList<XmlAttribute> XmlAttributes
+        internal IList<XmlAttribute>? XmlAttributes
         {
             get { return _xmlAttributes; }
             set { _xmlAttributes = value; }
         }
 
-        internal IList<XmlNode> XmlChildNodes
+        internal IList<XmlNode>? XmlChildNodes
         {
             get { return _xmlChildNodes; }
             set { _xmlChildNodes = value; }
         }
 
-        internal XmlDocument OwnerDocument
+        internal XmlDocument? OwnerDocument
         {
             get { return _ownerDocument; }
             set { _ownerDocument = value; }
@@ -279,9 +276,9 @@ namespace System.Runtime.Serialization
 
     internal class CollectionDataNode : DataNode<Array>
     {
-        private IList<IDataNode> _items;
-        private string _itemName;
-        private string _itemNamespace;
+        private IList<IDataNode?>? _items;
+        private string? _itemName;
+        private string? _itemNamespace;
         private int _size = -1;
 
         internal CollectionDataNode()
@@ -289,19 +286,19 @@ namespace System.Runtime.Serialization
             dataType = Globals.TypeOfCollectionDataNode;
         }
 
-        internal IList<IDataNode> Items
+        internal IList<IDataNode?>? Items
         {
             get { return _items; }
             set { _items = value; }
         }
 
-        internal string ItemName
+        internal string? ItemName
         {
             get { return _itemName; }
             set { _itemName = value; }
         }
 
-        internal string ItemNamespace
+        internal string? ItemNamespace
         {
             get { return _itemNamespace; }
             set { _itemNamespace = value; }
@@ -330,28 +327,28 @@ namespace System.Runtime.Serialization
 
     internal class ISerializableDataNode : DataNode<object>
     {
-        private string _factoryTypeName;
-        private string _factoryTypeNamespace;
-        private IList<ISerializableDataMember> _members;
+        private string? _factoryTypeName;
+        private string? _factoryTypeNamespace;
+        private IList<ISerializableDataMember>? _members;
 
         internal ISerializableDataNode()
         {
             dataType = Globals.TypeOfISerializableDataNode;
         }
 
-        internal string FactoryTypeName
+        internal string? FactoryTypeName
         {
             get { return _factoryTypeName; }
             set { _factoryTypeName = value; }
         }
 
-        internal string FactoryTypeNamespace
+        internal string? FactoryTypeNamespace
         {
             get { return _factoryTypeNamespace; }
             set { _factoryTypeNamespace = value; }
         }
 
-        internal IList<ISerializableDataMember> Members
+        internal IList<ISerializableDataMember>? Members
         {
             get { return _members; }
             set { _members = value; }
@@ -375,16 +372,16 @@ namespace System.Runtime.Serialization
 
     internal class ISerializableDataMember
     {
-        private string _name;
-        private IDataNode _value;
+        private IDataNode? _value;
 
-        internal string Name
+        public ISerializableDataMember(string name)
         {
-            get { return _name; }
-            set { _name = value; }
+            Name = name;
         }
 
-        internal IDataNode Value
+        internal string Name { get; }
+
+        internal IDataNode? Value
         {
             get { return _value; }
             set { _value = value; }
index 1ecfbb8..4f31147 100644 (file)
@@ -3,6 +3,7 @@
 
 using System.Xml;
 using System.Collections;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization
 {
@@ -21,25 +22,25 @@ namespace System.Runtime.Serialization
             NullElement,
         }
 
-        private ElementData[] _elements;
-        private ElementData _element;
-        private ElementData _nextElement;
+        private ElementData?[]? _elements;
+        private ElementData? _element;
+        private ElementData? _nextElement;
 
         private ReadState _readState = ReadState.Initial;
         private readonly ExtensionDataNodeType _internalNodeType;
         private XmlNodeType _nodeType;
         private int _depth;
-        private string _localName;
-        private string _ns;
-        private string _prefix;
-        private string _value;
+        private string? _localName;
+        private string? _ns;
+        private string? _prefix;
+        private string? _value;
         private int _attributeCount;
         private int _attributeIndex;
 
         private static readonly object s_prefixLock = new object();
 
 #pragma warning disable 0649
-        private readonly XmlNodeReader _xmlNodeReader;
+        private readonly XmlNodeReader? _xmlNodeReader;
 #pragma warning restore 0649
 
         private readonly XmlObjectSerializerReadContext _context;
@@ -61,9 +62,9 @@ namespace System.Runtime.Serialization
             _context = context;
         }
 
-        internal IDataNode GetCurrentNode()
+        internal IDataNode? GetCurrentNode()
         {
-            IDataNode retVal = _element.dataNode;
+            IDataNode? retVal = _element!.dataNode;
             Skip();
             return retVal;
         }
@@ -82,13 +83,17 @@ namespace System.Runtime.Serialization
             _elements = null;
         }
 
+#pragma warning disable CS8775 // Member must have a non-null value when exiting in some condition.
+        [MemberNotNullWhen(true, nameof(_xmlNodeReader))]
+        [MemberNotNullWhen(false, nameof(_element))]
         private bool IsXmlDataNode { get { return (_internalNodeType == ExtensionDataNodeType.Xml); } }
+#pragma warning restore CS8775 // Member must have a non-null value when exiting in some condition.
 
         public override XmlNodeType NodeType { get { return IsXmlDataNode ? _xmlNodeReader.NodeType : _nodeType; } }
-        public override string LocalName { get { return IsXmlDataNode ? _xmlNodeReader.LocalName : _localName; } }
-        public override string NamespaceURI { get { return IsXmlDataNode ? _xmlNodeReader.NamespaceURI : _ns; } }
-        public override string Prefix { get { return IsXmlDataNode ? _xmlNodeReader.Prefix : _prefix; } }
-        public override string Value { get { return IsXmlDataNode ? _xmlNodeReader.Value : _value; } }
+        public override string LocalName { get { return IsXmlDataNode ? _xmlNodeReader.LocalName : _localName!; } }
+        public override string NamespaceURI { get { return IsXmlDataNode ? _xmlNodeReader.NamespaceURI : _ns!; } }
+        public override string Prefix { get { return IsXmlDataNode ? _xmlNodeReader.Prefix : _prefix!; } }
+        public override string Value { get { return IsXmlDataNode ? _xmlNodeReader.Value : _value!; } }
         public override int Depth { get { return IsXmlDataNode ? _xmlNodeReader.Depth : _depth; } }
         public override int AttributeCount { get { return IsXmlDataNode ? _xmlNodeReader.AttributeCount : _attributeCount; } }
         public override bool EOF { get { return IsXmlDataNode ? _xmlNodeReader.EOF : (_readState == ReadState.EndOfFile); } }
@@ -99,8 +104,9 @@ namespace System.Runtime.Serialization
         public override XmlSpace XmlSpace { get { return IsXmlDataNode ? _xmlNodeReader.XmlSpace : base.XmlSpace; } }
         public override string XmlLang { get { return IsXmlDataNode ? _xmlNodeReader.XmlLang : base.XmlLang; } }
         public override string this[int i] { get { return IsXmlDataNode ? _xmlNodeReader[i] : GetAttribute(i); } }
-        public override string this[string name] { get { return IsXmlDataNode ? _xmlNodeReader[name] : GetAttribute(name); } }
-        public override string this[string name, string namespaceURI] { get { return IsXmlDataNode ? _xmlNodeReader[name, namespaceURI] : GetAttribute(name, namespaceURI); } }
+        public override string? this[string name] { get { return IsXmlDataNode ? _xmlNodeReader[name] : GetAttribute(name); } }
+        // TODO-NULLABLE - unnecessary namespaceURI! - https://github.com/dotnet/roslyn/issues/47221
+        public override string? this[string name, string? namespaceURI] { get { return IsXmlDataNode ? _xmlNodeReader[name, namespaceURI!] : GetAttribute(name, namespaceURI); } }
 
         public override bool MoveToFirstAttribute()
         {
@@ -134,7 +140,7 @@ namespace System.Runtime.Serialization
                     throw new XmlException(SR.InvalidXmlDeserializingExtensionData);
 
                 _nodeType = XmlNodeType.Attribute;
-                AttributeData attribute = _element.attributes[index];
+                AttributeData attribute = _element.attributes![index];
                 _localName = attribute.localName;
                 _ns = attribute.ns;
                 _prefix = attribute.prefix;
@@ -143,14 +149,14 @@ namespace System.Runtime.Serialization
             }
         }
 
-        public override string GetAttribute(string name, string namespaceURI)
+        public override string? GetAttribute(string name, string? namespaceURI)
         {
             if (IsXmlDataNode)
                 return _xmlNodeReader.GetAttribute(name, namespaceURI);
 
             for (int i = 0; i < _element.attributeCount; i++)
             {
-                AttributeData attribute = _element.attributes[i];
+                AttributeData attribute = _element.attributes![i];
                 if (attribute.localName == name && attribute.ns == namespaceURI)
                     return attribute.value;
             }
@@ -158,14 +164,14 @@ namespace System.Runtime.Serialization
             return null;
         }
 
-        public override bool MoveToAttribute(string name, string namespaceURI)
+        public override bool MoveToAttribute(string name, string? namespaceURI)
         {
             if (IsXmlDataNode)
                 return _xmlNodeReader.MoveToAttribute(name, _ns);
 
             for (int i = 0; i < _element.attributeCount; i++)
             {
-                AttributeData attribute = _element.attributes[i];
+                AttributeData attribute = _element.attributes![i];
                 if (attribute.localName == name && attribute.ns == namespaceURI)
                 {
                     MoveToAttribute(i);
@@ -191,7 +197,7 @@ namespace System.Runtime.Serialization
         private void SetElement()
         {
             _nodeType = XmlNodeType.Element;
-            _localName = _element.localName;
+            _localName = _element!.localName;
             _ns = _element.ns;
             _prefix = _element.prefix;
             _value = string.Empty;
@@ -199,12 +205,12 @@ namespace System.Runtime.Serialization
             _attributeIndex = -1;
         }
 
-        public override string LookupNamespace(string prefix)
+        public override string? LookupNamespace(string prefix)
         {
             if (IsXmlDataNode)
                 return _xmlNodeReader.LookupNamespace(prefix);
 
-            return (string)s_prefixToNsTable[prefix];
+            return (string?)s_prefixToNsTable[prefix];
         }
 
         public override void Skip()
@@ -263,7 +269,7 @@ namespace System.Runtime.Serialization
             if (_nodeType == XmlNodeType.Attribute && MoveToNextAttribute())
                 return true;
 
-            MoveNext(_element.dataNode);
+            MoveNext(_element!.dataNode);
 
             switch (_internalNodeType)
             {
@@ -370,7 +376,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        public override string GetAttribute(string name)
+        public override string? GetAttribute(string name)
         {
             if (IsXmlDataNode)
             {
@@ -422,7 +428,7 @@ namespace System.Runtime.Serialization
             return false;
         }
 
-        private void MoveNext(IDataNode dataNode)
+        private void MoveNext(IDataNode? dataNode)
         {
             throw NotImplemented.ByDesign;
         }
@@ -442,7 +448,7 @@ namespace System.Runtime.Serialization
 
         private void PopElement()
         {
-            _prefix = _element.prefix;
+            _prefix = _element!.prefix;
             _localName = _element.localName;
             _ns = _element.ns;
 
@@ -457,6 +463,7 @@ namespace System.Runtime.Serialization
             }
         }
 
+        [MemberNotNull(nameof(_elements))]
         private void GrowElementsIfNeeded()
         {
             if (_elements == null)
@@ -469,25 +476,25 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private ElementData GetNextElement()
+        private ElementData? GetNextElement()
         {
             int nextDepth = _depth + 1;
             return (_elements == null || _elements.Length <= nextDepth || _elements[nextDepth] == null)
                 ? new ElementData() : _elements[nextDepth];
         }
 
-        internal static string GetPrefix(string ns)
+        internal static string GetPrefix(string? ns)
         {
             ns = ns ?? string.Empty;
-            string prefix = (string)s_nsToPrefixTable[ns];
+            string? prefix = (string?)s_nsToPrefixTable[ns];
             if (prefix == null)
             {
                 lock (s_prefixLock)
                 {
-                    prefix = (string)s_nsToPrefixTable[ns];
+                    prefix = (string?)s_nsToPrefixTable[ns];
                     if (prefix == null)
                     {
-                        prefix = (ns == null || ns.Length == 0) ? string.Empty : "p" + s_nsToPrefixTable.Count;
+                        prefix = (ns.Length == 0) ? string.Empty : "p" + s_nsToPrefixTable.Count;
                         AddPrefix(prefix, ns);
                     }
                 }
@@ -508,10 +515,10 @@ namespace System.Runtime.Serialization
     internal class AttributeData
 #endif
     {
-        public string prefix;
-        public string ns;
-        public string localName;
-        public string value;
+        public string? prefix;
+        public string? ns;
+        public string? localName;
+        public string? value;
     }
 
 #if USE_REFEMIT
@@ -520,15 +527,15 @@ namespace System.Runtime.Serialization
     internal class ElementData
 #endif
     {
-        public string localName;
-        public string ns;
-        public string prefix;
+        public string? localName;
+        public string? ns;
+        public string? prefix;
         public int attributeCount;
-        public AttributeData[] attributes;
-        public IDataNode dataNode;
+        public AttributeData[]? attributes;
+        public IDataNode? dataNode;
         public int childElementIndex;
 
-        public void AddAttribute(string prefix, string ns, string name, string value)
+        public void AddAttribute(string prefix, string ns, string name, string? value)
         {
             GrowAttributesIfNeeded();
             AttributeData attribute = attributes[attributeCount];
@@ -541,6 +548,7 @@ namespace System.Runtime.Serialization
             attributeCount++;
         }
 
+        [MemberNotNull(nameof(attributes))]
         private void GrowAttributesIfNeeded()
         {
             if (attributes == null)
index 39881a5..d1f0ec5 100644 (file)
@@ -13,7 +13,7 @@ namespace System.Runtime.Serialization
         internal GenericParameterDataContract(Type type)
             : base(new GenericParameterDataContractCriticalHelper(type))
         {
-            _helper = base.Helper as GenericParameterDataContractCriticalHelper;
+            _helper = (base.Helper as GenericParameterDataContractCriticalHelper)!;
         }
 
         internal int ParameterPosition
index 06fc98f..52b08bf 100644 (file)
@@ -22,7 +22,7 @@ namespace System.Runtime.Serialization
         /// </SecurityNote>
         internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
 
-        private static XmlQualifiedName s_idQualifiedName;
+        private static XmlQualifiedName? s_idQualifiedName;
         internal static XmlQualifiedName IdQualifiedName
         {
             get
@@ -33,7 +33,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static XmlQualifiedName s_refQualifiedName;
+        private static XmlQualifiedName? s_refQualifiedName;
         internal static XmlQualifiedName RefQualifiedName
         {
             get
@@ -44,7 +44,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfObject;
+        private static Type? s_typeOfObject;
         internal static Type TypeOfObject
         {
             get
@@ -55,7 +55,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfValueType;
+        private static Type? s_typeOfValueType;
         internal static Type TypeOfValueType
         {
             get
@@ -66,7 +66,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfArray;
+        private static Type? s_typeOfArray;
         internal static Type TypeOfArray
         {
             get
@@ -77,7 +77,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfString;
+        private static Type? s_typeOfString;
         internal static Type TypeOfString
         {
             get
@@ -88,7 +88,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfInt;
+        private static Type? s_typeOfInt;
         internal static Type TypeOfInt
         {
             get
@@ -99,7 +99,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfULong;
+        private static Type? s_typeOfULong;
         internal static Type TypeOfULong
         {
             get
@@ -110,7 +110,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfVoid;
+        private static Type? s_typeOfVoid;
         internal static Type TypeOfVoid
         {
             get
@@ -121,7 +121,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfByteArray;
+        private static Type? s_typeOfByteArray;
         internal static Type TypeOfByteArray
         {
             get
@@ -132,7 +132,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfTimeSpan;
+        private static Type? s_typeOfTimeSpan;
         internal static Type TypeOfTimeSpan
         {
             get
@@ -143,7 +143,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfGuid;
+        private static Type? s_typeOfGuid;
         internal static Type TypeOfGuid
         {
             get
@@ -154,7 +154,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfDateTimeOffset;
+        private static Type? s_typeOfDateTimeOffset;
         internal static Type TypeOfDateTimeOffset
         {
             get
@@ -165,7 +165,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfDateTimeOffsetAdapter;
+        private static Type? s_typeOfDateTimeOffsetAdapter;
         internal static Type TypeOfDateTimeOffsetAdapter
         {
             get
@@ -176,7 +176,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfUri;
+        private static Type? s_typeOfUri;
         internal static Type TypeOfUri
         {
             get
@@ -187,7 +187,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfTypeEnumerable;
+        private static Type? s_typeOfTypeEnumerable;
         internal static Type TypeOfTypeEnumerable
         {
             get
@@ -198,7 +198,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfStreamingContext;
+        private static Type? s_typeOfStreamingContext;
         internal static Type TypeOfStreamingContext
         {
             get
@@ -209,7 +209,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfISerializable;
+        private static Type? s_typeOfISerializable;
         internal static Type TypeOfISerializable
         {
             get
@@ -220,7 +220,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIDeserializationCallback;
+        private static Type? s_typeOfIDeserializationCallback;
         internal static Type TypeOfIDeserializationCallback
         {
             get
@@ -231,7 +231,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIObjectReference;
+        private static Type? s_typeOfIObjectReference;
         internal static Type TypeOfIObjectReference
         {
             get
@@ -242,7 +242,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlFormatClassWriterDelegate;
+        private static Type? s_typeOfXmlFormatClassWriterDelegate;
         internal static Type TypeOfXmlFormatClassWriterDelegate
         {
             get
@@ -253,7 +253,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlFormatCollectionWriterDelegate;
+        private static Type? s_typeOfXmlFormatCollectionWriterDelegate;
         internal static Type TypeOfXmlFormatCollectionWriterDelegate
         {
             get
@@ -264,7 +264,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlFormatClassReaderDelegate;
+        private static Type? s_typeOfXmlFormatClassReaderDelegate;
         internal static Type TypeOfXmlFormatClassReaderDelegate
         {
             get
@@ -275,7 +275,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlFormatCollectionReaderDelegate;
+        private static Type? s_typeOfXmlFormatCollectionReaderDelegate;
         internal static Type TypeOfXmlFormatCollectionReaderDelegate
         {
             get
@@ -286,7 +286,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlFormatGetOnlyCollectionReaderDelegate;
+        private static Type? s_typeOfXmlFormatGetOnlyCollectionReaderDelegate;
         internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate
         {
             get
@@ -297,7 +297,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfKnownTypeAttribute;
+        private static Type? s_typeOfKnownTypeAttribute;
         internal static Type TypeOfKnownTypeAttribute
         {
             get
@@ -308,7 +308,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfDataContractAttribute;
+        private static Type? s_typeOfDataContractAttribute;
         internal static Type TypeOfDataContractAttribute
         {
             get
@@ -319,7 +319,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfDataMemberAttribute;
+        private static Type? s_typeOfDataMemberAttribute;
         internal static Type TypeOfDataMemberAttribute
         {
             get
@@ -330,7 +330,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfEnumMemberAttribute;
+        private static Type? s_typeOfEnumMemberAttribute;
         internal static Type TypeOfEnumMemberAttribute
         {
             get
@@ -341,7 +341,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfCollectionDataContractAttribute;
+        private static Type? s_typeOfCollectionDataContractAttribute;
         internal static Type TypeOfCollectionDataContractAttribute
         {
             get
@@ -352,7 +352,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfOptionalFieldAttribute;
+        private static Type? s_typeOfOptionalFieldAttribute;
         internal static Type TypeOfOptionalFieldAttribute
         {
             get
@@ -366,7 +366,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfObjectArray;
+        private static Type? s_typeOfObjectArray;
         internal static Type TypeOfObjectArray
         {
             get
@@ -377,7 +377,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfOnSerializingAttribute;
+        private static Type? s_typeOfOnSerializingAttribute;
         internal static Type TypeOfOnSerializingAttribute
         {
             get
@@ -388,7 +388,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfOnSerializedAttribute;
+        private static Type? s_typeOfOnSerializedAttribute;
         internal static Type TypeOfOnSerializedAttribute
         {
             get
@@ -399,7 +399,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfOnDeserializingAttribute;
+        private static Type? s_typeOfOnDeserializingAttribute;
         internal static Type TypeOfOnDeserializingAttribute
         {
             get
@@ -410,7 +410,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfOnDeserializedAttribute;
+        private static Type? s_typeOfOnDeserializedAttribute;
         internal static Type TypeOfOnDeserializedAttribute
         {
             get
@@ -421,7 +421,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfFlagsAttribute;
+        private static Type? s_typeOfFlagsAttribute;
         internal static Type TypeOfFlagsAttribute
         {
             get
@@ -432,7 +432,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIXmlSerializable;
+        private static Type? s_typeOfIXmlSerializable;
         internal static Type TypeOfIXmlSerializable
         {
             get
@@ -443,7 +443,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlSchemaProviderAttribute;
+        private static Type? s_typeOfXmlSchemaProviderAttribute;
         internal static Type TypeOfXmlSchemaProviderAttribute
         {
             get
@@ -454,7 +454,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlRootAttribute;
+        private static Type? s_typeOfXmlRootAttribute;
         internal static Type TypeOfXmlRootAttribute
         {
             get
@@ -465,7 +465,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlQualifiedName;
+        private static Type? s_typeOfXmlQualifiedName;
         internal static Type TypeOfXmlQualifiedName
         {
             get
@@ -476,7 +476,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlSchemaType;
+        private static Type? s_typeOfXmlSchemaType;
         internal static Type TypeOfXmlSchemaType
         {
             get
@@ -490,13 +490,13 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIExtensibleDataObject;
+        private static Type? s_typeOfIExtensibleDataObject;
         internal static Type TypeOfIExtensibleDataObject => s_typeOfIExtensibleDataObject ?? (s_typeOfIExtensibleDataObject = typeof(IExtensibleDataObject));
 
-        private static Type s_typeOfExtensionDataObject;
+        private static Type? s_typeOfExtensionDataObject;
         internal static Type TypeOfExtensionDataObject => s_typeOfExtensionDataObject ?? (s_typeOfExtensionDataObject = typeof(ExtensionDataObject));
 
-        private static Type s_typeOfISerializableDataNode;
+        private static Type? s_typeOfISerializableDataNode;
         internal static Type TypeOfISerializableDataNode
         {
             get
@@ -507,7 +507,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfClassDataNode;
+        private static Type? s_typeOfClassDataNode;
         internal static Type TypeOfClassDataNode
         {
             get
@@ -518,7 +518,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfCollectionDataNode;
+        private static Type? s_typeOfCollectionDataNode;
         internal static Type TypeOfCollectionDataNode
         {
             get
@@ -529,10 +529,10 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlDataNode;
+        private static Type? s_typeOfXmlDataNode;
         internal static Type TypeOfXmlDataNode => s_typeOfXmlDataNode ?? (s_typeOfXmlDataNode = typeof(XmlDataNode));
 
-        private static Type s_typeOfNullable;
+        private static Type? s_typeOfNullable;
         internal static Type TypeOfNullable
         {
             get
@@ -543,7 +543,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIDictionaryGeneric;
+        private static Type? s_typeOfIDictionaryGeneric;
         internal static Type TypeOfIDictionaryGeneric
         {
             get
@@ -554,7 +554,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIDictionary;
+        private static Type? s_typeOfIDictionary;
         internal static Type TypeOfIDictionary
         {
             get
@@ -565,7 +565,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIListGeneric;
+        private static Type? s_typeOfIListGeneric;
         internal static Type TypeOfIListGeneric
         {
             get
@@ -576,7 +576,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIList;
+        private static Type? s_typeOfIList;
         internal static Type TypeOfIList
         {
             get
@@ -587,7 +587,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfICollectionGeneric;
+        private static Type? s_typeOfICollectionGeneric;
         internal static Type TypeOfICollectionGeneric
         {
             get
@@ -598,7 +598,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfICollection;
+        private static Type? s_typeOfICollection;
         internal static Type TypeOfICollection
         {
             get
@@ -609,7 +609,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIEnumerableGeneric;
+        private static Type? s_typeOfIEnumerableGeneric;
         internal static Type TypeOfIEnumerableGeneric
         {
             get
@@ -620,7 +620,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIEnumerable;
+        private static Type? s_typeOfIEnumerable;
         internal static Type TypeOfIEnumerable
         {
             get
@@ -631,7 +631,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIEnumeratorGeneric;
+        private static Type? s_typeOfIEnumeratorGeneric;
         internal static Type TypeOfIEnumeratorGeneric
         {
             get
@@ -642,7 +642,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIEnumerator;
+        private static Type? s_typeOfIEnumerator;
         internal static Type TypeOfIEnumerator
         {
             get
@@ -653,7 +653,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfKeyValuePair;
+        private static Type? s_typeOfKeyValuePair;
         internal static Type TypeOfKeyValuePair
         {
             get
@@ -664,7 +664,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfKeyValuePairAdapter;
+        private static Type? s_typeOfKeyValuePairAdapter;
         internal static Type TypeOfKeyValuePairAdapter
         {
             get
@@ -675,7 +675,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfKeyValue;
+        private static Type? s_typeOfKeyValue;
         internal static Type TypeOfKeyValue
         {
             get
@@ -686,7 +686,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfIDictionaryEnumerator;
+        private static Type? s_typeOfIDictionaryEnumerator;
         internal static Type TypeOfIDictionaryEnumerator
         {
             get
@@ -697,7 +697,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfDictionaryEnumerator;
+        private static Type? s_typeOfDictionaryEnumerator;
         internal static Type TypeOfDictionaryEnumerator
         {
             get
@@ -708,7 +708,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfGenericDictionaryEnumerator;
+        private static Type? s_typeOfGenericDictionaryEnumerator;
         internal static Type TypeOfGenericDictionaryEnumerator
         {
             get
@@ -719,7 +719,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfDictionaryGeneric;
+        private static Type? s_typeOfDictionaryGeneric;
         internal static Type TypeOfDictionaryGeneric
         {
             get
@@ -730,7 +730,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfHashtable;
+        private static Type? s_typeOfHashtable;
         internal static Type TypeOfHashtable
         {
             get
@@ -741,7 +741,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlElement;
+        private static Type? s_typeOfXmlElement;
         internal static Type TypeOfXmlElement
         {
             get
@@ -752,7 +752,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfXmlNodeArray;
+        private static Type? s_typeOfXmlNodeArray;
         internal static Type TypeOfXmlNodeArray
         {
             get
@@ -763,7 +763,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Type s_typeOfDBNull;
+        private static Type? s_typeOfDBNull;
         internal static Type TypeOfDBNull
         {
             get
@@ -774,7 +774,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static Uri s_dataContractXsdBaseNamespaceUri;
+        private static Uri? s_dataContractXsdBaseNamespaceUri;
         internal static Uri DataContractXsdBaseNamespaceUri
         {
             get
@@ -799,7 +799,7 @@ namespace System.Runtime.Serialization
             return true;
         }
 
-        private static MethodBase FilterMethodBases(MethodBase[] methodBases, Type[] parameterTypes, string methodName)
+        private static MethodBase? FilterMethodBases(MethodBase[]? methodBases, Type[] parameterTypes, string methodName)
         {
             if (methodBases == null || string.IsNullOrEmpty(methodName))
                 return null;
@@ -809,23 +809,23 @@ namespace System.Runtime.Serialization
             return matchedMethods.FirstOrDefault();
         }
 
-        internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes)
+        internal static ConstructorInfo? GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes)
         {
-            var constructorInfos = type.GetConstructors(bindingFlags);
-            var constructorInfo = FilterMethodBases(constructorInfos.Cast<MethodBase>().ToArray(), parameterTypes, ".ctor");
+            ConstructorInfo[] constructorInfos = type.GetConstructors(bindingFlags);
+            var constructorInfo = FilterMethodBases(constructorInfos.Cast<MethodBase>().ToArray()!, parameterTypes, ".ctor");
             return constructorInfo != null ? (ConstructorInfo)constructorInfo : null;
         }
 
-        internal static MethodInfo GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Type[] parameterTypes)
+        internal static MethodInfo? GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Type[] parameterTypes)
         {
             var methodInfos = type.GetMethods(bindingFlags);
-            var methodInfo = FilterMethodBases(methodInfos.Cast<MethodBase>().ToArray(), parameterTypes, methodName);
+            var methodInfo = FilterMethodBases(methodInfos.Cast<MethodBase>().ToArray()!, parameterTypes, methodName);
             return methodInfo != null ? (MethodInfo)methodInfo : null;
         }
 
         #endregion
 
-        private static readonly Type s_typeOfScriptObject;
+        private static readonly Type? s_typeOfScriptObject;
 
         internal static ClassDataContract CreateScriptObjectClassDataContract()
         {
index 7f07fb2..035f155 100644 (file)
@@ -10,19 +10,19 @@ namespace System.Runtime.Serialization
 {
     internal class HybridObjectCache
     {
-        private Dictionary<string, object> _objectDictionary;
-        private Dictionary<string, object> _referencedObjectDictionary;
+        private Dictionary<string, object?>? _objectDictionary;
+        private Dictionary<string, object?>? _referencedObjectDictionary;
 
         internal HybridObjectCache()
         {
         }
 
-        internal void Add(string id, object obj)
+        internal void Add(string id, object? obj)
         {
             if (_objectDictionary == null)
-                _objectDictionary = new Dictionary<string, object>();
+                _objectDictionary = new Dictionary<string, object?>();
 
-            object existingObject;
+            object? existingObject;
             if (_objectDictionary.TryGetValue(id, out existingObject))
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.MultipleIdDefinition, id)));
             _objectDictionary.Add(id, obj);
@@ -34,11 +34,11 @@ namespace System.Runtime.Serialization
                 _objectDictionary.Remove(id);
         }
 
-        internal object GetObject(string id)
+        internal object? GetObject(string id)
         {
             if (_referencedObjectDictionary == null)
             {
-                _referencedObjectDictionary = new Dictionary<string, object>();
+                _referencedObjectDictionary = new Dictionary<string, object?>();
                 _referencedObjectDictionary.Add(id, null);
             }
             else
@@ -48,7 +48,7 @@ namespace System.Runtime.Serialization
 
             if (_objectDictionary != null)
             {
-                object obj;
+                object? obj;
                 _objectDictionary.TryGetValue(id, out obj);
                 return obj;
             }
index 701e4ec..4cfbc8f 100644 (file)
@@ -5,6 +5,6 @@ namespace System.Runtime.Serialization
 {
     public interface IExtensibleDataObject
     {
-        ExtensionDataObject ExtensionData { get; set; }
+        ExtensionDataObject? ExtensionData { get; set; }
     }
 }
index 05cc2a2..604040e 100644 (file)
@@ -16,6 +16,7 @@ namespace System.Runtime.Serialization.Json
     using System.Globalization;
     using System.Reflection;
     using System.Security;
+    using System.Diagnostics.CodeAnalysis;
 
     public sealed class DataContractJsonSerializer : XmlObjectSerializer
     {
@@ -27,13 +28,13 @@ namespace System.Runtime.Serialization.Json
         private const char WHITESPACE = ' ';
 
 
-        internal IList<Type> knownTypeList;
-        internal DataContractDictionary knownDataContracts;
+        internal IList<Type>? knownTypeList;
+        internal DataContractDictionary? knownDataContracts;
         private readonly EmitTypeInformation _emitTypeInformation;
-        private ReadOnlyCollection<Type> _knownTypeCollection;
+        private ReadOnlyCollection<Type>? _knownTypeCollection;
         private readonly int _maxItemsInObjectGraph;
         private readonly bool _serializeReadOnlyTypes;
-        private readonly DateTimeFormat _dateTimeFormat;
+        private readonly DateTimeFormat? _dateTimeFormat;
         private readonly bool _useSimpleDictionaryFormat;
 
         private readonly DataContractJsonSerializerImpl _serializer;
@@ -44,32 +45,32 @@ namespace System.Runtime.Serialization.Json
             _serializer = new DataContractJsonSerializerImpl(type);
         }
 
-        public DataContractJsonSerializer(Type type, string rootName)
+        public DataContractJsonSerializer(Type type, string? rootName)
             : this(type, rootName, null)
         {
         }
 
-        public DataContractJsonSerializer(Type type, XmlDictionaryString rootName)
+        public DataContractJsonSerializer(Type type, XmlDictionaryString? rootName)
             : this(type, rootName, null)
         {
         }
 
-        public DataContractJsonSerializer(Type type, IEnumerable<Type> knownTypes)
+        public DataContractJsonSerializer(Type type, IEnumerable<Type>? knownTypes)
         {
             _serializer = new DataContractJsonSerializerImpl(type, knownTypes);
         }
 
-        public DataContractJsonSerializer(Type type, string rootName, IEnumerable<Type> knownTypes)
+        public DataContractJsonSerializer(Type type, string? rootName, IEnumerable<Type>? knownTypes)
             : this(type, new DataContractJsonSerializerSettings() { RootName = rootName, KnownTypes = knownTypes })
         {
         }
 
-        public DataContractJsonSerializer(Type type, XmlDictionaryString rootName, IEnumerable<Type> knownTypes)
+        public DataContractJsonSerializer(Type type, XmlDictionaryString? rootName, IEnumerable<Type>? knownTypes)
         {
             _serializer = new DataContractJsonSerializerImpl(type, rootName, knownTypes);
         }
 
-        public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings settings)
+        public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings? settings)
         {
             _serializer = new DataContractJsonSerializerImpl(type, settings);
         }
@@ -98,7 +99,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal override DataContractDictionary KnownDataContracts
+        internal override DataContractDictionary? KnownDataContracts
         {
             get
             {
@@ -119,7 +120,7 @@ namespace System.Runtime.Serialization.Json
             get { return _maxItemsInObjectGraph; }
         }
 
-        public DateTimeFormat DateTimeFormat
+        public DateTimeFormat? DateTimeFormat
         {
             get
             {
@@ -171,42 +172,42 @@ namespace System.Runtime.Serialization.Json
             return contract;
         }
 
-        public override void WriteObject(Stream stream, object graph)
+        public override void WriteObject(Stream stream, object? graph)
         {
             _serializer.WriteObject(stream, graph);
         }
 
-        public override void WriteObject(XmlWriter writer, object graph)
+        public override void WriteObject(XmlWriter writer, object? graph)
         {
             _serializer.WriteObject(writer, graph);
         }
 
-        public override void WriteObject(XmlDictionaryWriter writer, object graph)
+        public override void WriteObject(XmlDictionaryWriter writer, object? graph)
         {
             _serializer.WriteObject(writer, graph);
         }
 
-        public override object ReadObject(Stream stream)
+        public override object? ReadObject(Stream stream)
         {
             return _serializer.ReadObject(stream);
         }
 
-        public override object ReadObject(XmlReader reader)
+        public override object? ReadObject(XmlReader reader)
         {
             return _serializer.ReadObject(reader);
         }
 
-        public override object ReadObject(XmlReader reader, bool verifyObjectName)
+        public override object? ReadObject(XmlReader reader, bool verifyObjectName)
         {
             return _serializer.ReadObject(reader, verifyObjectName);
         }
 
-        public override object ReadObject(XmlDictionaryReader reader)
+        public override object? ReadObject(XmlDictionaryReader reader)
         {
             return _serializer.ReadObject(reader);
         }
 
-        private List<Type> GetKnownTypesFromContext(XmlObjectSerializerContext context, IList<Type> serializerKnownTypeList)
+        private List<Type> GetKnownTypesFromContext(XmlObjectSerializerContext context, IList<Type>? serializerKnownTypeList)
         {
             List<Type> knownTypesList = new List<Type>();
             if (context != null)
@@ -241,10 +242,8 @@ namespace System.Runtime.Serialization.Json
 
         internal static void InvokeOnSerializing(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context)
         {
-            if (contract is ClassDataContract)
+            if (contract is ClassDataContract classContract)
             {
-                ClassDataContract classContract = contract as ClassDataContract;
-
                 if (classContract.BaseContract != null)
                     InvokeOnSerializing(value, classContract.BaseContract, context);
                 if (classContract.OnSerializing != null)
@@ -279,10 +278,8 @@ namespace System.Runtime.Serialization.Json
 
         internal static void InvokeOnSerialized(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context)
         {
-            if (contract is ClassDataContract)
+            if (contract is ClassDataContract classContract)
             {
-                ClassDataContract classContract = contract as ClassDataContract;
-
                 if (classContract.BaseContract != null)
                     InvokeOnSerialized(value, classContract.BaseContract, context);
                 if (classContract.OnSerialized != null)
@@ -317,10 +314,8 @@ namespace System.Runtime.Serialization.Json
 
         internal static void InvokeOnDeserializing(object value, DataContract contract, XmlObjectSerializerReadContextComplexJson context)
         {
-            if (contract is ClassDataContract)
+            if (contract is ClassDataContract classContract)
             {
-                ClassDataContract classContract = contract as ClassDataContract;
-
                 if (classContract.BaseContract != null)
                     InvokeOnDeserializing(value, classContract.BaseContract, context);
                 if (classContract.OnDeserializing != null)
@@ -355,10 +350,8 @@ namespace System.Runtime.Serialization.Json
 
         internal static void InvokeOnDeserialized(object value, DataContract contract, XmlObjectSerializerReadContextComplexJson context)
         {
-            if (contract is ClassDataContract)
+            if (contract is ClassDataContract classContract)
             {
-                ClassDataContract classContract = contract as ClassDataContract;
-
                 if (classContract.BaseContract != null)
                     InvokeOnDeserialized(value, classContract.BaseContract, context);
                 if (classContract.OnDeserialized != null)
@@ -427,12 +420,12 @@ namespace System.Runtime.Serialization.Json
             return XmlConvert.DecodeName(xmlName);
         }
 
-        internal static XmlDictionaryString ConvertXmlNameToJsonName(XmlDictionaryString xmlName)
+        internal static XmlDictionaryString? ConvertXmlNameToJsonName(XmlDictionaryString? xmlName)
         {
             return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value));
         }
 
-        internal static object ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context)
+        internal static object? ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context)
         {
             return JsonDataContract.GetJsonDataContract(contract).ReadJsonValue(reader, context);
         }
@@ -442,22 +435,22 @@ namespace System.Runtime.Serialization.Json
             contract.WriteJsonValue(writer, graph, context, declaredTypeHandle);
         }
 
-        public override void WriteStartObject(XmlWriter writer, object graph)
+        public override void WriteStartObject(XmlWriter writer, object? graph)
         {
             _serializer.WriteStartObject(writer, graph);
         }
 
-        public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
+        public override void WriteStartObject(XmlDictionaryWriter writer, object? graph)
         {
             _serializer.WriteStartObject(writer, graph);
         }
 
-        public override void WriteObjectContent(XmlWriter writer, object graph)
+        public override void WriteObjectContent(XmlWriter writer, object? graph)
         {
             _serializer.WriteObjectContent(writer, graph);
         }
 
-        public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
+        public override void WriteObjectContent(XmlDictionaryWriter writer, object? graph)
         {
             _serializer.WriteObjectContent(writer, graph);
         }
@@ -472,7 +465,7 @@ namespace System.Runtime.Serialization.Json
             _serializer.WriteEndObject(writer);
         }
 
-        public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
+        public override object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
         {
             return _serializer.ReadObject(reader, verifyObjectName);
         }
@@ -490,38 +483,38 @@ namespace System.Runtime.Serialization.Json
 
     internal sealed class DataContractJsonSerializerImpl : XmlObjectSerializer
     {
-        internal IList<Type> knownTypeList;
-        internal DataContractDictionary knownDataContracts;
+        internal IList<Type>? knownTypeList;
+        internal DataContractDictionary? knownDataContracts;
         private EmitTypeInformation _emitTypeInformation;
         private bool _ignoreExtensionDataObject;
-        private ReadOnlyCollection<Type> _knownTypeCollection;
+        private ReadOnlyCollection<Type>? _knownTypeCollection;
         private int _maxItemsInObjectGraph;
-        private DataContract _rootContract; // post-surrogate
-        private XmlDictionaryString _rootName;
+        private DataContract? _rootContract; // post-surrogate
+        private XmlDictionaryString? _rootName;
         private bool _rootNameRequiresMapping;
         private Type _rootType;
         private bool _serializeReadOnlyTypes;
-        private DateTimeFormat _dateTimeFormat;
+        private DateTimeFormat? _dateTimeFormat;
         private bool _useSimpleDictionaryFormat;
 
         public DataContractJsonSerializerImpl(Type type)
-            : this(type, (IEnumerable<Type>)null)
+            : this(type, (IEnumerable<Type>?)null)
         {
         }
 
-        public DataContractJsonSerializerImpl(Type type, IEnumerable<Type> knownTypes)
+        public DataContractJsonSerializerImpl(Type type, IEnumerable<Type>? knownTypes)
             : this(type, null, knownTypes, int.MaxValue, false, false)
         {
         }
 
-        public DataContractJsonSerializerImpl(Type type, XmlDictionaryString rootName, IEnumerable<Type> knownTypes)
+        public DataContractJsonSerializerImpl(Type type, XmlDictionaryString? rootName, IEnumerable<Type>? knownTypes)
             : this(type, rootName, knownTypes, int.MaxValue, false, false)
         {
         }
 
         internal DataContractJsonSerializerImpl(Type type,
-            XmlDictionaryString rootName,
-            IEnumerable<Type> knownTypes,
+            XmlDictionaryString? rootName,
+            IEnumerable<Type>? knownTypes,
             int maxItemsInObjectGraph,
             bool ignoreExtensionDataObject,
             bool alwaysEmitTypeInformation)
@@ -530,14 +523,14 @@ namespace System.Runtime.Serialization.Json
             Initialize(type, rootName, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, emitTypeInformation, false, null, false);
         }
 
-        public DataContractJsonSerializerImpl(Type type, DataContractJsonSerializerSettings settings)
+        public DataContractJsonSerializerImpl(Type type, DataContractJsonSerializerSettings? settings)
         {
             if (settings == null)
             {
                 settings = new DataContractJsonSerializerSettings();
             }
 
-            XmlDictionaryString rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName);
+            XmlDictionaryString? rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName);
             Initialize(type, rootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject,
                 settings.EmitTypeInformation, settings.SerializeReadOnlyTypes, settings.DateTimeFormat, settings.UseSimpleDictionaryFormat);
         }
@@ -561,7 +554,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal override DataContractDictionary KnownDataContracts
+        internal override DataContractDictionary? KnownDataContracts
         {
             get
             {
@@ -606,7 +599,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        public DateTimeFormat DateTimeFormat
+        public DateTimeFormat? DateTimeFormat
         {
             get
             {
@@ -655,28 +648,28 @@ namespace System.Runtime.Serialization.Json
             return IsStartObjectHandleExceptions(new JsonReaderDelegator(reader));
         }
 
-        public override object ReadObject(Stream stream)
+        public override object? ReadObject(Stream stream)
         {
             CheckNull(stream, nameof(stream));
             return ReadObject(JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max));
         }
 
-        public override object ReadObject(XmlReader reader)
+        public override object? ReadObject(XmlReader reader)
         {
             return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), true);
         }
 
-        public override object ReadObject(XmlReader reader, bool verifyObjectName)
+        public override object? ReadObject(XmlReader reader, bool verifyObjectName)
         {
             return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), verifyObjectName);
         }
 
-        public override object ReadObject(XmlDictionaryReader reader)
+        public override object? ReadObject(XmlDictionaryReader reader)
         {
             return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), true); // verifyObjectName
         }
 
-        public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
+        public override object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
         {
             return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), verifyObjectName);
         }
@@ -694,7 +687,7 @@ namespace System.Runtime.Serialization.Json
         }
 
 
-        public override void WriteObject(Stream stream, object graph)
+        public override void WriteObject(Stream stream, object? graph)
         {
             CheckNull(stream, nameof(stream));
             XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, false); //  ownsStream
@@ -702,39 +695,39 @@ namespace System.Runtime.Serialization.Json
             jsonWriter.Flush();
         }
 
-        public override void WriteObject(XmlWriter writer, object graph)
+        public override void WriteObject(XmlWriter writer, object? graph)
         {
             WriteObjectHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph);
         }
 
-        public override void WriteObject(XmlDictionaryWriter writer, object graph)
+        public override void WriteObject(XmlDictionaryWriter writer, object? graph)
         {
             WriteObjectHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph);
         }
 
-        public override void WriteObjectContent(XmlWriter writer, object graph)
+        public override void WriteObjectContent(XmlWriter writer, object? graph)
         {
             WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph);
         }
 
-        public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
+        public override void WriteObjectContent(XmlDictionaryWriter writer, object? graph)
         {
             WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph);
         }
 
-        public override void WriteStartObject(XmlWriter writer, object graph)
+        public override void WriteStartObject(XmlWriter writer, object? graph)
         {
             // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in start object
             WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph);
         }
 
-        public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
+        public override void WriteStartObject(XmlDictionaryWriter writer, object? graph)
         {
             // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in start object
             WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph);
         }
 
-        internal static bool CheckIfJsonNameRequiresMapping(string jsonName)
+        internal static bool CheckIfJsonNameRequiresMapping(string? jsonName)
         {
             if (jsonName != null)
             {
@@ -754,7 +747,7 @@ namespace System.Runtime.Serialization.Json
             return false;
         }
 
-        internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString jsonName)
+        internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString? jsonName)
         {
             return (jsonName == null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value);
         }
@@ -774,14 +767,15 @@ namespace System.Runtime.Serialization.Json
             return XmlConvert.DecodeName(xmlName);
         }
 
-        internal static XmlDictionaryString ConvertXmlNameToJsonName(XmlDictionaryString xmlName)
+        [return: NotNullIfNotNull("xmlName")]
+        internal static XmlDictionaryString? ConvertXmlNameToJsonName(XmlDictionaryString? xmlName)
         {
             return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value));
         }
 
         internal static bool IsJsonLocalName(XmlReaderDelegator reader, string elementName)
         {
-            string name;
+            string? name;
             if (XmlObjectSerializerReadContextComplexJson.TryGetJsonLocalName(reader, out name))
             {
                 return (elementName == name);
@@ -789,7 +783,7 @@ namespace System.Runtime.Serialization.Json
             return false;
         }
 
-        internal static object ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context)
+        internal static object? ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson? context)
         {
             return JsonDataContract.GetJsonDataContract(contract).ReadJsonValue(reader, context);
         }
@@ -799,17 +793,17 @@ namespace System.Runtime.Serialization.Json
             writer.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.nullString); //  prefix //  namespace
         }
 
-        internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
+        internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle)
         {
             contract.WriteJsonValue(writer, graph, context, declaredTypeHandle);
         }
 
-        internal override Type GetDeserializeType()
+        internal override Type? GetDeserializeType()
         {
             return _rootType;
         }
 
-        internal override Type GetSerializeType(object graph)
+        internal override Type? GetSerializeType(object? graph)
         {
             return (graph == null) ? _rootType : graph.GetType();
         }
@@ -824,7 +818,7 @@ namespace System.Runtime.Serialization.Json
             return IsJsonLocalName(reader, RootName.Value);
         }
 
-        internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName)
+        internal override object? InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName)
         {
             if (MaxItemsInObjectGraph == 0)
             {
@@ -858,14 +852,14 @@ namespace System.Runtime.Serialization.Json
             writer.WriteEndElement();
         }
 
-        internal override void InternalWriteObject(XmlWriterDelegator writer, object graph)
+        internal override void InternalWriteObject(XmlWriterDelegator writer, object? graph)
         {
             InternalWriteStartObject(writer, graph);
             InternalWriteObjectContent(writer, graph);
             InternalWriteEndObject(writer);
         }
 
-        internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph)
+        internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object? graph)
         {
             if (MaxItemsInObjectGraph == 0)
             {
@@ -917,7 +911,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph)
+        internal override void InternalWriteStartObject(XmlWriterDelegator writer, object? graph)
         {
             if (_rootNameRequiresMapping)
             {
@@ -932,7 +926,7 @@ namespace System.Runtime.Serialization.Json
 
         private void AddCollectionItemTypeToKnownTypes(Type knownType)
         {
-            Type itemType;
+            Type? itemType;
             Type typeToCheck = knownType;
             while (CollectionDataContract.IsCollection(typeToCheck, out itemType))
             {
@@ -940,18 +934,19 @@ namespace System.Runtime.Serialization.Json
                 {
                     itemType = Globals.TypeOfKeyValuePair.MakeGenericType(itemType.GenericTypeArguments);
                 }
-                this.knownTypeList.Add(itemType);
+                this.knownTypeList!.Add(itemType);
                 typeToCheck = itemType;
             }
         }
 
+        [MemberNotNull(nameof(_rootType))]
         private void Initialize(Type type,
-            IEnumerable<Type> knownTypes,
+            IEnumerable<Type>? knownTypes,
             int maxItemsInObjectGraph,
             bool ignoreExtensionDataObject,
             EmitTypeInformation emitTypeInformation,
             bool serializeReadOnlyTypes,
-            DateTimeFormat dateTimeFormat,
+            DateTimeFormat? dateTimeFormat,
             bool useSimpleDictionaryFormat)
         {
             CheckNull(type, nameof(type));
@@ -982,14 +977,15 @@ namespace System.Runtime.Serialization.Json
             _useSimpleDictionaryFormat = useSimpleDictionaryFormat;
         }
 
+        [MemberNotNull(nameof(_rootType))]
         private void Initialize(Type type,
-            XmlDictionaryString rootName,
-            IEnumerable<Type> knownTypes,
+            XmlDictionaryString? rootName,
+            IEnumerable<Type>? knownTypes,
             int maxItemsInObjectGraph,
             bool ignoreExtensionDataObject,
             EmitTypeInformation emitTypeInformation,
             bool serializeReadOnlyTypes,
-            DateTimeFormat dateTimeFormat,
+            DateTimeFormat? dateTimeFormat,
             bool useSimpleDictionaryFormat)
         {
             Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, emitTypeInformation, serializeReadOnlyTypes, dateTimeFormat, useSimpleDictionaryFormat);
index efddc3e..e3958d8 100644 (file)
@@ -17,12 +17,12 @@ namespace System.Runtime.Serialization.Json
         /// <summary>
         /// Gets or sets Dummy documentation
         /// </summary>
-        public string RootName { get; set; }
+        public string? RootName { get; set; }
 
         /// <summary>
         /// Gets or sets Dummy documentation
         /// </summary>
-        public IEnumerable<Type> KnownTypes { get; set; }
+        public IEnumerable<Type>? KnownTypes { get; set; }
 
         /// <summary>
         /// Gets or sets Dummy documentation
@@ -53,7 +53,7 @@ namespace System.Runtime.Serialization.Json
         /// <summary>
         /// Gets or sets Dummy documentation
         /// </summary>
-        public DateTimeFormat DateTimeFormat { get; set; }
+        public DateTimeFormat? DateTimeFormat { get; set; }
 
         /// <summary>
         /// Gets or sets a value indicating whether Dummy documentation
index 4f5656d..6986ae6 100644 (file)
@@ -10,10 +10,10 @@ namespace System.Runtime.Serialization.Json
 {
     public interface IXmlJsonReaderInitializer
     {
-        void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas,
-            OnXmlDictionaryReaderClose onClose);
+        void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas,
+            OnXmlDictionaryReaderClose? onClose);
 
-        void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas,
-            OnXmlDictionaryReaderClose onClose);
+        void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas,
+            OnXmlDictionaryReaderClose? onClose);
     }
 }
index 1d763d2..19ac608 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Runtime.Serialization.Json
         {
         }
 
-        public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
+        public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context)
         {
             if (context == null)
             {
index 3913290..13e8a40 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Runtime.Serialization.Json
         public JsonClassDataContract(ClassDataContract traditionalDataContract)
             : base(new JsonClassDataContractCriticalHelper(traditionalDataContract))
         {
-            _helper = base.Helper as JsonClassDataContractCriticalHelper;
+            _helper = (base.Helper as JsonClassDataContractCriticalHelper)!;
         }
 
         private JsonFormatClassReaderDelegate CreateJsonFormatReaderDelegate()
@@ -87,13 +87,13 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal XmlDictionaryString[] MemberNames => _helper.MemberNames;
+        internal XmlDictionaryString[]? MemberNames => _helper.MemberNames;
 
         internal override string TypeName => _helper.TypeName;
 
         private ClassDataContract TraditionalClassDataContract => _helper.TraditionalClassDataContract;
 
-        public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
+        public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context)
         {
             jsonReader.Read();
             object o = JsonFormatReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, MemberNames);
@@ -101,17 +101,18 @@ namespace System.Runtime.Serialization.Json
             return o;
         }
 
-        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
+        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle)
         {
+            Debug.Assert(context != null);
             jsonWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString);
             JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalClassDataContract, MemberNames);
         }
 
         private class JsonClassDataContractCriticalHelper : JsonDataContractCriticalHelper
         {
-            private JsonFormatClassReaderDelegate _jsonFormatReaderDelegate;
-            private JsonFormatClassWriterDelegate _jsonFormatWriterDelegate;
-            private XmlDictionaryString[] _memberNames;
+            private JsonFormatClassReaderDelegate? _jsonFormatReaderDelegate;
+            private JsonFormatClassWriterDelegate? _jsonFormatWriterDelegate;
+            private XmlDictionaryString[]? _memberNames;
             private readonly ClassDataContract _traditionalClassDataContract;
             private readonly string _typeName;
 
@@ -123,19 +124,19 @@ namespace System.Runtime.Serialization.Json
                 CopyMembersAndCheckDuplicateNames();
             }
 
-            internal JsonFormatClassReaderDelegate JsonFormatReaderDelegate
+            internal JsonFormatClassReaderDelegate? JsonFormatReaderDelegate
             {
                 get { return _jsonFormatReaderDelegate; }
                 set { _jsonFormatReaderDelegate = value; }
             }
 
-            internal JsonFormatClassWriterDelegate JsonFormatWriterDelegate
+            internal JsonFormatClassWriterDelegate? JsonFormatWriterDelegate
             {
                 get { return _jsonFormatWriterDelegate; }
                 set { _jsonFormatWriterDelegate = value; }
             }
 
-            internal XmlDictionaryString[] MemberNames
+            internal XmlDictionaryString[]? MemberNames
             {
                 get { return _memberNames; }
             }
@@ -150,7 +151,7 @@ namespace System.Runtime.Serialization.Json
                 if (_traditionalClassDataContract.MemberNames != null)
                 {
                     int memberCount = _traditionalClassDataContract.MemberNames.Length;
-                    Dictionary<string, object> memberTable = new Dictionary<string, object>(memberCount);
+                    Dictionary<string, object?> memberTable = new Dictionary<string, object?>(memberCount);
                     XmlDictionaryString[] decodedMemberNames = new XmlDictionaryString[memberCount];
                     for (int i = 0; i < memberCount; i++)
                     {
index c2dc630..3374eb7 100644 (file)
@@ -1,6 +1,7 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System.Diagnostics;
 using System.Reflection;
 using System.Runtime.CompilerServices;
 using System.Threading;
@@ -15,7 +16,7 @@ namespace System.Runtime.Serialization.Json
         public JsonCollectionDataContract(CollectionDataContract traditionalDataContract)
             : base(new JsonCollectionDataContractCriticalHelper(traditionalDataContract))
         {
-            _helper = base.Helper as JsonCollectionDataContractCriticalHelper;
+            _helper = (base.Helper as JsonCollectionDataContractCriticalHelper)!;
         }
 
         private JsonFormatCollectionReaderDelegate CreateJsonFormatReaderDelegate()
@@ -129,10 +130,12 @@ namespace System.Runtime.Serialization.Json
 
         private CollectionDataContract TraditionalCollectionDataContract => _helper.TraditionalCollectionDataContract;
 
-        public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
+        public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context)
         {
+            Debug.Assert(context != null);
+
             jsonReader.Read();
-            object o = null;
+            object? o = null;
             if (context.IsGetOnlyCollection)
             {
                 // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
@@ -147,8 +150,9 @@ namespace System.Runtime.Serialization.Json
             return o;
         }
 
-        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
+        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle)
         {
+            Debug.Assert(context != null);
             // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
             context.IsGetOnlyCollection = false;
             JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalCollectionDataContract);
@@ -156,9 +160,9 @@ namespace System.Runtime.Serialization.Json
 
         private class JsonCollectionDataContractCriticalHelper : JsonDataContractCriticalHelper
         {
-            private JsonFormatCollectionReaderDelegate _jsonFormatReaderDelegate;
-            private JsonFormatGetOnlyCollectionReaderDelegate _jsonFormatGetOnlyReaderDelegate;
-            private JsonFormatCollectionWriterDelegate _jsonFormatWriterDelegate;
+            private JsonFormatCollectionReaderDelegate? _jsonFormatReaderDelegate;
+            private JsonFormatGetOnlyCollectionReaderDelegate? _jsonFormatGetOnlyReaderDelegate;
+            private JsonFormatCollectionWriterDelegate? _jsonFormatWriterDelegate;
             private readonly CollectionDataContract _traditionalCollectionDataContract;
 
             public JsonCollectionDataContractCriticalHelper(CollectionDataContract traditionalDataContract)
@@ -167,19 +171,19 @@ namespace System.Runtime.Serialization.Json
                 _traditionalCollectionDataContract = traditionalDataContract;
             }
 
-            internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate
+            internal JsonFormatCollectionReaderDelegate? JsonFormatReaderDelegate
             {
                 get { return _jsonFormatReaderDelegate; }
                 set { _jsonFormatReaderDelegate = value; }
             }
 
-            internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate
+            internal JsonFormatGetOnlyCollectionReaderDelegate? JsonFormatGetOnlyReaderDelegate
             {
                 get { return _jsonFormatGetOnlyReaderDelegate; }
                 set { _jsonFormatGetOnlyReaderDelegate = value; }
             }
 
-            internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate
+            internal JsonFormatCollectionWriterDelegate? JsonFormatWriterDelegate
             {
                 get { return _jsonFormatWriterDelegate; }
                 set { _jsonFormatWriterDelegate = value; }
index a66b741..be57273 100644 (file)
@@ -6,6 +6,7 @@ using System.Runtime;
 using System.Runtime.Serialization;
 using System.Reflection;
 using System.Xml;
+using System.Diagnostics;
 
 namespace System.Runtime.Serialization.Json
 {
@@ -23,26 +24,26 @@ namespace System.Runtime.Serialization.Json
             _helper = helper;
         }
 
-        internal virtual string TypeName => null;
+        internal virtual string? TypeName => null;
 
         protected JsonDataContractCriticalHelper Helper => _helper;
 
         protected DataContract TraditionalDataContract => _helper.TraditionalDataContract;
 
-        private Dictionary<XmlQualifiedName, DataContract> KnownDataContracts => _helper.KnownDataContracts;
+        private Dictionary<XmlQualifiedName, DataContract>? KnownDataContracts => _helper.KnownDataContracts;
 
-        public static JsonReadWriteDelegates GetGeneratedReadWriteDelegates(DataContract c)
+        public static JsonReadWriteDelegates? GetGeneratedReadWriteDelegates(DataContract c)
         {
             // this method used to be rewritten by an IL transform
             // with the restructuring for multi-file, this is no longer true - instead
             // this has become a normal method
-            JsonReadWriteDelegates result;
+            JsonReadWriteDelegates? result;
             return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null;
         }
 
         internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c)
         {
-            JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c);
+            JsonReadWriteDelegates? result = GetGeneratedReadWriteDelegates(c);
             if (result == null)
             {
                 throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType));
@@ -53,9 +54,9 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal static JsonReadWriteDelegates TryGetReadWriteDelegatesFromGeneratedAssembly(DataContract c)
+        internal static JsonReadWriteDelegates? TryGetReadWriteDelegatesFromGeneratedAssembly(DataContract c)
         {
-            JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c);
+            JsonReadWriteDelegates? result = GetGeneratedReadWriteDelegates(c);
             return result;
         }
 
@@ -64,27 +65,27 @@ namespace System.Runtime.Serialization.Json
             return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract);
         }
 
-        public object ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
+        public object? ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context)
         {
             PushKnownDataContracts(context);
-            object deserializedObject = ReadJsonValueCore(jsonReader, context);
+            object? deserializedObject = ReadJsonValueCore(jsonReader, context);
             PopKnownDataContracts(context);
             return deserializedObject;
         }
 
-        public virtual object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
+        public virtual object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context)
         {
             return TraditionalDataContract.ReadXmlValue(jsonReader, context);
         }
 
-        public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
+        public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle)
         {
             PushKnownDataContracts(context);
             WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle);
             PopKnownDataContracts(context);
         }
 
-        public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
+        public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle)
         {
             TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context);
         }
@@ -108,18 +109,20 @@ namespace System.Runtime.Serialization.Json
             return false;
         }
 
-        protected void PopKnownDataContracts(XmlObjectSerializerContext context)
+        protected void PopKnownDataContracts(XmlObjectSerializerContext? context)
         {
             if (KnownDataContracts != null)
             {
+                Debug.Assert(context != null);
                 context.scopedKnownTypes.Pop();
             }
         }
 
-        protected void PushKnownDataContracts(XmlObjectSerializerContext context)
+        protected void PushKnownDataContracts(XmlObjectSerializerContext? context)
         {
             if (KnownDataContracts != null)
             {
+                Debug.Assert(context != null);
                 context.scopedKnownTypes.Push(KnownDataContracts);
             }
         }
@@ -134,7 +137,7 @@ namespace System.Runtime.Serialization.Json
 
             private static readonly TypeHandleRef s_typeHandleRef = new TypeHandleRef();
             private static readonly Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer());
-            private Dictionary<XmlQualifiedName, DataContract> _knownDataContracts;
+            private Dictionary<XmlQualifiedName, DataContract>? _knownDataContracts;
             private readonly DataContract _traditionalDataContract;
             private readonly string _typeName;
 
@@ -145,7 +148,7 @@ namespace System.Runtime.Serialization.Json
                 _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value));
             }
 
-            internal Dictionary<XmlQualifiedName, DataContract> KnownDataContracts => _knownDataContracts;
+            internal Dictionary<XmlQualifiedName, DataContract>? KnownDataContracts => _knownDataContracts;
 
             internal DataContract TraditionalDataContract => _traditionalDataContract;
 
@@ -167,7 +170,7 @@ namespace System.Runtime.Serialization.Json
             {
                 lock (s_cacheLock)
                 {
-                    IntRef id;
+                    IntRef? id;
                     s_typeHandleRef.Value = typeHandle;
                     if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id))
                     {
@@ -269,7 +272,7 @@ namespace System.Runtime.Serialization.Json
                 {
                     foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in _traditionalDataContract.KnownDataContracts)
                     {
-                        CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract;
+                        CollectionDataContract? collectionDataContract = knownDataContract.Value as CollectionDataContract;
                         while (collectionDataContract != null)
                         {
                             DataContract itemContract = collectionDataContract.ItemContract;
@@ -309,10 +312,10 @@ namespace System.Runtime.Serialization.Json
             return s_jsonDelegates;
         }
 
-        public JsonFormatClassWriterDelegate ClassWriterDelegate { get; set; }
-        public JsonFormatClassReaderDelegate ClassReaderDelegate { get; set; }
-        public JsonFormatCollectionWriterDelegate CollectionWriterDelegate { get; set; }
-        public JsonFormatCollectionReaderDelegate CollectionReaderDelegate { get; set; }
-        public JsonFormatGetOnlyCollectionReaderDelegate GetOnlyCollectionReaderDelegate { get; set; }
+        public JsonFormatClassWriterDelegate? ClassWriterDelegate { get; set; }
+        public JsonFormatClassReaderDelegate? ClassReaderDelegate { get; set; }
+        public JsonFormatCollectionWriterDelegate? CollectionWriterDelegate { get; set; }
+        public JsonFormatCollectionReaderDelegate? CollectionReaderDelegate { get; set; }
+        public JsonFormatGetOnlyCollectionReaderDelegate? GetOnlyCollectionReaderDelegate { get; set; }
     }
 }
index 3ed7266..939f83b 100644 (file)
@@ -1,6 +1,8 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.IO;
 using System.Text;
 using System.Xml;
@@ -22,18 +24,18 @@ namespace System.Runtime.Serialization.Json
         private readonly byte[] _byteBuffer = new byte[1];
         private int _byteCount;
         private int _byteOffset;
-        private byte[] _bytes;
-        private char[] _chars;
-        private Decoder _dec;
-        private Encoder _enc;
-        private Encoding _encoding;
+        private byte[]? _bytes;
+        private char[]? _chars;
+        private Decoder? _dec;
+        private Encoder? _enc;
+        private Encoding? _encoding;
 
         private SupportedEncoding _encodingCode;
         private readonly bool _isReading;
 
-        private Stream _stream;
+        private Stream _stream = null!; // initialized in InitForXXX
 
-        public JsonEncodingStreamWrapper(Stream stream, Encoding encoding, bool isReader)
+        public JsonEncodingStreamWrapper(Stream stream, Encoding? encoding, bool isReader)
         {
             _isReading = isReader;
             if (isReader)
@@ -128,7 +130,7 @@ namespace System.Runtime.Serialization.Json
             set { _stream.WriteTimeout = value; }
         }
 
-        public static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding)
+        public static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding? encoding)
         {
             try
             {
@@ -186,6 +188,8 @@ namespace System.Runtime.Serialization.Json
                         return _stream.Read(buffer, offset, count);
                     }
 
+                    Debug.Assert(_bytes != null);
+                    Debug.Assert(_chars != null);
                     // No more bytes than can be turned into characters
                     _byteOffset = 0;
                     _byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2);
@@ -200,7 +204,7 @@ namespace System.Runtime.Serialization.Json
                     CleanupCharBreak();
 
                     // Change encoding
-                    int charCount = _encoding.GetChars(_bytes, 0, _byteCount, _chars, 0);
+                    int charCount = _encoding!.GetChars(_bytes, 0, _byteCount, _chars, 0);
                     _byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0);
                 }
 
@@ -209,7 +213,7 @@ namespace System.Runtime.Serialization.Json
                 {
                     count = _byteCount;
                 }
-                Buffer.BlockCopy(_bytes, _byteOffset, buffer, offset, count);
+                Buffer.BlockCopy(_bytes!, _byteOffset, buffer, offset, count);
                 _byteOffset += count;
                 _byteCount -= count;
                 return count;
@@ -253,11 +257,13 @@ namespace System.Runtime.Serialization.Json
                 return;
             }
 
+            Debug.Assert(_bytes != null);
+            Debug.Assert(_chars != null);
             while (count > 0)
             {
                 int size = _chars.Length < count ? _chars.Length : count;
-                int charCount = _dec.GetChars(buffer, offset, size, _chars, 0, false);
-                _byteCount = _enc.GetBytes(_chars, 0, charCount, _bytes, 0, false);
+                int charCount = _dec!.GetChars(buffer, offset, size, _chars, 0, false);
+                _byteCount = _enc!.GetBytes(_chars, 0, charCount, _bytes, 0, false);
                 _stream.Write(_bytes, 0, _byteCount);
                 offset += size;
                 count -= size;
@@ -293,7 +299,7 @@ namespace System.Runtime.Serialization.Json
                 _ => throw new XmlException(SR.JsonEncodingNotSupported),
             };
 
-        private static SupportedEncoding GetSupportedEncoding(Encoding encoding)
+        private static SupportedEncoding GetSupportedEncoding(Encoding? encoding)
         {
             if (encoding == null)
             {
@@ -346,6 +352,8 @@ namespace System.Runtime.Serialization.Json
 
         private void CleanupCharBreak()
         {
+            Debug.Assert(_bytes != null);
+
             int max = _byteOffset + _byteCount;
 
             // Read on 2 byte boundaries
@@ -385,6 +393,8 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
+        [MemberNotNull(nameof(_chars))]
+        [MemberNotNull(nameof(_bytes))]
         private void EnsureBuffers()
         {
             EnsureByteBuffer();
@@ -394,6 +404,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
+        [MemberNotNull(nameof(_bytes))]
         private void EnsureByteBuffer()
         {
             if (_bytes != null)
@@ -408,6 +419,8 @@ namespace System.Runtime.Serialization.Json
 
         private void FillBuffer(int count)
         {
+            Debug.Assert(_bytes != null);
+
             count -= _byteCount;
             while (count > 0)
             {
@@ -422,7 +435,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        private void InitForReading(Stream inputStream, Encoding expectedEncoding)
+        private void InitForReading(Stream inputStream, Encoding? expectedEncoding)
         {
             try
             {
index 916e22d..f169cf1 100644 (file)
@@ -10,12 +10,12 @@ namespace System.Runtime.Serialization.Json
         public JsonEnumDataContract(EnumDataContract traditionalDataContract)
             : base(new JsonEnumDataContractCriticalHelper(traditionalDataContract))
         {
-            _helper = base.Helper as JsonEnumDataContractCriticalHelper;
+            _helper = (base.Helper as JsonEnumDataContractCriticalHelper)!;
         }
 
         public bool IsULong => _helper.IsULong;
 
-        public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
+        public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context)
         {
             object enumValue;
             if (IsULong)
@@ -34,7 +34,7 @@ namespace System.Runtime.Serialization.Json
             return enumValue;
         }
 
-        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
+        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle)
         {
             if (IsULong)
             {
index f746185..85ba87d 100644 (file)
@@ -12,73 +12,73 @@ namespace System.Runtime.Serialization
 {
     public static class JsonFormatGeneratorStatics
     {
-        private static PropertyInfo s_collectionItemNameProperty;
+        private static PropertyInfo? s_collectionItemNameProperty;
 
-        private static ConstructorInfo s_extensionDataObjectCtor;
+        private static ConstructorInfo? s_extensionDataObjectCtor;
 
-        private static PropertyInfo s_extensionDataProperty;
+        private static PropertyInfo? s_extensionDataProperty;
 
-        private static MethodInfo s_getItemContractMethod;
+        private static MethodInfo? s_getItemContractMethod;
 
-        private static MethodInfo s_getJsonDataContractMethod;
+        private static MethodInfo? s_getJsonDataContractMethod;
 
-        private static MethodInfo s_getJsonMemberIndexMethod;
+        private static MethodInfo? s_getJsonMemberIndexMethod;
 
-        private static MethodInfo s_getRevisedItemContractMethod;
+        private static MethodInfo? s_getRevisedItemContractMethod;
 
-        private static MethodInfo s_getUninitializedObjectMethod;
+        private static MethodInfo? s_getUninitializedObjectMethod;
 
-        private static MethodInfo s_ienumeratorGetCurrentMethod;
+        private static MethodInfo? s_ienumeratorGetCurrentMethod;
 
-        private static MethodInfo s_ienumeratorMoveNextMethod;
+        private static MethodInfo? s_ienumeratorMoveNextMethod;
 
-        private static MethodInfo s_isStartElementMethod0;
+        private static MethodInfo? s_isStartElementMethod0;
 
-        private static MethodInfo s_isStartElementMethod2;
+        private static MethodInfo? s_isStartElementMethod2;
 
-        private static PropertyInfo s_localNameProperty;
+        private static PropertyInfo? s_localNameProperty;
 
-        private static PropertyInfo s_namespaceProperty;
+        private static PropertyInfo? s_namespaceProperty;
 
-        private static MethodInfo s_moveToContentMethod;
+        private static MethodInfo? s_moveToContentMethod;
 
-        private static PropertyInfo s_nodeTypeProperty;
+        private static PropertyInfo? s_nodeTypeProperty;
 
-        private static MethodInfo s_onDeserializationMethod;
+        private static MethodInfo? s_onDeserializationMethod;
 
-        private static MethodInfo s_readJsonValueMethod;
+        private static MethodInfo? s_readJsonValueMethod;
 
-        private static ConstructorInfo s_serializationExceptionCtor;
+        private static ConstructorInfo? s_serializationExceptionCtor;
 
-        private static Type[] s_serInfoCtorArgs;
+        private static Type[]? s_serInfoCtorArgs;
 
-        private static MethodInfo s_throwDuplicateMemberExceptionMethod;
+        private static MethodInfo? s_throwDuplicateMemberExceptionMethod;
 
-        private static MethodInfo s_throwMissingRequiredMembersMethod;
+        private static MethodInfo? s_throwMissingRequiredMembersMethod;
 
-        private static PropertyInfo s_typeHandleProperty;
+        private static PropertyInfo? s_typeHandleProperty;
 
-        private static PropertyInfo s_useSimpleDictionaryFormatReadProperty;
+        private static PropertyInfo? s_useSimpleDictionaryFormatReadProperty;
 
-        private static PropertyInfo s_useSimpleDictionaryFormatWriteProperty;
+        private static PropertyInfo? s_useSimpleDictionaryFormatWriteProperty;
 
-        private static MethodInfo s_writeAttributeStringMethod;
+        private static MethodInfo? s_writeAttributeStringMethod;
 
-        private static MethodInfo s_writeEndElementMethod;
+        private static MethodInfo? s_writeEndElementMethod;
 
-        private static MethodInfo s_writeJsonISerializableMethod;
+        private static MethodInfo? s_writeJsonISerializableMethod;
 
-        private static MethodInfo s_writeJsonNameWithMappingMethod;
+        private static MethodInfo? s_writeJsonNameWithMappingMethod;
 
-        private static MethodInfo s_writeJsonValueMethod;
+        private static MethodInfo? s_writeJsonValueMethod;
 
-        private static MethodInfo s_writeStartElementMethod;
+        private static MethodInfo? s_writeStartElementMethod;
 
-        private static MethodInfo s_writeStartElementStringMethod;
+        private static MethodInfo? s_writeStartElementStringMethod;
 
-        private static MethodInfo s_parseEnumMethod;
+        private static MethodInfo? s_parseEnumMethod;
 
-        private static MethodInfo s_getJsonMemberNameMethod;
+        private static MethodInfo? s_getJsonMemberNameMethod;
 
         public static PropertyInfo CollectionItemNameProperty
         {
@@ -96,10 +96,10 @@ namespace System.Runtime.Serialization
 
         public static ConstructorInfo ExtensionDataObjectCtor => s_extensionDataObjectCtor ??
                                                                  (s_extensionDataObjectCtor =
-                                                                     typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, null, Array.Empty<Type>(), null));
+                                                                     typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, null, Array.Empty<Type>(), null))!;
 
         public static PropertyInfo ExtensionDataProperty => s_extensionDataProperty ??
-                                                            (s_extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData"));
+                                                            (s_extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData")!);
 
         public static MethodInfo GetCurrentMethod
         {
@@ -107,7 +107,7 @@ namespace System.Runtime.Serialization
             {
                 if (s_ienumeratorGetCurrentMethod == null)
                 {
-                    s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current").GetGetMethod();
+                    s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current")!.GetGetMethod();
                     Debug.Assert(s_ienumeratorGetCurrentMethod != null);
                 }
                 return s_ienumeratorGetCurrentMethod;
@@ -119,7 +119,7 @@ namespace System.Runtime.Serialization
             {
                 if (s_getItemContractMethod == null)
                 {
-                    s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers).GetGetMethod(true); // nonPublic
+                    s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers)!.GetGetMethod(nonPublic: true);
                     Debug.Assert(s_getItemContractMethod != null);
                 }
                 return s_getItemContractMethod;
@@ -265,6 +265,7 @@ namespace System.Runtime.Serialization
                 if (s_onDeserializationMethod == null)
                 {
                     s_onDeserializationMethod = typeof(IDeserializationCallback).GetMethod("OnDeserialization");
+                    Debug.Assert(s_onDeserializationMethod != null);
                 }
                 return s_onDeserializationMethod;
             }
@@ -288,6 +289,7 @@ namespace System.Runtime.Serialization
                 if (s_serializationExceptionCtor == null)
                 {
                     s_serializationExceptionCtor = typeof(SerializationException).GetConstructor(new Type[] { typeof(string) });
+                    Debug.Assert(s_serializationExceptionCtor != null);
                 }
                 return s_serializationExceptionCtor;
             }
@@ -394,6 +396,7 @@ namespace System.Runtime.Serialization
                 if (s_writeJsonISerializableMethod == null)
                 {
                     s_writeJsonISerializableMethod = typeof(XmlObjectSerializerWriteContextComplexJson).GetMethod("WriteJsonISerializable", Globals.ScanAllMembers);
+                    Debug.Assert(s_writeJsonISerializableMethod != null);
                 }
                 return s_writeJsonISerializableMethod;
             }
@@ -455,6 +458,7 @@ namespace System.Runtime.Serialization
                 if (s_parseEnumMethod == null)
                 {
                     s_parseEnumMethod = typeof(Enum).GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(Type), typeof(string) });
+                    Debug.Assert(s_parseEnumMethod != null);
                 }
                 return s_parseEnumMethod;
             }
index 47d4b81..5f03267 100644 (file)
@@ -8,13 +8,14 @@ namespace System.Runtime.Serialization.Json
 {
     using System;
     using System.Collections.Generic;
+    using System.Diagnostics;
     using System.Reflection;
     using System.Reflection.Emit;
     using System.Runtime;
     using System.Security;
     using System.Xml;
 
-    internal delegate object JsonFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames);
+    internal delegate object JsonFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson? context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[]? memberNames);
     internal delegate object JsonFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract);
     internal delegate void JsonFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract);
 
@@ -44,14 +45,14 @@ namespace System.Runtime.Serialization.Json
 
         private class CriticalHelper
         {
-            private CodeGenerator _ilg;
-            private LocalBuilder _objectLocal;
-            private Type _objectType;
-            private ArgBuilder _xmlReaderArg;
-            private ArgBuilder _contextArg;
-            private ArgBuilder _memberNamesArg;
-            private ArgBuilder _collectionContractArg;
-            private ArgBuilder _emptyDictionaryStringArg;
+            private CodeGenerator _ilg = null!; // initialized in GenerateXXXReader
+            private LocalBuilder _objectLocal = null!; // initialized in CreateObject and ReadCollection
+            private Type? _objectType;
+            private ArgBuilder _xmlReaderArg = null!; // initialized in InitArgs
+            private ArgBuilder _contextArg = null!; // initialized in InitArgs
+            private ArgBuilder _memberNamesArg = null!; // initialized in InitArgs
+            private ArgBuilder? _collectionContractArg;
+            private ArgBuilder _emptyDictionaryStringArg = null!; // initialized in InitArgs
 
             public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract)
             {
@@ -59,7 +60,7 @@ namespace System.Runtime.Serialization.Json
                 bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null);
                 try
                 {
-                    BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(classContract.StableName.Name) + "FromJson", typeof(JsonFormatClassReaderDelegate), memberAccessFlag);
+                    BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(classContract.StableName!.Name) + "FromJson", typeof(JsonFormatClassReaderDelegate), memberAccessFlag);
                 }
                 catch (SecurityException securityException)
                 {
@@ -167,7 +168,7 @@ namespace System.Runtime.Serialization.Json
                 ilg.BeginMethod(methodName, delegateType, allowPrivateMemberAccess);
 #else
 
-                MethodInfo signature = delegateType.GetMethod("Invoke");
+                MethodInfo signature = delegateType.GetMethod("Invoke")!;
                 ParameterInfo[] parameters = signature.GetParameters();
                 Type[] paramTypes = new Type[parameters.Length];
                 for (int i = 0; i < parameters.Length; i++)
@@ -195,7 +196,7 @@ namespace System.Runtime.Serialization.Json
 
                 if (classContract.UnderlyingType == Globals.TypeOfDBNull)
                 {
-                    _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value"));
+                    _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value")!);
                     _ilg.Stloc(_objectLocal);
                 }
                 else if (classContract.IsNonAttributedType)
@@ -207,7 +208,7 @@ namespace System.Runtime.Serialization.Json
                     }
                     else
                     {
-                        _ilg.New(classContract.GetNonAttributedTypeConstructor());
+                        _ilg.New(classContract.GetNonAttributedTypeConstructor()!);
                         _ilg.Stloc(_objectLocal);
                     }
                 }
@@ -226,7 +227,7 @@ namespace System.Runtime.Serialization.Json
                 if (classContract.OnDeserializing != null)
                 {
                     _ilg.LoadAddress(_objectLocal);
-                    _ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
+                    _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!);
                     _ilg.Load(_contextArg);
                     _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
                     _ilg.Call(classContract.OnDeserializing);
@@ -240,7 +241,7 @@ namespace System.Runtime.Serialization.Json
                 if (classContract.OnDeserialized != null)
                 {
                     _ilg.LoadAddress(_objectLocal);
-                    _ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
+                    _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!);
                     _ilg.Load(_contextArg);
                     _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
                     _ilg.Call(classContract.OnDeserialized);
@@ -277,10 +278,10 @@ namespace System.Runtime.Serialization.Json
                     _ilg.Store(extensionDataLocal);
                     ReadMembers(classContract, extensionDataLocal);
 
-                    ClassDataContract currentContract = classContract;
+                    ClassDataContract? currentContract = classContract;
                     while (currentContract != null)
                     {
-                        MethodInfo extensionDataSetMethod = currentContract.ExtensionDataSetMethod;
+                        MethodInfo? extensionDataSetMethod = currentContract.ExtensionDataSetMethod;
                         if (extensionDataSetMethod != null)
                             _ilg.Call(_objectLocal, extensionDataSetMethod, extensionDataLocal);
                         currentContract = currentContract.BaseContract;
@@ -292,9 +293,9 @@ namespace System.Runtime.Serialization.Json
                 }
             }
 
-            private void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal)
+            private void ReadMembers(ClassDataContract classContract, LocalBuilder? extensionDataLocal)
             {
-                int memberCount = classContract.MemberNames.Length;
+                int memberCount = classContract.MemberNames!.Length;
                 _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount);
 
                 BitFlagsGenerator expectedElements = new BitFlagsGenerator(memberCount, _ilg, classContract.UnderlyingType.Name + "_ExpectedElements");
@@ -345,7 +346,7 @@ namespace System.Runtime.Serialization.Json
                 int memberCount = (classContract.BaseContract == null) ? 0 :
                     ReadMembers(classContract.BaseContract, expectedElements, memberLabels, throwDuplicateMemberLabel, memberIndexLocal);
 
-                for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
+                for (int i = 0; i < classContract.Members!.Count; i++, memberCount++)
                 {
                     DataMember dataMember = classContract.Members[i];
                     Type memberType = dataMember.MemberType;
@@ -353,7 +354,7 @@ namespace System.Runtime.Serialization.Json
                     _ilg.Set(memberIndexLocal, memberCount);
                     expectedElements.Load(memberCount);
                     _ilg.Brfalse(throwDuplicateMemberLabel);
-                    LocalBuilder value = null;
+                    LocalBuilder? value = null;
                     if (dataMember.IsGetOnlyCollection)
                     {
                         _ilg.LoadAddress(_objectLocal);
@@ -368,7 +369,7 @@ namespace System.Runtime.Serialization.Json
                         _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetCollectionMemberInfoMethod);
                         value = ReadValue(memberType, dataMember.Name);
                         _ilg.LoadAddress(_objectLocal);
-                        _ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
+                        _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!);
                         _ilg.Ldloc(value);
                         _ilg.StoreMember(dataMember.MemberInfo);
                     }
@@ -407,7 +408,7 @@ namespace System.Runtime.Serialization.Json
             {
                 int memberCount = (contract.BaseContract == null) ? 0 :
                     SetRequiredElements(contract.BaseContract, requiredElements);
-                List<DataMember> members = contract.Members;
+                List<DataMember> members = contract.Members!;
                 for (int i = 0; i < members.Count; i++, memberCount++)
                 {
                     if (members[i].IsRequired)
@@ -434,11 +435,11 @@ namespace System.Runtime.Serialization.Json
 
             private void ReadISerializable(ClassDataContract classContract)
             {
-                ConstructorInfo ctor = classContract.UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, JsonFormatGeneratorStatics.SerInfoCtorArgs, null);
+                ConstructorInfo? ctor = classContract.UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, JsonFormatGeneratorStatics.SerInfoCtorArgs, null);
                 if (ctor == null)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(classContract.UnderlyingType))));
                 _ilg.LoadAddress(_objectLocal);
-                _ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
+                _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!);
                 _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadSerializationInfoMethod, _xmlReaderArg, classContract.UnderlyingType);
                 _ilg.Load(_contextArg);
                 _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
@@ -448,7 +449,7 @@ namespace System.Runtime.Serialization.Json
             private LocalBuilder ReadValue(Type type, string name)
             {
                 LocalBuilder value = _ilg.DeclareLocal(type, "valueRead");
-                LocalBuilder nullableValue = null;
+                LocalBuilder? nullableValue = null;
                 int nullables = 0;
                 while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
                 {
@@ -456,7 +457,7 @@ namespace System.Runtime.Serialization.Json
                     type = type.GetGenericArguments()[0];
                 }
 
-                PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
+                PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
                 if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType)
                 {
                     LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead");
@@ -559,10 +560,10 @@ namespace System.Runtime.Serialization.Json
                 for (int i = 1; i < nullables; i++)
                 {
                     Type type = Globals.TypeOfNullable.MakeGenericType(innerType);
-                    _ilg.New(type.GetConstructor(new Type[] { innerType }));
+                    _ilg.New(type.GetConstructor(new Type[] { innerType })!);
                     innerType = type;
                 }
-                _ilg.Call(outerType.GetConstructor(new Type[] { innerType }));
+                _ilg.Call(outerType.GetConstructor(new Type[] { innerType })!);
             }
 
             private void ReadCollection(CollectionDataContract collectionContract)
@@ -570,18 +571,18 @@ namespace System.Runtime.Serialization.Json
                 Type type = collectionContract.UnderlyingType;
                 Type itemType = collectionContract.ItemType;
                 bool isArray = (collectionContract.Kind == CollectionKind.Array);
-                ConstructorInfo constructor = collectionContract.Constructor;
+                ConstructorInfo constructor = collectionContract.Constructor!;
                 if (type.IsInterface)
                 {
                     switch (collectionContract.Kind)
                     {
                         case CollectionKind.GenericDictionary:
                             type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments());
-                            constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
+                            constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>())!;
                             break;
                         case CollectionKind.Dictionary:
                             type = Globals.TypeOfHashtable;
-                            constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
+                            constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>())!;
                             break;
                         case CollectionKind.Collection:
                         case CollectionKind.GenericCollection:
@@ -635,7 +636,7 @@ namespace System.Runtime.Serialization.Json
                     _ilg.IfNot();
                 }
 
-                LocalBuilder growingCollection = null;
+                LocalBuilder? growingCollection = null;
                 if (isArray)
                 {
                     growingCollection = _ilg.DeclareLocal(type, "growingCollection");
@@ -651,6 +652,7 @@ namespace System.Runtime.Serialization.Json
                 LocalBuilder value = ReadCollectionItem(collectionContract, itemType);
                 if (isArray)
                 {
+                    Debug.Assert(growingCollection != null);
                     MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType);
                     _ilg.Call(null, ensureArraySizeMethod, growingCollection, i);
                     _ilg.Stloc(growingCollection);
@@ -704,7 +706,7 @@ namespace System.Runtime.Serialization.Json
                 }
 
                 ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract;
-                DataContract keyDataContract = keyValueDataContract.Members[0].MemberTypeContract;
+                DataContract keyDataContract = keyValueDataContract.Members![0].MemberTypeContract;
 
                 KeyParseMode keyParseMode = KeyParseMode.Fail;
 
@@ -763,7 +765,7 @@ namespace System.Runtime.Serialization.Json
                     }
                     else if (keyParseMode == KeyParseMode.UsingCustomParse)
                     {
-                        _ilg.Call(keyDataContract.ParseMethod);
+                        _ilg.Call(keyDataContract.ParseMethod!);
                     }
                     LocalBuilder pairKey = _ilg.DeclareLocal(keyType, "key");
                     _ilg.Stloc(pairKey);
@@ -871,11 +873,11 @@ namespace System.Runtime.Serialization.Json
 
             private bool TryReadPrimitiveArray(Type itemType)
             {
-                PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
+                PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
                 if (primitiveContract == null)
                     return false;
 
-                string readArrayMethod = null;
+                string? readArrayMethod = null;
                 switch (itemType.GetTypeCode())
                 {
                     case TypeCode.Boolean:
@@ -913,7 +915,7 @@ namespace System.Runtime.Serialization.Json
                     // -1 Array Size
                     _ilg.Load(-1);
                     _ilg.Ldloca(_objectLocal);
-                    _ilg.Call(typeof(JsonReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers));
+                    _ilg.Call(typeof(JsonReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers)!);
                     return true;
                 }
                 return false;
@@ -945,12 +947,12 @@ namespace System.Runtime.Serialization.Json
             {
                 if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary)
                 {
-                    ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract;
+                    ClassDataContract? keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract;
                     if (keyValuePairContract == null)
                     {
                         Fx.Assert("Failed to create contract for KeyValuePair type");
                     }
-                    DataMember keyMember = keyValuePairContract.Members[0];
+                    DataMember keyMember = keyValuePairContract.Members![0];
                     DataMember valueMember = keyValuePairContract.Members[1];
                     LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name);
                     LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name);
@@ -965,6 +967,8 @@ namespace System.Runtime.Serialization.Json
                 }
                 else
                 {
+                    Debug.Assert(collectionContract.AddMethod != null);
+
                     _ilg.Call(collection, collectionContract.AddMethod, value);
                     if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid)
                         _ilg.Pop();
@@ -973,6 +977,8 @@ namespace System.Runtime.Serialization.Json
 
             private void StoreKeyValuePair(LocalBuilder collection, CollectionDataContract collectionContract, LocalBuilder pairKey, LocalBuilder pairValue)
             {
+                Debug.Assert(collectionContract.AddMethod != null);
+
                 _ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue);
                 if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid)
                     _ilg.Pop();
index da53366..606d464 100644 (file)
@@ -8,12 +8,13 @@ namespace System.Runtime.Serialization.Json
 {
     using System;
     using System.Collections;
+    using System.Diagnostics;
     using System.Reflection;
     using System.Reflection.Emit;
     using System.Security;
     using System.Xml;
 
-    internal delegate void JsonFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[] memberNames);
+    internal delegate void JsonFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[]? memberNames);
     internal delegate void JsonFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract);
 
     internal class JsonFormatWriterGenerator
@@ -37,14 +38,14 @@ namespace System.Runtime.Serialization.Json
 
         private class CriticalHelper
         {
-            private CodeGenerator _ilg;
-            private ArgBuilder _xmlWriterArg;
-            private ArgBuilder _contextArg;
-            private ArgBuilder _dataContractArg;
-            private LocalBuilder _objectLocal;
+            private CodeGenerator _ilg = null!; // initialized in GenerateXXXWriter
+            private ArgBuilder _xmlWriterArg = null!; // initialized in InitArgs
+            private ArgBuilder _contextArg = null!; // initialized in InitArgs
+            private ArgBuilder _dataContractArg = null!; // initialized in InitArgs
+            private LocalBuilder _objectLocal = null!; // initialized in InitArgs
 
             // Used for classes
-            private ArgBuilder _memberNamesArg;
+            private ArgBuilder? _memberNamesArg;
             private int _typeIndex = 1;
             private int _childElementIndex;
 
@@ -102,7 +103,7 @@ namespace System.Runtime.Serialization.Json
 #if USE_REFEMIT
                 ilg.BeginMethod(methodName, delegateType, allowPrivateMemberAccess);
 #else
-                MethodInfo signature = delegateType.GetMethod("Invoke");
+                MethodInfo signature = delegateType.GetMethod("Invoke")!;
                 ParameterInfo[] parameters = signature.GetParameters();
                 Type[] paramTypes = new Type[parameters.Length];
                 for (int i = 0; i < parameters.Length; i++)
@@ -136,8 +137,8 @@ namespace System.Runtime.Serialization.Json
                 else if (objType.IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter)
                 {
                     ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType);
-                    _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments));
-                    _ilg.New(dc.KeyValuePairAdapterConstructorInfo);
+                    _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments!));
+                    _ilg.New(dc.KeyValuePairAdapterConstructorInfo!);
                 }
                 else
                 {
@@ -200,19 +201,19 @@ namespace System.Runtime.Serialization.Json
                 InvokeOnSerialized(classContract);
             }
 
-            private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract)
+            private int WriteMembers(ClassDataContract classContract, LocalBuilder? extensionDataLocal, ClassDataContract derivedMostClassContract)
             {
                 int memberCount = (classContract.BaseContract == null) ? 0 :
                     WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract);
 
-                int classMemberCount = classContract.Members.Count;
+                int classMemberCount = classContract.Members!.Count;
                 _ilg.Call(thisObj: _contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classMemberCount);
 
                 for (int i = 0; i < classMemberCount; i++, memberCount++)
                 {
                     DataMember member = classContract.Members[i];
                     Type memberType = member.MemberType;
-                    LocalBuilder memberValue = null;
+                    LocalBuilder? memberValue = null;
 
                     _ilg.Load(_contextArg);
                     _ilg.Call(methodInfo: member.IsGetOnlyCollection ?
@@ -225,7 +226,7 @@ namespace System.Runtime.Serialization.Json
                         _ilg.IfNotDefaultValue(memberValue);
                     }
 
-                    bool requiresNameAttribute = DataContractJsonSerializerImpl.CheckIfXmlNameRequiresMapping(classContract.MemberNames[i]);
+                    bool requiresNameAttribute = DataContractJsonSerializerImpl.CheckIfXmlNameRequiresMapping(classContract.MemberNames![i]);
                     if (requiresNameAttribute || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, arrayItemIndex: null, name: null, nameIndex: i + _childElementIndex))
                     {
                         // Note: DataContractSerializer has member-conflict logic here to deal with the schema export
@@ -306,7 +307,9 @@ namespace System.Runtime.Serialization.Json
                 }
                 else
                 {
-                    MethodInfo incrementCollectionCountMethod = null;
+                    Debug.Assert(collectionContract.GetEnumeratorMethod != null);
+
+                    MethodInfo? incrementCollectionCountMethod = null;
                     switch (collectionContract.Kind)
                     {
                         case CollectionKind.Collection:
@@ -328,8 +331,8 @@ namespace System.Runtime.Serialization.Json
                     }
 
                     bool isDictionary = false, isGenericDictionary = false;
-                    Type enumeratorType = null;
-                    Type[] keyValueTypes = null;
+                    Type? enumeratorType = null;
+                    Type[]? keyValueTypes = null;
                     if (collectionContract.Kind == CollectionKind.GenericDictionary)
                     {
                         isGenericDictionary = true;
@@ -346,8 +349,8 @@ namespace System.Runtime.Serialization.Json
                     {
                         enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
                     }
-                    MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
-                    MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
+                    MethodInfo? moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
+                    MethodInfo? getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
                     if (moveNextMethod == null || getCurrentMethod == null)
                     {
                         if (enumeratorType.IsInterface)
@@ -376,9 +379,9 @@ namespace System.Runtime.Serialization.Json
                                 }
                             }
                             if (moveNextMethod == null)
-                                moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
+                                moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!;
                             if (getCurrentMethod == null)
-                                getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
+                                getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!;
                         }
                     }
                     Type elementType = getCurrentMethod.ReturnType;
@@ -388,14 +391,15 @@ namespace System.Runtime.Serialization.Json
                     _ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod);
                     if (isDictionary)
                     {
-                        ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator });
+                        ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator })!;
                         _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, Globals.TypeOfIDictionaryEnumerator);
                         _ilg.New(dictEnumCtor);
                     }
                     else if (isGenericDictionary)
                     {
+                        Debug.Assert(keyValueTypes != null);
                         Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
-                        ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam });
+                        ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam })!;
                         _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam);
                         _ilg.New(dictEnumCtor);
                     }
@@ -404,9 +408,10 @@ namespace System.Runtime.Serialization.Json
                     bool canWriteSimpleDictionary = isDictionary || isGenericDictionary;
                     if (canWriteSimpleDictionary)
                     {
+                        Debug.Assert(keyValueTypes != null);
                         Type genericDictionaryKeyValueType = Globals.TypeOfKeyValue.MakeGenericType(keyValueTypes);
-                        PropertyInfo genericDictionaryKeyProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.KeyString);
-                        PropertyInfo genericDictionaryValueProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.ValueString);
+                        PropertyInfo genericDictionaryKeyProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.KeyString)!;
+                        PropertyInfo genericDictionaryValueProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.ValueString)!;
 
                         _ilg.Load(_contextArg);
                         _ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatWriteProperty);
@@ -472,9 +477,9 @@ namespace System.Runtime.Serialization.Json
                 }
             }
 
-            private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder name, int nameIndex)
+            private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? memberInfo, LocalBuilder? arrayItemIndex, LocalBuilder? name, int nameIndex)
             {
-                PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
+                PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
                 if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
                     return false;
 
@@ -509,7 +514,7 @@ namespace System.Runtime.Serialization.Json
                 }
                 else
                 {
-                    _ilg.LoadArrayElement(_memberNamesArg, nameIndex);
+                    _ilg.LoadArrayElement(_memberNamesArg!, nameIndex);
                 }
                 // load namespace
                 _ilg.Load(null);
@@ -520,11 +525,11 @@ namespace System.Runtime.Serialization.Json
 
             private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName)
             {
-                PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
+                PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
                 if (primitiveContract == null)
                     return false;
 
-                string writeArrayMethod = null;
+                string? writeArrayMethod = null;
                 switch (itemType.GetTypeCode())
                 {
                     case TypeCode.Boolean:
@@ -558,7 +563,7 @@ namespace System.Runtime.Serialization.Json
                     MethodInfo writeArrayMethodInfo = typeof(JsonWriterDelegator).GetMethod(
                         writeArrayMethod,
                         Globals.ScanAllMembers,
-                        new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
+                        new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })!;
                     _ilg.Call(_xmlWriterArg, writeArrayMethodInfo, value, itemName, null);
                     return true;
                 }
@@ -590,7 +595,7 @@ namespace System.Runtime.Serialization.Json
                                       memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);
                 if (memberType.IsValueType && !isNullableOfT)
                 {
-                    PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
+                    PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
                     if (primitiveContract != null)
                         _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue);
                     else
@@ -612,7 +617,7 @@ namespace System.Runtime.Serialization.Json
                     _ilg.If();
                     _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType));
                     _ilg.Else();
-                    PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
+                    PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
                     if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject)
                     {
                         if (isNullableOfT)
@@ -661,7 +666,7 @@ namespace System.Runtime.Serialization.Json
                 _ilg.Stloc(typeHandleValue);
                 _ilg.LoadAddress(typeHandleValue);
                 _ilg.Ldtoken(memberType);
-                _ilg.Call(typeof(RuntimeTypeHandle).GetMethod("Equals", new Type[] { typeof(RuntimeTypeHandle) }));
+                _ilg.Call(typeof(RuntimeTypeHandle).GetMethod("Equals", new Type[] { typeof(RuntimeTypeHandle) })!);
                 _ilg.Load(writeXsiType);
                 _ilg.Load(DataContract.GetId(memberType.TypeHandle));
                 _ilg.Ldtoken(memberType);
@@ -678,9 +683,9 @@ namespace System.Runtime.Serialization.Json
                 {
                     Type innerType = memberType.GetGenericArguments()[0];
                     _ilg.Dup();
-                    _ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_HasValue"));
+                    _ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_HasValue")!);
                     _ilg.Brfalse(onNull);
-                    _ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_Value"));
+                    _ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_Value")!);
                     memberType = innerType;
                 }
                 memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue");
@@ -696,13 +701,13 @@ namespace System.Runtime.Serialization.Json
                 return memberValue;
             }
 
-            private void WriteStartElement(LocalBuilder nameLocal, int nameIndex)
+            private void WriteStartElement(LocalBuilder? nameLocal, int nameIndex)
             {
                 _ilg.Load(_xmlWriterArg);
 
                 // localName
                 if (nameLocal == null)
-                    _ilg.LoadArrayElement(_memberNamesArg, nameIndex);
+                    _ilg.LoadArrayElement(_memberNamesArg!, nameIndex);
                 else
                     _ilg.Load(nameLocal);
 
index 544dd2a..601ddc1 100644 (file)
@@ -14,10 +14,10 @@ namespace System.Runtime.Serialization.Json
         {
         }
 
-        public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
+        public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context)
         {
-            object obj;
-            string contentMode = jsonReader.GetAttribute(JsonGlobals.typeString);
+            object? obj;
+            string? contentMode = jsonReader.GetAttribute(JsonGlobals.typeString);
 
             switch (contentMode)
             {
@@ -53,7 +53,7 @@ namespace System.Runtime.Serialization.Json
             return obj;
         }
 
-        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
+        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle)
         {
             jsonWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString);
         }
index b3992d0..7a9f805 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Runtime.Serialization.Json
         {
         }
 
-        public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
+        public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context)
         {
             if (context == null)
             {
index f567fe8..d1ae4d9 100644 (file)
@@ -4,26 +4,27 @@
 using System.Xml;
 using System.Runtime.Serialization;
 using System.Globalization;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization.Json
 {
     internal class JsonReaderDelegator : XmlReaderDelegator
     {
-        private readonly DateTimeFormat _dateTimeFormat;
-        private DateTimeArrayJsonHelperWithString _dateTimeArrayHelper;
+        private readonly DateTimeFormat? _dateTimeFormat;
+        private DateTimeArrayJsonHelperWithString? _dateTimeArrayHelper;
 
         public JsonReaderDelegator(XmlReader reader)
             : base(reader)
         {
         }
 
-        public JsonReaderDelegator(XmlReader reader, DateTimeFormat dateTimeFormat)
+        public JsonReaderDelegator(XmlReader reader, DateTimeFormat? dateTimeFormat)
             : this(reader)
         {
             _dateTimeFormat = dateTimeFormat;
         }
 
-        internal XmlDictionaryReaderQuotas ReaderQuotas
+        internal XmlDictionaryReaderQuotas? ReaderQuotas
         {
             get
             {
@@ -139,7 +140,7 @@ namespace System.Runtime.Serialization.Json
             return ParseJsonDate(ReadContentAsString(), _dateTimeFormat);
         }
 
-        internal static DateTime ParseJsonDate(string originalDateTimeValue, DateTimeFormat dateTimeFormat)
+        internal static DateTime ParseJsonDate(string originalDateTimeValue, DateTimeFormat? dateTimeFormat)
         {
             if (dateTimeFormat == null)
             {
@@ -241,14 +242,14 @@ namespace System.Runtime.Serialization.Json
         internal override bool TryReadDateTimeArray(XmlObjectSerializerReadContext context,
 #endif
         XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
-            int arrayLength, out DateTime[] array)
+            int arrayLength, [NotNullWhen(true)] out DateTime[]? array)
         {
             return TryReadJsonDateTimeArray(context, itemName, itemNamespace, arrayLength, out array);
         }
 
         internal bool TryReadJsonDateTimeArray(XmlObjectSerializerReadContext context,
             XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
-            int arrayLength, out DateTime[] array)
+            int arrayLength, [NotNullWhen(true)] out DateTime[]? array)
         {
             if ((dictionaryReader == null) || (arrayLength != -1))
             {
@@ -264,9 +265,9 @@ namespace System.Runtime.Serialization.Json
 
         private class DateTimeArrayJsonHelperWithString : ArrayHelper<string, DateTime>
         {
-            private readonly DateTimeFormat _dateTimeFormat;
+            private readonly DateTimeFormat? _dateTimeFormat;
 
-            public DateTimeArrayJsonHelperWithString(DateTimeFormat dateTimeFormat)
+            public DateTimeArrayJsonHelperWithString(DateTimeFormat? dateTimeFormat)
             {
                 _dateTimeFormat = dateTimeFormat;
             }
index fd1a83b..888c613 100644 (file)
@@ -30,7 +30,7 @@ namespace System.Runtime.Serialization.Json
             return CreateJsonReader(buffer, 0, buffer.Length, null, quotas, null);
         }
 
-        public static XmlDictionaryReader CreateJsonReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
+        public static XmlDictionaryReader CreateJsonReader(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose)
         {
             XmlJsonReader reader = new XmlJsonReader();
             reader.SetInput(stream, encoding, quotas, onClose);
@@ -42,7 +42,7 @@ namespace System.Runtime.Serialization.Json
             return CreateJsonReader(buffer, offset, count, null, quotas, null);
         }
 
-        public static XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
+        public static XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose)
         {
             XmlJsonReader reader = new XmlJsonReader();
             reader.SetInput(buffer, offset, count, encoding, quotas, onClose);
@@ -69,7 +69,7 @@ namespace System.Runtime.Serialization.Json
             return CreateJsonWriter(stream, encoding, ownsStream, indent, JsonReaderWriterFactory.DefaultIndentChars);
         }
 
-        public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent, string indentChars)
+        public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent, string? indentChars)
         {
             XmlJsonWriter writer = new XmlJsonWriter(indent, indentChars);
             writer.SetOutput(stream, encoding, ownsStream);
index 5e4236c..e9e1d3c 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Runtime.Serialization.Json
         {
         }
 
-        public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
+        public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context)
         {
             if (context == null)
             {
index ef9f909..5e56059 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Runtime.Serialization.Json
         {
         }
 
-        public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
+        public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context)
         {
             if (context == null)
             {
index 834e58b..0ed5f9f 100644 (file)
@@ -8,14 +8,14 @@ namespace System.Runtime.Serialization.Json
 {
     internal class JsonWriterDelegator : XmlWriterDelegator
     {
-        private readonly DateTimeFormat _dateTimeFormat;
+        private readonly DateTimeFormat? _dateTimeFormat;
 
         public JsonWriterDelegator(XmlWriter writer)
             : base(writer)
         {
         }
 
-        public JsonWriterDelegator(XmlWriter writer, DateTimeFormat dateTimeFormat)
+        public JsonWriterDelegator(XmlWriter writer, DateTimeFormat? dateTimeFormat)
             : this(writer)
         {
             _dateTimeFormat = dateTimeFormat;
@@ -26,7 +26,7 @@ namespace System.Runtime.Serialization.Json
             WriteString(XmlConvert.ToString(value));
         }
 
-        internal override void WriteBase64(byte[] bytes)
+        internal override void WriteBase64(byte[]? bytes)
         {
             if (bytes == null)
             {
@@ -118,7 +118,7 @@ namespace System.Runtime.Serialization.Json
         }
 
 
-        internal void WriteJsonBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
+        internal void WriteJsonBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace)
         {
             for (int i = 0; i < value.Length; i++)
             {
@@ -126,7 +126,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal void WriteJsonDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
+        internal void WriteJsonDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace)
         {
             for (int i = 0; i < value.Length; i++)
             {
@@ -134,7 +134,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal void WriteJsonDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
+        internal void WriteJsonDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace)
         {
             for (int i = 0; i < value.Length; i++)
             {
@@ -142,7 +142,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal void WriteJsonInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
+        internal void WriteJsonInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace)
         {
             for (int i = 0; i < value.Length; i++)
             {
@@ -150,7 +150,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal void WriteJsonInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
+        internal void WriteJsonInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace)
         {
             for (int i = 0; i < value.Length; i++)
             {
@@ -217,7 +217,7 @@ namespace System.Runtime.Serialization.Json
             writer.WriteString(JsonGlobals.DateTimeEndGuardReader);
         }
 
-        internal void WriteJsonSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
+        internal void WriteJsonSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace)
         {
             for (int i = 0; i < value.Length; i++)
             {
@@ -225,7 +225,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal void WriteJsonDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
+        internal void WriteJsonDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace)
         {
             for (int i = 0; i < value.Length; i++)
             {
@@ -233,7 +233,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal override void WriteStartElement(string prefix, string localName, string ns)
+        internal override void WriteStartElement(string? prefix, string localName, string? ns)
         {
             if (localName != null && localName.Length == 0)
             {
@@ -242,7 +242,7 @@ namespace System.Runtime.Serialization.Json
             }
             else
             {
-                base.WriteStartElement(prefix, localName, ns);
+                base.WriteStartElement(prefix, localName!, ns);
             }
         }
     }
index dffbb13..0dea02f 100644 (file)
@@ -15,7 +15,7 @@ namespace System.Runtime.Serialization.Json
         {
         }
 
-        public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
+        public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context)
         {
             string xmlContent = jsonReader.ReadElementContentAsString();
 
@@ -23,8 +23,8 @@ namespace System.Runtime.Serialization.Json
                 GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false); //  maxItemsInObjectGraph //  ignoreExtensionDataObject //  preserveObjectReferences
 
             MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlContent));
-            object xmlValue;
-            XmlDictionaryReaderQuotas quotas = ((JsonReaderDelegator)jsonReader).ReaderQuotas;
+            object? xmlValue;
+            XmlDictionaryReaderQuotas? quotas = ((JsonReaderDelegator)jsonReader).ReaderQuotas;
             if (quotas == null)
             {
                 xmlValue = dataContractSerializer.ReadObject(memoryStream);
@@ -40,7 +40,7 @@ namespace System.Runtime.Serialization.Json
             return xmlValue;
         }
 
-        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle)
+        public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle)
         {
             DataContractSerializer dataContractSerializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle),
                 GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false); //  maxItemsInObjectGraph //  ignoreExtensionDataObject //  preserveObjectReferences
@@ -52,7 +52,7 @@ namespace System.Runtime.Serialization.Json
             jsonWriter.WriteString(serialized);
         }
 
-        private List<Type> GetKnownTypesFromContext(XmlObjectSerializerContext context, IList<Type> serializerKnownTypeList)
+        private List<Type> GetKnownTypesFromContext(XmlObjectSerializerContext? context, IList<Type>? serializerKnownTypeList)
         {
             List<Type> knownTypesList = new List<Type>();
             if (context != null)
index d97393f..dae0e1b 100644 (file)
@@ -25,7 +25,7 @@ namespace System.Runtime.Serialization.Json
             _reflectionReader = new ReflectionJsonReader();
         }
 
-        public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames)
+        public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson? context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[]? memberNames)
         {
             Debug.Assert(_classContract != null);
             return _reflectionReader.ReflectionReadClass(xmlReader, context, memberNames, null /*memberNamespaces*/, _classContract);
@@ -49,12 +49,12 @@ namespace System.Runtime.Serialization.Json
 
     internal sealed class ReflectionJsonReader : ReflectionReader
     {
-        protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, ClassDataContract classContract, ref object obj)
+        protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract, ref object obj)
         {
             var jsonContext = context as XmlObjectSerializerReadContextComplexJson;
             Debug.Assert(jsonContext != null);
 
-            int memberCount = classContract.MemberNames.Length;
+            int memberCount = classContract.MemberNames!.Length;
             context.IncrementItemCount(memberCount);
 
             DataMember[] members = new DataMember[memberCount];
@@ -62,7 +62,7 @@ namespace System.Runtime.Serialization.Json
 
             int memberIndex = -1;
 
-            ExtensionDataObject extensionData = null;
+            ExtensionDataObject? extensionData = null;
 
             if (classContract.HasExtensionData)
             {
@@ -102,7 +102,7 @@ namespace System.Runtime.Serialization.Json
             return string.Empty;
         }
 
-        protected override object ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract)
+        protected override object? ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract)
         {
             var jsonContext = context as XmlObjectSerializerReadContextComplexJson;
             Debug.Assert(jsonContext != null);
@@ -113,7 +113,7 @@ namespace System.Runtime.Serialization.Json
             return DataContractJsonSerializer.ReadJsonValue(itemContract, xmlReader, jsonContext);
         }
 
-        protected override bool ReflectionReadSpecialCollection(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, object resultCollection)
+        protected override bool ReflectionReadSpecialCollection(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, object? resultCollection)
         {
             var jsonContext = context as XmlObjectSerializerReadContextComplexJson;
             Debug.Assert(jsonContext != null);
@@ -128,7 +128,7 @@ namespace System.Runtime.Serialization.Json
             return false;
         }
 
-        private void ReadSimpleDictionary(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type keyValueType, object dictionary)
+        private void ReadSimpleDictionary(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type keyValueType, object? dictionary)
         {
             Type[] keyValueTypes = keyValueType.GetGenericArguments();
             Type keyType = keyValueTypes[0];
@@ -142,7 +142,7 @@ namespace System.Runtime.Serialization.Json
             }
 
             ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract;
-            DataContract keyDataContract = keyValueDataContract.Members[0].MemberTypeContract;
+            DataContract keyDataContract = keyValueDataContract.Members![0].MemberTypeContract;
 
             KeyParseMode keyParseMode = KeyParseMode.Fail;
 
@@ -207,7 +207,7 @@ namespace System.Runtime.Serialization.Json
                         TypeCode.UInt16 => ushort.Parse(keyString),
                         TypeCode.UInt32 => uint.Parse(keyString),
                         TypeCode.UInt64 => ulong.Parse(keyString),
-                        _ => keyDataContract.ParseMethod.Invoke(null, new object[] { keyString }),
+                        _ => keyDataContract.ParseMethod!.Invoke(null, new object[] { keyString })!,
                     };
                 }
                 else
@@ -220,9 +220,9 @@ namespace System.Runtime.Serialization.Json
                     throw new NotImplementedException(SR.Format(SR.MustBeGreaterThanZero, keyTypeNullableDepth));
                 }
 
-                object pairValue = ReflectionReadValue(xmlReader, context, valueType, string.Empty, string.Empty);
-
+                object? pairValue = ReflectionReadValue(xmlReader, context, valueType, string.Empty, string.Empty);
 
+                Debug.Assert(dictionary != null);
                 ((IDictionary)dictionary).Add(pairKey, pairValue);
             }
         }
index 23ec559..3fd8d58 100644 (file)
@@ -4,6 +4,7 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Linq;
 using System.Reflection;
 using System.Text;
@@ -16,14 +17,14 @@ namespace System.Runtime.Serialization.Json
     {
         private readonly ReflectionJsonClassWriter _reflectionClassWriter = new ReflectionJsonClassWriter();
 
-        public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract classContract, XmlDictionaryString[] memberNames)
+        public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract classContract, XmlDictionaryString[]? memberNames)
         {
             _reflectionClassWriter.ReflectionWriteClass(xmlWriter, obj, context, classContract, memberNames);
         }
 
         public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract collectionContract)
         {
-            JsonWriterDelegator jsonWriter = xmlWriter as JsonWriterDelegator;
+            JsonWriterDelegator? jsonWriter = xmlWriter as JsonWriterDelegator;
             if (jsonWriter == null)
             {
                 throw new ArgumentException(nameof(xmlWriter));
@@ -40,7 +41,7 @@ namespace System.Runtime.Serialization.Json
                     ReflectionWriteArrayAttribute(jsonWriter);
 
                     Array array = (Array)obj;
-                    PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
+                    PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
                     for (int i = 0; i < array.Length; ++i)
                     {
                         _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, itemName);
@@ -64,14 +65,14 @@ namespace System.Runtime.Serialization.Json
                 {
                     ReflectionWriteObjectAttribute(jsonWriter);
                     Type[] itemTypeGenericArguments = collectionContract.ItemType.GetGenericArguments();
-                    Type dictionaryValueType = itemTypeGenericArguments.Length == 2 ? itemTypeGenericArguments[1] : null;
+                    Type? dictionaryValueType = itemTypeGenericArguments.Length == 2 ? itemTypeGenericArguments[1] : null;
 
                     while (enumerator.MoveNext())
                     {
                         object current = enumerator.Current;
-                        object key = ((IKeyValue)current).Key;
-                        object value = ((IKeyValue)current).Value;
-                        _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, key.ToString());
+                        object key = ((IKeyValue)current).Key!;
+                        object value = ((IKeyValue)current).Value!;
+                        _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, key.ToString()!);
                         _reflectionClassWriter.ReflectionWriteValue(jsonWriter, context, dictionaryValueType ?? value.GetType(), value, false, primitiveContractForParamType: null);
                         _reflectionClassWriter.ReflectionWriteEndElement(jsonWriter);
                     }
@@ -80,7 +81,7 @@ namespace System.Runtime.Serialization.Json
                 {
                     ReflectionWriteArrayAttribute(jsonWriter);
 
-                    PrimitiveDataContract primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(collectionContract.UnderlyingType);
+                    PrimitiveDataContract? primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(collectionContract.UnderlyingType);
                     if (primitiveContractForType != null && primitiveContractForType.UnderlyingType != Globals.TypeOfObject)
                     {
                         while (enumerator.MoveNext())
@@ -95,8 +96,8 @@ namespace System.Runtime.Serialization.Json
                         Type elementType = collectionContract.GetCollectionElementType();
                         bool isDictionary = collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary;
 
-                        DataContract itemContract = null;
-                        JsonDataContract jsonDataContract = null;
+                        DataContract? itemContract = null;
+                        JsonDataContract? jsonDataContract = null;
                         if (isDictionary)
                         {
                             itemContract = XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(collectionContract.ItemContract);
@@ -110,7 +111,7 @@ namespace System.Runtime.Serialization.Json
                             _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, itemName);
                             if (isDictionary)
                             {
-                                jsonDataContract.WriteJsonValue(jsonWriter, current, context, collectionContract.ItemType.TypeHandle);
+                                jsonDataContract!.WriteJsonValue(jsonWriter, current, context, collectionContract.ItemType.TypeHandle);
                             }
                             else
                             {
@@ -135,11 +136,11 @@ namespace System.Runtime.Serialization.Json
 
         private bool ReflectionTryWritePrimitiveArray(JsonWriterDelegator jsonWriter, object obj, Type underlyingType, Type itemType, XmlDictionaryString collectionItemName)
         {
-            PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
+            PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
             if (primitiveContract == null)
                 return false;
 
-            XmlDictionaryString itemNamespace = null;
+            XmlDictionaryString? itemNamespace = null;
 
             switch (itemType.GetTypeCode())
             {
@@ -189,14 +190,16 @@ namespace System.Runtime.Serialization.Json
 
     internal class ReflectionJsonClassWriter : ReflectionClassWriter
     {
-        protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[] memberNames)
+        protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[]? memberNames)
         {
+            Debug.Assert(memberNames != null);
+
             int memberCount = (classContract.BaseContract == null) ? 0 :
                 ReflectionWriteMembers(xmlWriter, obj, context, classContract.BaseContract, derivedMostClassContract, childElementIndex, memberNames);
 
             childElementIndex += memberCount;
 
-            context.IncrementItemCount(classContract.Members.Count);
+            context.IncrementItemCount(classContract.Members!.Count);
             for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
             {
                 DataMember member = classContract.Members[i];
@@ -212,11 +215,11 @@ namespace System.Runtime.Serialization.Json
 
 
                 bool shouldWriteValue = true;
-                object memberValue = null;
+                object? memberValue = null;
                 if (!member.EmitDefaultValue)
                 {
                     memberValue = ReflectionGetMemberValue(obj, member);
-                    object defaultValue = XmlFormatGeneratorStatics.GetDefaultValue(memberType);
+                    object? defaultValue = XmlFormatGeneratorStatics.GetDefaultValue(memberType);
                     if ((memberValue == null && defaultValue == null)
                         || (memberValue != null && memberValue.Equals(defaultValue)))
                     {
@@ -235,8 +238,8 @@ namespace System.Runtime.Serialization.Json
                     {
                         memberValue = ReflectionGetMemberValue(obj, member);
                     }
-                    bool requiresNameAttribute = DataContractJsonSerializerImpl.CheckIfXmlNameRequiresMapping(classContract.MemberNames[i]);
-                    PrimitiveDataContract primitiveContract = member.MemberPrimitiveContract;
+                    bool requiresNameAttribute = DataContractJsonSerializerImpl.CheckIfXmlNameRequiresMapping(classContract.MemberNames![i]);
+                    PrimitiveDataContract? primitiveContract = member.MemberPrimitiveContract;
                     if (requiresNameAttribute || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, null/*ns*/, primitiveContract))
                     {
                         // Note: DataContractSerializer has member-conflict logic here to deal with the schema export
index 4b23e31..b755f9b 100644 (file)
@@ -7,6 +7,8 @@ using System.Text;
 using System.Runtime.Serialization;
 using System.Collections.Generic;
 using System.Xml;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics;
 
 namespace System.Runtime.Serialization.Json
 {
@@ -274,14 +276,14 @@ namespace System.Runtime.Serialization.Json
                 CharType.None | CharType.FirstName | CharType.Name, //  FF (?)
             };
         private bool _buffered;
-        private byte[] _charactersToSkipOnNextRead;
+        private byte[]? _charactersToSkipOnNextRead;
         private JsonComplexTextMode _complexTextMode = JsonComplexTextMode.None;
         private bool _expectingFirstElementInNonPrimitiveChild;
         private int _maxBytesPerRead;
-        private OnXmlDictionaryReaderClose _onReaderClose;
+        private OnXmlDictionaryReaderClose? _onReaderClose;
         private bool _readServerTypeElement;
         private int _scopeDepth;
-        private JsonNodeType[] _scopes;
+        private JsonNodeType[]? _scopes;
 
         private enum JsonComplexTextMode
         {
@@ -322,7 +324,7 @@ namespace System.Runtime.Serialization.Json
         {
             get
             {
-                return ((_scopeDepth > 0) && (_scopes[_scopeDepth] == JsonNodeType.Collection));
+                return ((_scopeDepth > 0) && (_scopes![_scopeDepth] == JsonNodeType.Collection));
             }
         }
 
@@ -337,7 +339,7 @@ namespace System.Runtime.Serialization.Json
 
         protected override void Dispose(bool disposing)
         {
-            OnXmlDictionaryReaderClose onClose = _onReaderClose;
+            OnXmlDictionaryReaderClose? onClose = _onReaderClose;
             _onReaderClose = null;
             ResetState();
             if (onClose != null)
@@ -369,7 +371,7 @@ namespace System.Runtime.Serialization.Json
             return UnescapeJsonString(base.GetAttribute(index));
         }
 
-        public override string GetAttribute(string localName, string namespaceUri)
+        public override string? GetAttribute(string localName, string? namespaceUri)
         {
             if (localName != JsonGlobals.typeString)
             {
@@ -377,7 +379,7 @@ namespace System.Runtime.Serialization.Json
             }
             return base.GetAttribute(localName, namespaceUri);
         }
-        public override string GetAttribute(string name)
+        public override string? GetAttribute(string name)
         {
             if (name != JsonGlobals.typeString)
             {
@@ -386,7 +388,7 @@ namespace System.Runtime.Serialization.Json
             return base.GetAttribute(name);
         }
 
-        public override string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public override string? GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
         {
             if (XmlDictionaryString.GetString(localName) != JsonGlobals.typeString)
             {
@@ -417,6 +419,7 @@ namespace System.Runtime.Serialization.Json
                 BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead);
             }
 
+            Debug.Assert(_charactersToSkipOnNextRead != null);
             byte ch;
 
             // Skip whitespace before checking EOF
@@ -806,8 +809,8 @@ namespace System.Runtime.Serialization.Json
             return base.ReadValueChunk(chars, offset, count);
         }
 
-        public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas,
-            OnXmlDictionaryReaderClose onClose)
+        public void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas,
+            OnXmlDictionaryReaderClose? onClose)
         {
             if (buffer == null)
             {
@@ -832,13 +835,13 @@ namespace System.Runtime.Serialization.Json
             MoveToInitial(quotas, onClose);
 
             ArraySegment<byte> seg = JsonEncodingStreamWrapper.ProcessBuffer(buffer, offset, count, encoding);
-            BufferReader.SetBuffer(seg.Array, seg.Offset, seg.Count, null, null);
+            BufferReader.SetBuffer(seg.Array!, seg.Offset, seg.Count, null, null);
             _buffered = true;
             ResetState();
         }
 
-        public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas,
-            OnXmlDictionaryReaderClose onClose)
+        public void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas,
+            OnXmlDictionaryReaderClose? onClose)
         {
             if (stream == null)
             {
@@ -853,7 +856,7 @@ namespace System.Runtime.Serialization.Json
             ResetState();
         }
 
-        public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
+        public override void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes)
         {
             throw new NotSupportedException();
         }
@@ -1080,7 +1083,7 @@ namespace System.Runtime.Serialization.Json
 
         private JsonNodeType ExitJsonScope()
         {
-            JsonNodeType nodeTypeToReturn = _scopes[_scopeDepth];
+            JsonNodeType nodeTypeToReturn = _scopes![_scopeDepth];
             _scopes[_scopeDepth] = JsonNodeType.None;
             _scopeDepth--;
             return nodeTypeToReturn;
@@ -1092,7 +1095,7 @@ namespace System.Runtime.Serialization.Json
             base.MoveToEndElement();
         }
 
-        private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
+        private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose)
         {
             MoveToInitial(quotas);
             _maxBytesPerRead = quotas.MaxBytesPerRead;
@@ -1611,14 +1614,15 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        private string UnescapeJsonString(string val)
+        [return: NotNullIfNotNull("val")]
+        private string? UnescapeJsonString(string? val)
         {
             if (val == null)
             {
                 return null;
             }
 
-            StringBuilder sb = null;
+            StringBuilder? sb = null;
             int startIndex = 0, count = 0;
             for (int i = 0; i < val.Length; i++)
             {
index 3b28291..31c8c2f 100644 (file)
@@ -1,6 +1,7 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System.Diagnostics;
 using System.Diagnostics.CodeAnalysis;
 using System.Globalization;
 using System.IO;
@@ -62,9 +63,9 @@ namespace System.Runtime.Serialization.Json
             "\\u001f"
         };
 
-        private static BinHexEncoding s_binHexEncoding;
+        private static BinHexEncoding? s_binHexEncoding;
 
-        private string _attributeText;
+        private string? _attributeText;
         private JsonDataType _dataType;
         private int _depth;
         private bool _endElementBuffer;
@@ -74,21 +75,21 @@ namespace System.Runtime.Serialization.Json
         private bool _isWritingXmlnsAttributeDefaultNs;
         private NameState _nameState;
         private JsonNodeType _nodeType;
-        private JsonNodeWriter _nodeWriter;
-        private JsonNodeType[] _scopes;
-        private string _serverTypeValue;
+        private JsonNodeWriter _nodeWriter = null!; // initialized in SetOutput
+        private JsonNodeType[]? _scopes;
+        private string? _serverTypeValue;
         // Do not use this field's value anywhere other than the WriteState property.
         // It's OK to set this field's value anywhere and then change the WriteState property appropriately.
         // If it's necessary to check the WriteState outside WriteState, use the WriteState property.
         private WriteState _writeState;
         private bool _wroteServerTypeAttribute;
         private readonly bool _indent;
-        private readonly string _indentChars;
+        private readonly string? _indentChars;
         private int _indentLevel;
 
         public XmlJsonWriter() : this(false, null) { }
 
-        public XmlJsonWriter(bool indent, string indentChars)
+        public XmlJsonWriter(bool indent, string? indentChars)
         {
             _indent = indent;
             if (indent)
@@ -122,7 +123,7 @@ namespace System.Runtime.Serialization.Json
             WrittenNameWithMapping = 4,
         }
 
-        public override XmlWriterSettings Settings
+        public override XmlWriterSettings? Settings
         {
             // The XmlWriterSettings object used to create this writer instance.
             // If this writer was not created using the Create method, this property
@@ -158,7 +159,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        public override string XmlLang
+        public override string? XmlLang
         {
             get { return null; }
         }
@@ -184,7 +185,7 @@ namespace System.Runtime.Serialization.Json
 
         private bool IsClosed => (WriteState == WriteState.Closed);
 
-        private bool IsWritingCollection => (_depth > 0) && (_scopes[_depth] == JsonNodeType.Collection);
+        private bool IsWritingCollection => (_depth > 0) && (_scopes![_depth] == JsonNodeType.Collection);
 
         private bool IsWritingNameAttribute => (_nameState & NameState.IsWritingNameAttribute) == NameState.IsWritingNameAttribute;
 
@@ -230,7 +231,7 @@ namespace System.Runtime.Serialization.Json
             _nodeWriter.Flush();
         }
 
-        public override string LookupPrefix(string ns)
+        public override string? LookupPrefix(string ns)
         {
             if (ns == null)
             {
@@ -261,119 +262,120 @@ namespace System.Runtime.Serialization.Json
             {
                 throw new ArgumentNullException(nameof(encoding));
             }
-            if (encoding.WebName != Encoding.UTF8.WebName)
+            Encoding? tempEncoding = encoding;
+            if (tempEncoding.WebName != Encoding.UTF8.WebName)
             {
-                stream = new JsonEncodingStreamWrapper(stream, encoding, false);
+                stream = new JsonEncodingStreamWrapper(stream, tempEncoding, false);
             }
             else
             {
-                encoding = null;
+                tempEncoding = null;
             }
             if (_nodeWriter == null)
             {
                 _nodeWriter = new JsonNodeWriter();
             }
 
-            _nodeWriter.SetOutput(stream, ownsStream, encoding);
+            _nodeWriter.SetOutput(stream, ownsStream, tempEncoding);
             InitializeWriter();
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, bool[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, short[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, int[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, long[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, float[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, double[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, decimal[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, DateTime[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, Guid[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, TimeSpan[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, bool[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, decimal[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, double[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, float[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, int[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, long[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, short[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, DateTime[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, Guid[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, TimeSpan[] array, int offset, int count)
         {
             throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
         }
@@ -430,7 +432,7 @@ namespace System.Runtime.Serialization.Json
             WriteEscapedJsonString(BinHexEncoding.GetString(buffer, index, count));
         }
 
-        public override void WriteCData(string text)
+        public override void WriteCData(string? text)
         {
             WriteString(text);
         }
@@ -465,12 +467,12 @@ namespace System.Runtime.Serialization.Json
             WriteString(new string(buffer, index, count));
         }
 
-        public override void WriteComment(string text)
+        public override void WriteComment(string? text)
         {
             throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteComment"));
         }
 
-        public override void WriteDocType(string name, string pubid, string sysid, string subset)
+        public override void WriteDocType(string name, string? pubid, string? sysid, string? subset)
         {
             throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteDocType"));
         }
@@ -554,7 +556,7 @@ namespace System.Runtime.Serialization.Json
             }
             else if (IsWritingNameAttribute)
             {
-                WriteJsonElementName(_attributeText);
+                WriteJsonElementName(_attributeText!);
                 _attributeText = null;
                 _nameState = NameState.IsWritingNameWithMapping | NameState.WrittenNameWithMapping;
                 WriteDataTypeServerType();
@@ -680,7 +682,7 @@ namespace System.Runtime.Serialization.Json
                         }
                     }
                     _nodeWriter.WriteText(JsonGlobals.EndObjectChar);
-                    if ((_depth > 0) && _scopes[_depth] == JsonNodeType.Element)
+                    if ((_depth > 0) && _scopes![_depth] == JsonNodeType.Element)
                     {
                         ExitScope();
                         _endElementBuffer = true;
@@ -704,7 +706,7 @@ namespace System.Runtime.Serialization.Json
             WriteEndElement();
         }
 
-        public override void WriteProcessingInstruction(string name, string text)
+        public override void WriteProcessingInstruction(string name, string? text)
         {
             if (IsClosed)
             {
@@ -722,7 +724,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        public override void WriteQualifiedName(string localName, string ns)
+        public override void WriteQualifiedName(string localName, string? ns)
         {
             if (localName == null)
             {
@@ -770,7 +772,7 @@ namespace System.Runtime.Serialization.Json
             WriteString(new string(buffer, index, count));
         }
 
-        public override void WriteStartAttribute(string prefix, string localName, string ns)
+        public override void WriteStartAttribute(string? prefix, string localName, string? ns)
         {
             if (IsClosed)
             {
@@ -898,7 +900,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        public override void WriteStartElement(string prefix, string localName, string ns)
+        public override void WriteStartElement(string? prefix, string localName, string? ns)
         {
             if (localName == null)
             {
@@ -1009,7 +1011,7 @@ namespace System.Runtime.Serialization.Json
             _nodeType = JsonNodeType.Element;
         }
 
-        public override void WriteString(string text)
+        public override void WriteString(string? text)
         {
             if (HasOpenAttribute && (text != null))
             {
@@ -1084,7 +1086,7 @@ namespace System.Runtime.Serialization.Json
             _nodeWriter.WriteDateTimeText(value);
         }
 
-        public override void WriteValue(string value)
+        public override void WriteValue(string? value)
         {
             WriteString(value);
         }
@@ -1132,7 +1134,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        public override void WriteWhitespace(string ws)
+        public override void WriteWhitespace(string? ws)
         {
             if (IsClosed)
             {
@@ -1158,17 +1160,17 @@ namespace System.Runtime.Serialization.Json
             WriteString(ws);
         }
 
-        public override void WriteXmlAttribute(string localName, string value)
+        public override void WriteXmlAttribute(string localName, string? value)
         {
             throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlAttribute"));
         }
 
-        public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value)
+        public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString? value)
         {
             throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlAttribute"));
         }
 
-        public override void WriteXmlnsAttribute(string prefix, string namespaceUri)
+        public override void WriteXmlnsAttribute(string? prefix, string namespaceUri)
         {
             if (!IsWritingNameWithMapping)
             {
@@ -1176,7 +1178,7 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri)
+        public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString namespaceUri)
         {
             if (!IsWritingNameWithMapping)
             {
@@ -1232,7 +1234,7 @@ namespace System.Runtime.Serialization.Json
 
         private JsonNodeType ExitScope()
         {
-            JsonNodeType nodeTypeToReturn = _scopes[_depth];
+            JsonNodeType nodeTypeToReturn = _scopes![_depth];
             _scopes[_depth] = JsonNodeType.None;
             _depth--;
             return nodeTypeToReturn;
@@ -1433,7 +1435,7 @@ namespace System.Runtime.Serialization.Json
         {
             for (int i = 0; i < _indentLevel; i++)
             {
-                _nodeWriter.WriteText(_indentChars);
+                _nodeWriter.WriteText(_indentChars!);
             }
         }
 
@@ -1536,7 +1538,7 @@ namespace System.Runtime.Serialization.Json
 
         private void WriteServerTypeAttribute()
         {
-            string value = _serverTypeValue;
+            string? value = _serverTypeValue;
             JsonDataType oldDataType = _dataType;
             NameState oldNameState = _nameState;
             WriteStartElement(JsonGlobals.serverTypeString);
@@ -1569,7 +1571,7 @@ namespace System.Runtime.Serialization.Json
                 {
                     _nodeWriter.WriteText(JsonGlobals.WhitespaceChar);
                 }
-                WritePrimitiveValue(array.GetValue(i));
+                WritePrimitiveValue(array.GetValue(i)!);
             }
             _dataType = oldDataType;
         }
index 0212c48..39011d6 100644 (file)
@@ -10,24 +10,16 @@ using System.Runtime.Serialization.Json;
 using System.Runtime.Serialization;
 using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Runtime.Serialization.DataContract>;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization.Json
 {
     internal class XmlObjectSerializerReadContextComplexJson : XmlObjectSerializerReadContextComplex
     {
-        private string _extensionDataValueType;
-        private readonly DataContractJsonSerializer _jsonSerializer;
-        private readonly DateTimeFormat _dateTimeFormat;
+        private string? _extensionDataValueType;
+        private readonly DateTimeFormat? _dateTimeFormat;
         private readonly bool _useSimpleDictionaryFormat;
 
-        public XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
-            : base(null, int.MaxValue, default(StreamingContext), true)
-        {
-            this.rootTypeDataContract = rootTypeDataContract;
-            this.serializerKnownTypeList = serializer.KnownTypes;
-            _jsonSerializer = serializer;
-        }
-
         internal XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
             : base(serializer, serializer.MaxItemsInObjectGraph, default(StreamingContext), false)
         {
@@ -42,12 +34,12 @@ namespace System.Runtime.Serialization.Json
             return new XmlObjectSerializerReadContextComplexJson(serializer, rootTypeDataContract);
         }
 
-        protected override object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
+        protected override object? ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
         {
             return DataContractJsonSerializerImpl.ReadJsonValue(dataContract, reader, this);
         }
 
-        public int GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, int memberIndex, ExtensionDataObject extensionData)
+        public int GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, int memberIndex, ExtensionDataObject? extensionData)
         {
             int length = memberNames.Length;
             if (length != 0)
@@ -59,7 +51,7 @@ namespace System.Runtime.Serialization.Json
                         return index;
                     }
                 }
-                string name;
+                string? name;
                 if (TryGetJsonLocalName(xmlReader, out name))
                 {
                     for (int i = 0, index = (memberIndex + 1) % length; i < length; i++, index = (index + 1) % length)
@@ -75,7 +67,7 @@ namespace System.Runtime.Serialization.Json
             return length;
         }
 
-        internal IList<Type> SerializerKnownTypeList
+        internal IList<Type>? SerializerKnownTypeList
         {
             get
             {
@@ -96,7 +88,7 @@ namespace System.Runtime.Serialization.Json
             _extensionDataValueType = xmlReader.GetAttribute(JsonGlobals.typeString);
         }
 
-        protected override IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace)
+        protected override IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace)
         {
             IDataNode dataNode;
 
@@ -244,14 +236,14 @@ namespace System.Runtime.Serialization.Json
             }
             return new XmlQualifiedName(name, ns);
         }
-        internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
+        internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type? type)
         {
             DataContract dataContract = base.GetDataContract(typeHandle, type);
             DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
             return dataContract;
         }
 
-        internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
+        internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type? type)
         {
             DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type);
             DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
@@ -265,7 +257,7 @@ namespace System.Runtime.Serialization.Json
             return dataContract;
         }
 
-        internal static bool TryGetJsonLocalName(XmlReaderDelegator xmlReader, out string name)
+        internal static bool TryGetJsonLocalName(XmlReaderDelegator xmlReader, [NotNullWhen(true)] out string? name)
         {
             if (xmlReader.IsStartElement(JsonGlobals.itemDictionaryString, JsonGlobals.itemDictionaryString))
             {
@@ -281,7 +273,7 @@ namespace System.Runtime.Serialization.Json
 
         public static string GetJsonMemberName(XmlReaderDelegator xmlReader)
         {
-            string name;
+            string? name;
             if (!TryGetJsonLocalName(xmlReader, out name))
             {
                 name = xmlReader.LocalName;
index c3d9d7c..15d0335 100644 (file)
@@ -9,30 +9,16 @@ using System.Reflection;
 using System.Collections;
 using System.IO;
 using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Runtime.Serialization.DataContract>;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization.Json
 {
     internal class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex
     {
-        private readonly DataContractJsonSerializer _jsonSerializer;
         private readonly EmitTypeInformation _emitXsiType;
         private bool _perCallXsiTypeAlreadyEmitted;
         private readonly bool _useSimpleDictionaryFormat;
 
-        public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
-            : base(null, int.MaxValue, default(StreamingContext), true)
-
-        {
-            _jsonSerializer = serializer;
-            this.rootTypeDataContract = rootTypeDataContract;
-            this.serializerKnownTypeList = serializer.knownTypeList;
-        }
-
-        internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
-        {
-            return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract);
-        }
-
         internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
         {
             return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract);
@@ -48,7 +34,7 @@ namespace System.Runtime.Serialization.Json
             _useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
         }
 
-        internal IList<Type> SerializerKnownTypeList
+        internal IList<Type>? SerializerKnownTypeList
         {
             get
             {
@@ -79,7 +65,7 @@ namespace System.Runtime.Serialization.Json
             //Noop
         }
 
-        protected override void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace)
+        protected override void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string? dataContractNamespace)
         {
             if (_emitXsiType != EmitTypeInformation.Never)
             {
@@ -170,7 +156,7 @@ namespace System.Runtime.Serialization.Json
             JsonDataContract jsonDataContract = JsonDataContract.GetJsonDataContract(dataContract);
             if (_emitXsiType == EmitTypeInformation.Always && !_perCallXsiTypeAlreadyEmitted && RequiresJsonTypeInfo(dataContract))
             {
-                WriteTypeInfo(xmlWriter, jsonDataContract.TypeName);
+                WriteTypeInfo(xmlWriter, jsonDataContract.TypeName!);
             }
             _perCallXsiTypeAlreadyEmitted = false;
             DataContractJsonSerializerImpl.WriteJsonValue(jsonDataContract, xmlWriter, obj, this, declaredTypeHandle);
@@ -186,7 +172,7 @@ namespace System.Runtime.Serialization.Json
             get { return JsonGlobals.itemDictionaryString; }
         }
 
-        protected override void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
+        protected override void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type? objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
         {
             DataContract dataContract;
             bool verifyKnownType = false;
@@ -229,8 +215,8 @@ namespace System.Runtime.Serialization.Json
                 if (((CollectionDataContract)dataContract).Kind == CollectionKind.Dictionary)
                 {
                     // Convert non-generic dictionary to generic dictionary
-                    IDictionary dictionaryObj = obj as IDictionary;
-                    Dictionary<object, object> genericDictionaryObj = new Dictionary<object, object>(dictionaryObj.Count);
+                    IDictionary dictionaryObj = (obj as IDictionary)!;
+                    Dictionary<object, object?> genericDictionaryObj = new Dictionary<object, object?>(dictionaryObj.Count);
                     // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
                     IDictionaryEnumerator e = dictionaryObj.GetEnumerator();
                     try
@@ -254,7 +240,7 @@ namespace System.Runtime.Serialization.Json
         internal override void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
         {
             bool verifyKnownType = false;
-            Type declaredType = rootTypeDataContract.UnderlyingType;
+            Type declaredType = rootTypeDataContract!.UnderlyingType;
             bool isDeclaredTypeInterface = declaredType.IsInterface;
 
             if (!(isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType))
@@ -354,7 +340,8 @@ namespace System.Runtime.Serialization.Json
             }
         }
 
-        internal static DataContract GetRevisedItemContract(DataContract oldItemContract)
+        [return: NotNullIfNotNull("oldItemContract")]
+        internal static DataContract? GetRevisedItemContract(DataContract oldItemContract)
         {
             if ((oldItemContract != null) &&
                 oldItemContract.UnderlyingType.IsGenericType &&
@@ -364,14 +351,14 @@ namespace System.Runtime.Serialization.Json
             }
             return oldItemContract;
         }
-        internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
+        internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type? type)
         {
             DataContract dataContract = base.GetDataContract(typeHandle, type);
             DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
             return dataContract;
         }
 
-        internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
+        internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type? type)
         {
             DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type);
             DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
index 9b524bd..79cd6fb 100644 (file)
@@ -20,7 +20,7 @@ namespace System.Runtime.Serialization
             _context = context;
         }
 
-        public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
+        public override bool TryResolveType(Type type, Type? declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString? typeName, out XmlDictionaryString? typeNamespace)
         {
             if (type == null)
             {
@@ -50,7 +50,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
+        public override Type? ResolveName(string typeName, string? typeNamespace, Type? declaredType, DataContractResolver knownTypeResolver)
         {
             if (typeName == null || typeNamespace == null)
                 return null;
index f023602..7945a64 100644 (file)
@@ -14,9 +14,9 @@ namespace System.Runtime.Serialization
         private const int InitialArraySize = 4;
 
         private int _count;
-        private object[] _objectArray;
-        private bool[] _isReferenceArray;
-        private Dictionary<object, object> _objectDictionary;
+        private object[]? _objectArray;
+        private bool[]? _isReferenceArray;
+        private Dictionary<object, object?>? _objectDictionary;
 
         internal void Push(object obj)
         {
@@ -34,7 +34,7 @@ namespace System.Runtime.Serialization
             else
             {
                 if (_objectDictionary == null)
-                    _objectDictionary = new Dictionary<object, object>();
+                    _objectDictionary = new Dictionary<object, object?>();
 
                 _objectDictionary.Add(obj, null);
                 _count++;
@@ -95,7 +95,7 @@ namespace System.Runtime.Serialization
             }
             for (int i = (currentCount - 1); i >= 0; i--)
             {
-                if (object.ReferenceEquals(obj, _objectArray[i]) && _isReferenceArray != null && !_isReferenceArray[i])
+                if (object.ReferenceEquals(obj, _objectArray![i]) && _isReferenceArray != null && !_isReferenceArray[i])
                     return true;
             }
             return false;
index 8f8b5b8..dbe8684 100644 (file)
@@ -11,7 +11,7 @@ namespace System.Runtime.Serialization
     {
         internal int m_currentCount;
         internal int[] m_ids;
-        internal object[] m_objs;
+        internal object?[] m_objs;
         internal bool[] m_isWrapped;
 
         public ObjectToIdCache()
@@ -131,7 +131,7 @@ namespace System.Runtime.Serialization
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.ObjectTableOverflow));
         }
 
-        private int ComputeStartPosition(object o)
+        private int ComputeStartPosition(object? o)
         {
             return (RuntimeHelpers.GetHashCode(o) & 0x7FFFFFFF) % m_objs.Length;
         }
@@ -140,14 +140,14 @@ namespace System.Runtime.Serialization
         {
             int size = GetPrime(m_objs.Length + 1); // The lookup does an inherent doubling
             int[] oldIds = m_ids;
-            object[] oldObjs = m_objs;
+            object?[] oldObjs = m_objs;
             m_ids = new int[size];
             m_objs = new object[size];
             m_isWrapped = new bool[size];
 
             for (int j = 0; j < oldObjs.Length; j++)
             {
-                object obj = oldObjs[j];
+                object? obj = oldObjs[j];
                 if (obj != null)
                 {
                     bool found, isWrapped;
index ed1c009..c094c8d 100644 (file)
@@ -18,15 +18,15 @@ namespace System.Runtime.Serialization
 
         protected PrimitiveDataContract(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(new PrimitiveDataContractCriticalHelper(type, name, ns))
         {
-            _helper = base.Helper as PrimitiveDataContractCriticalHelper;
+            _helper = (base.Helper as PrimitiveDataContractCriticalHelper)!;
         }
 
-        internal static PrimitiveDataContract GetPrimitiveDataContract(Type type)
+        internal static PrimitiveDataContract? GetPrimitiveDataContract(Type type)
         {
             return DataContract.GetBuiltInDataContract(type) as PrimitiveDataContract;
         }
 
-        internal static PrimitiveDataContract GetPrimitiveDataContract(string name, string ns)
+        internal static PrimitiveDataContract? GetPrimitiveDataContract(string name, string ns)
         {
             return DataContract.GetBuiltInDataContract(name, ns) as PrimitiveDataContract;
         }
@@ -34,7 +34,7 @@ namespace System.Runtime.Serialization
         internal abstract string WriteMethodName { get; }
         internal abstract string ReadMethodName { get; }
 
-        public override XmlDictionaryString TopLevelElementNamespace
+        public override XmlDictionaryString? TopLevelElementNamespace
         {
             get
             { return DictionaryGlobals.SerializationNamespace; }
@@ -56,9 +56,9 @@ namespace System.Runtime.Serialization
                 if (_helper.XmlFormatWriterMethod == null)
                 {
                     if (UnderlyingType.IsValueType)
-                        _helper.XmlFormatWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
+                        _helper.XmlFormatWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })!;
                     else
-                        _helper.XmlFormatWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
+                        _helper.XmlFormatWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })!;
                 }
                 return _helper.XmlFormatWriterMethod;
             }
@@ -71,9 +71,9 @@ namespace System.Runtime.Serialization
                 if (_helper.XmlFormatContentWriterMethod == null)
                 {
                     if (UnderlyingType.IsValueType)
-                        _helper.XmlFormatContentWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType });
+                        _helper.XmlFormatContentWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType })!;
                     else
-                        _helper.XmlFormatContentWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType });
+                        _helper.XmlFormatContentWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType })!;
                 }
                 return _helper.XmlFormatContentWriterMethod;
             }
@@ -85,13 +85,13 @@ namespace System.Runtime.Serialization
             {
                 if (_helper.XmlFormatReaderMethod == null)
                 {
-                    _helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers);
+                    _helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers)!;
                 }
                 return _helper.XmlFormatReaderMethod;
             }
         }
 
-        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context)
         {
             xmlWriter.WriteAnyType(obj);
         }
@@ -118,28 +118,28 @@ namespace System.Runtime.Serialization
 
         private class PrimitiveDataContractCriticalHelper : DataContract.DataContractCriticalHelper
         {
-            private MethodInfo _xmlFormatWriterMethod;
-            private MethodInfo _xmlFormatContentWriterMethod;
-            private MethodInfo _xmlFormatReaderMethod;
+            private MethodInfo? _xmlFormatWriterMethod;
+            private MethodInfo? _xmlFormatContentWriterMethod;
+            private MethodInfo? _xmlFormatReaderMethod;
 
             internal PrimitiveDataContractCriticalHelper(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(type)
             {
                 SetDataContractName(name, ns);
             }
 
-            internal MethodInfo XmlFormatWriterMethod
+            internal MethodInfo? XmlFormatWriterMethod
             {
                 get { return _xmlFormatWriterMethod; }
                 set { _xmlFormatWriterMethod = value; }
             }
 
-            internal MethodInfo XmlFormatContentWriterMethod
+            internal MethodInfo? XmlFormatContentWriterMethod
             {
                 get { return _xmlFormatContentWriterMethod; }
                 set { _xmlFormatContentWriterMethod = value; }
             }
 
-            internal MethodInfo XmlFormatReaderMethod
+            internal MethodInfo? XmlFormatReaderMethod
             {
                 get { return _xmlFormatReaderMethod; }
                 set { _xmlFormatReaderMethod = value; }
@@ -160,20 +160,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteChar"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsChar"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteChar((char)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsChar()
                 : HandleReadValue(reader.ReadElementContentAsChar(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteChar((char)obj, name, ns);
+            xmlWriter.WriteChar((char)obj!, name, ns);
         }
     }
 
@@ -191,20 +191,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteBoolean"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsBoolean"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteBoolean((bool)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsBoolean()
                 : HandleReadValue(reader.ReadElementContentAsBoolean(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteBoolean((bool)obj, name, ns);
+            xmlWriter.WriteBoolean((bool)obj!, name, ns);
         }
     }
 
@@ -217,20 +217,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteSignedByte"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsSignedByte"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteSignedByte((sbyte)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsSignedByte()
                 : HandleReadValue(reader.ReadElementContentAsSignedByte(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteSignedByte((sbyte)obj, name, ns);
+            xmlWriter.WriteSignedByte((sbyte)obj!, name, ns);
         }
     }
 
@@ -243,20 +243,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteUnsignedByte"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedByte"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteUnsignedByte((byte)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsUnsignedByte()
                 : HandleReadValue(reader.ReadElementContentAsUnsignedByte(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteUnsignedByte((byte)obj, name, ns);
+            xmlWriter.WriteUnsignedByte((byte)obj!, name, ns);
         }
     }
 
@@ -269,20 +269,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteShort"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsShort"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteShort((short)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsShort()
                 : HandleReadValue(reader.ReadElementContentAsShort(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteShort((short)obj, name, ns);
+            xmlWriter.WriteShort((short)obj!, name, ns);
         }
     }
 
@@ -295,20 +295,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteUnsignedShort"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedShort"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteUnsignedShort((ushort)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsUnsignedShort()
                 : HandleReadValue(reader.ReadElementContentAsUnsignedShort(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteUnsignedShort((ushort)obj, name, ns);
+            xmlWriter.WriteUnsignedShort((ushort)obj!, name, ns);
         }
     }
 
@@ -335,17 +335,17 @@ namespace System.Runtime.Serialization
             }
         }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             throw new NotImplementedException();
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             throw new NotImplementedException();
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
             throw new NotImplementedException();
         }
@@ -360,20 +360,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteInt"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsInt"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteInt((int)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsInt()
                 : HandleReadValue(reader.ReadElementContentAsInt(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteInt((int)obj, name, ns);
+            xmlWriter.WriteInt((int)obj!, name, ns);
         }
     }
 
@@ -386,20 +386,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteUnsignedInt"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedInt"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteUnsignedInt((uint)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsUnsignedInt()
                 : HandleReadValue(reader.ReadElementContentAsUnsignedInt(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteUnsignedInt((uint)obj, name, ns);
+            xmlWriter.WriteUnsignedInt((uint)obj!, name, ns);
         }
     }
 
@@ -416,20 +416,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteLong"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsLong"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteLong((long)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsLong()
                 : HandleReadValue(reader.ReadElementContentAsLong(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteLong((long)obj, name, ns);
+            xmlWriter.WriteLong((long)obj!, name, ns);
         }
     }
 
@@ -467,20 +467,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteUnsignedLong"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedLong"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteUnsignedLong((ulong)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsUnsignedLong()
                 : HandleReadValue(reader.ReadElementContentAsUnsignedLong(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteUnsignedLong((ulong)obj, name, ns);
+            xmlWriter.WriteUnsignedLong((ulong)obj!, name, ns);
         }
     }
 
@@ -493,20 +493,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteFloat"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsFloat"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteFloat((float)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsFloat()
                 : HandleReadValue(reader.ReadElementContentAsFloat(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteFloat((float)obj, name, ns);
+            xmlWriter.WriteFloat((float)obj!, name, ns);
         }
     }
 
@@ -519,20 +519,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteDouble"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsDouble"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteDouble((double)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsDouble()
                 : HandleReadValue(reader.ReadElementContentAsDouble(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteDouble((double)obj, name, ns);
+            xmlWriter.WriteDouble((double)obj!, name, ns);
         }
     }
 
@@ -545,20 +545,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteDecimal"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsDecimal"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteDecimal((decimal)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsDecimal()
                 : HandleReadValue(reader.ReadElementContentAsDecimal(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteDecimal((decimal)obj, name, ns);
+            xmlWriter.WriteDecimal((decimal)obj!, name, ns);
         }
     }
 
@@ -571,20 +571,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteDateTime"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsDateTime"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteDateTime((DateTime)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsDateTime()
                 : HandleReadValue(reader.ReadElementContentAsDateTime(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteDateTime((DateTime)obj, name, ns);
+            xmlWriter.WriteDateTime((DateTime)obj!, name, ns);
         }
     }
 
@@ -601,12 +601,12 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteString"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsString"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteString((string)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             if (context == null)
             {
@@ -618,9 +618,9 @@ namespace System.Runtime.Serialization
             }
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            context.WriteString(xmlWriter, (string)obj, name, ns);
+            context.WriteString(xmlWriter, (string?)obj, name, ns);
         }
     }
 
@@ -733,12 +733,12 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteBase64"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsBase64"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteBase64((byte[])obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             if (context == null)
             {
@@ -750,10 +750,10 @@ namespace System.Runtime.Serialization
             }
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
             xmlWriter.WriteStartElement(name, ns);
-            xmlWriter.WriteBase64((byte[])obj);
+            xmlWriter.WriteBase64((byte[]?)obj);
             xmlWriter.WriteEndElement();
         }
     }
@@ -767,12 +767,12 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteAnyType"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsAnyType"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             // write nothing
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             object obj;
             if (reader.IsEmptyElement)
@@ -822,20 +822,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteTimeSpan"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsTimeSpan"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteTimeSpan((TimeSpan)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsTimeSpan()
                 : HandleReadValue(reader.ReadElementContentAsTimeSpan(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator writer, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            writer.WriteTimeSpan((TimeSpan)obj, name, ns);
+            writer.WriteTimeSpan((TimeSpan)obj!, name, ns);
         }
     }
 
@@ -857,20 +857,20 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteGuid"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsGuid"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteGuid((Guid)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             return (context == null) ? reader.ReadElementContentAsGuid()
                 : HandleReadValue(reader.ReadElementContentAsGuid(), context);
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            xmlWriter.WriteGuid((Guid)obj, name, ns);
+            xmlWriter.WriteGuid((Guid)obj!, name, ns);
         }
     }
 
@@ -888,12 +888,12 @@ namespace System.Runtime.Serialization
         internal override string WriteMethodName { get { return "WriteUri"; } }
         internal override string ReadMethodName { get { return "ReadElementContentAsUri"; } }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteUri((Uri)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             if (context == null)
             {
@@ -905,9 +905,9 @@ namespace System.Runtime.Serialization
             }
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator writer, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            writer.WriteUri((Uri)obj, name, ns);
+            writer.WriteUri((Uri?)obj, name, ns);
         }
     }
 
@@ -925,12 +925,12 @@ namespace System.Runtime.Serialization
             get { return false; }
         }
 
-        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context)
         {
             writer.WriteQName((XmlQualifiedName)obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context)
         {
             if (context == null)
             {
@@ -942,12 +942,12 @@ namespace System.Runtime.Serialization
             }
         }
 
-        public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns)
+        public override void WriteXmlElement(XmlWriterDelegator writer, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns)
         {
-            context.WriteQName(writer, (XmlQualifiedName)obj, name, ns);
+            context.WriteQName(writer, (XmlQualifiedName?)obj, name, ns);
         }
 
-        internal override void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns)
+        internal override void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString? ns)
         {
             if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace))
                 writer.WriteStartElement(Globals.SerPrefix, name, ns);
index 86801f8..6253555 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Runtime.Serialization
 {
     internal abstract class ReflectionClassWriter
     {
-        public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, XmlDictionaryString[] memberNames)
+        public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, XmlDictionaryString[]? memberNames)
         {
             InvokeOnSerializing(obj, context, classContract);
             obj = ResolveAdapterType(obj, classContract);
@@ -37,14 +37,16 @@ namespace System.Runtime.Serialization
             InvokeOnSerialized(obj, context, classContract);
         }
 
-        public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object value, bool writeXsiType, PrimitiveDataContract primitiveContractForParamType)
+        public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object? value, bool writeXsiType, PrimitiveDataContract? primitiveContractForParamType)
         {
             Type memberType = type;
-            object memberValue = value;
+            object? memberValue = value;
             bool originValueIsNullableOfT = (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);
             if (memberType.IsValueType && !originValueIsNullableOfT)
             {
-                PrimitiveDataContract primitiveContract = primitiveContractForParamType;
+                Debug.Assert(memberValue != null);
+
+                PrimitiveDataContract? primitiveContract = primitiveContractForParamType;
                 if (primitiveContract != null && !writeXsiType)
                 {
                     primitiveContract.WriteXmlValue(xmlWriter, memberValue, context);
@@ -60,12 +62,12 @@ namespace System.Runtime.Serialization
                 {
                     if (memberValue == null)
                     {
-                        memberType = Nullable.GetUnderlyingType(memberType);
+                        memberType = Nullable.GetUnderlyingType(memberType)!;
                     }
                     else
                     {
-                        MethodInfo getValue = memberType.GetMethod("get_Value", Array.Empty<Type>());
-                        memberValue = getValue.Invoke(memberValue, Array.Empty<object>());
+                        MethodInfo getValue = memberType.GetMethod("get_Value", Array.Empty<Type>())!;
+                        memberValue = getValue.Invoke(memberValue, Array.Empty<object>())!;
                         memberType = memberValue.GetType();
                     }
                 }
@@ -76,7 +78,7 @@ namespace System.Runtime.Serialization
                 }
                 else
                 {
-                    PrimitiveDataContract primitiveContract = originValueIsNullableOfT ? PrimitiveDataContract.GetPrimitiveDataContract(memberType) : primitiveContractForParamType;
+                    PrimitiveDataContract? primitiveContract = originValueIsNullableOfT ? PrimitiveDataContract.GetPrimitiveDataContract(memberType) : primitiveContractForParamType;
                     if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType)
                     {
                         primitiveContract.WriteXmlValue(xmlWriter, memberValue, context);
@@ -91,21 +93,21 @@ namespace System.Runtime.Serialization
                         }
                         else
                         {
-                            ReflectionInternalSerialize(xmlWriter, context, memberValue, memberValue.GetType().TypeHandle.Equals(memberType.TypeHandle), writeXsiType, memberType, originValueIsNullableOfT);
+                            ReflectionInternalSerialize(xmlWriter, context, memberValue!, memberValue!.GetType().TypeHandle.Equals(memberType.TypeHandle), writeXsiType, memberType, originValueIsNullableOfT);
                         }
                     }
                 }
             }
         }
 
-        protected abstract int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[] memberNames);
+        protected abstract int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[]? memberNames);
 
-        protected object ReflectionGetMemberValue(object obj, DataMember dataMember)
+        protected object? ReflectionGetMemberValue(object obj, DataMember dataMember)
         {
             return dataMember.Getter(obj);
         }
 
-        protected bool ReflectionTryWritePrimitive(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object value, XmlDictionaryString name, XmlDictionaryString ns, PrimitiveDataContract primitiveContract)
+        protected bool ReflectionTryWritePrimitive(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object? value, XmlDictionaryString name, XmlDictionaryString? ns, PrimitiveDataContract? primitiveContract)
         {
             if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
                 return false;
@@ -146,7 +148,7 @@ namespace System.Runtime.Serialization
             }
             else if (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePair)
             {
-                obj = classContract.KeyValuePairAdapterConstructorInfo.Invoke(new object[] { obj });
+                obj = classContract.KeyValuePairAdapterConstructorInfo!.Invoke(new object[] { obj });
             }
 
             return obj;
index 6673082..f1392a8 100644 (file)
@@ -5,6 +5,7 @@ using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Linq;
 using System.Reflection;
 using System.Runtime.Serialization.Json;
@@ -16,18 +17,20 @@ namespace System.Runtime.Serialization
 {
     internal abstract class ReflectionReader
     {
-        private delegate object CollectionReadItemDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type itemType, string itemName, string itemNs);
-        private delegate object CollectionSetItemDelegate(object resultCollection, object collectionItem, int itemIndex);
+        private delegate object? CollectionReadItemDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type itemType, string itemName, string itemNs);
+        private delegate object CollectionSetItemDelegate(object resultCollection, object? collectionItem, int itemIndex);
 
-        private static readonly MethodInfo s_getCollectionSetItemDelegateMethod = typeof(ReflectionReader).GetMethod(nameof(GetCollectionSetItemDelegate), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
-        private static readonly MethodInfo s_objectToKeyValuePairGetKey = typeof(ReflectionReader).GetMethod(nameof(ObjectToKeyValuePairGetKey), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
-        private static readonly MethodInfo s_objectToKeyValuePairGetValue = typeof(ReflectionReader).GetMethod(nameof(ObjectToKeyValuePairGetValue), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
+        private static readonly MethodInfo s_getCollectionSetItemDelegateMethod = typeof(ReflectionReader).GetMethod(nameof(GetCollectionSetItemDelegate), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)!;
+        private static readonly MethodInfo s_objectToKeyValuePairGetKey = typeof(ReflectionReader).GetMethod(nameof(ObjectToKeyValuePairGetKey), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!;
+        private static readonly MethodInfo s_objectToKeyValuePairGetValue = typeof(ReflectionReader).GetMethod(nameof(ObjectToKeyValuePairGetValue), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!;
 
         private static readonly Type[] s_arrayConstructorParameters = new Type[] { Globals.TypeOfInt };
         private static readonly object[] s_arrayConstructorArguments = new object[] { 32 };
 
-        public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, ClassDataContract classContract)
+        public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context, XmlDictionaryString[]? memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract)
         {
+            Debug.Assert(context != null);
+
             object obj = CreateObject(classContract);
             context.AddNewObject(obj);
             InvokeOnDeserializing(context, classContract, obj);
@@ -38,6 +41,7 @@ namespace System.Runtime.Serialization
             }
             else
             {
+                Debug.Assert(memberNames != null);
                 ReflectionReadMembers(xmlReader, context, memberNames, memberNamespaces, classContract, ref obj);
             }
 
@@ -55,7 +59,7 @@ namespace System.Runtime.Serialization
 
         public void ReflectionReadGetOnlyCollection(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString collectionItemName, XmlDictionaryString collectionItemNamespace, CollectionDataContract collectionContract)
         {
-            object resultCollection = context.GetCollectionMember();
+            object? resultCollection = context.GetCollectionMember();
             if (ReflectionReadSpecialCollection(xmlReader, context, collectionContract, resultCollection))
             {
                 return;
@@ -84,7 +88,7 @@ namespace System.Runtime.Serialization
             bool isArray = (collectionContract.Kind == CollectionKind.Array);
 
             int arraySize = context.GetArraySize();
-            object resultArray = null;
+            object? resultArray = null;
             if (isArray && ReflectionTryReadPrimitiveArray(xmlReader, context, collectionItemName, collectionItemNamespace, collectionContract.UnderlyingType, collectionContract.ItemType, arraySize, out resultArray))
             {
                 return resultArray;
@@ -128,14 +132,14 @@ namespace System.Runtime.Serialization
             Type itemType = collectionContract.ItemType;
             CollectionReadItemDelegate collectionReadItemDelegate = GetCollectionReadItemDelegate(collectionContract);
             MethodInfo getCollectionSetItemDelegateMethod = s_getCollectionSetItemDelegateMethod.MakeGenericMethod(itemType);
-            CollectionSetItemDelegate collectionSetItemDelegate = (CollectionSetItemDelegate)getCollectionSetItemDelegateMethod.Invoke(this, new object[] { collectionContract, resultCollection, isReadOnlyCollection });
+            CollectionSetItemDelegate collectionSetItemDelegate = (CollectionSetItemDelegate)getCollectionSetItemDelegateMethod.Invoke(this, new object[] { collectionContract, resultCollection, isReadOnlyCollection })!;
 
             int index = 0;
             while (true)
             {
                 if (xmlReader.IsStartElement(collectionItemName, collectionItemNamespace))
                 {
-                    object collectionItem = collectionReadItemDelegate(xmlReader, context, collectionContract, itemType, itemName, itemNs);
+                    object? collectionItem = collectionReadItemDelegate(xmlReader, context, collectionContract, itemType, itemName, itemNs);
                     resultCollection = collectionSetItemDelegate(resultCollection, collectionItem, index);
                     index++;
                 }
@@ -160,19 +164,19 @@ namespace System.Runtime.Serialization
             if (!isReadOnlyCollection && IsArrayLikeCollection(collectionContract))
             {
                 MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType);
-                resultCollection = trimArraySizeMethod.Invoke(null, new object[] { resultCollection, index });
+                resultCollection = trimArraySizeMethod.Invoke(null, new object[] { resultCollection, index })!;
             }
 
             return resultCollection;
         }
 
-        protected abstract void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, ClassDataContract classContract, ref object obj);
-        protected abstract object ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract);
+        protected abstract void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract, ref object obj);
+        protected abstract object? ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract);
         protected abstract string GetCollectionContractItemName(CollectionDataContract collectionContract);
         protected abstract string GetCollectionContractNamespace(CollectionDataContract collectionContract);
         protected abstract string GetClassContractNamespace(ClassDataContract classContract);
 
-        protected virtual bool ReflectionReadSpecialCollection(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, object resultCollection)
+        protected virtual bool ReflectionReadSpecialCollection(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, object? resultCollection)
         {
             return false;
         }
@@ -181,7 +185,7 @@ namespace System.Runtime.Serialization
         {
             int memberCount = (classContract.BaseContract == null) ? 0 : ReflectionGetMembers(classContract.BaseContract, members);
             int childElementIndex = memberCount;
-            for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
+            for (int i = 0; i < classContract.Members!.Count; i++, memberCount++)
             {
                 members[childElementIndex + i] = classContract.Members[i];
             }
@@ -211,9 +215,9 @@ namespace System.Runtime.Serialization
             }
         }
 
-        protected object ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, Type type, string name, string ns, PrimitiveDataContract primitiveContractForOriginalType = null)
+        protected object? ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, Type type, string name, string ns, PrimitiveDataContract? primitiveContractForOriginalType = null)
         {
-            object value = null;
+            object? value = null;
             int nullables = 0;
             while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
             {
@@ -221,7 +225,7 @@ namespace System.Runtime.Serialization
                 type = type.GetGenericArguments()[0];
             }
 
-            PrimitiveDataContract primitiveContract = nullables != 0 ?
+            PrimitiveDataContract? primitiveContract = nullables != 0 ?
                 PrimitiveDataContract.GetPrimitiveDataContract(type)
                 : (primitiveContractForOriginalType ?? PrimitiveDataContract.GetPrimitiveDataContract(type));
 
@@ -237,9 +241,9 @@ namespace System.Runtime.Serialization
             return value;
         }
 
-        private object ReadItemOfPrimitiveType(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, Type type, string name, string ns, PrimitiveDataContract primitiveContract, int nullables)
+        private object? ReadItemOfPrimitiveType(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, Type type, string name, string ns, PrimitiveDataContract? primitiveContract, int nullables)
         {
-            object value;
+            object? value;
             context.ReadAttributes(xmlReader);
             string objectId = context.ReadIfNullOrRef(xmlReader, type, DataContract.IsTypeSerializable(type));
             bool typeIsValueType = type.IsValueType;
@@ -295,7 +299,7 @@ namespace System.Runtime.Serialization
             object obj;
             SerializationInfo serializationInfo = context.ReadSerializationInfo(xmlReader, classContract.UnderlyingType);
             StreamingContext streamingContext = context.GetStreamingContext();
-            ConstructorInfo iSerializableConstructor = classContract.GetISerializableConstructor();
+            ConstructorInfo iSerializableConstructor = classContract.GetISerializableConstructor()!;
             obj = iSerializableConstructor.Invoke(new object[] { serializationInfo, streamingContext });
             return obj;
         }
@@ -310,7 +314,7 @@ namespace System.Runtime.Serialization
                 type = type.GetGenericArguments()[0];
             }
 
-            PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
+            PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
             if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType)
             {
                 return (xmlReaderArg, contextArg, collectionContract, typeArg, nameArg, nsArg) =>
@@ -324,17 +328,17 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private object ReflectionGetMemberValue(object obj, DataMember dataMember)
+        private object? ReflectionGetMemberValue(object obj, DataMember dataMember)
         {
             return dataMember.Getter(obj);
         }
 
-        private void ReflectionSetMemberValue(ref object obj, object memberValue, DataMember dataMember)
+        private void ReflectionSetMemberValue(ref object obj, object? memberValue, DataMember dataMember)
         {
             dataMember.Setter(ref obj, memberValue);
         }
 
-        private object ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, DataMember dataMember, string ns)
+        private object? ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, DataMember dataMember, string ns)
         {
             Type type = dataMember.MemberType;
             string name = dataMember.Name;
@@ -342,7 +346,7 @@ namespace System.Runtime.Serialization
             return ReflectionReadValue(xmlReader, context, type, name, ns, dataMember.MemberPrimitiveContract);
         }
 
-        private object ReflectionInternalDeserialize(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type type, string name, string ns)
+        private object? ReflectionInternalDeserialize(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract? collectionContract, Type type, string name, string ns)
         {
             return context.InternalDeserialize(xmlReader, DataContract.GetId(type.TypeHandle), type.TypeHandle, name, ns);
         }
@@ -377,7 +381,7 @@ namespace System.Runtime.Serialization
 
         private static object CreateObject(ClassDataContract classContract)
         {
-            object obj;
+            object? obj;
             if (!classContract.CreateNewInstanceViaDefaultConstructor(out obj))
             {
                 Type classType = classContract.UnderlyingType;
@@ -396,7 +400,7 @@ namespace System.Runtime.Serialization
             }
             else if (obj is IKeyValuePairAdapter)
             {
-                obj = classContract.GetKeyValuePairMethodInfo.Invoke(obj, Array.Empty<object>());
+                obj = classContract.GetKeyValuePairMethodInfo!.Invoke(obj, Array.Empty<object>())!;
             }
 
             return obj;
@@ -430,14 +434,14 @@ namespace System.Runtime.Serialization
             if (IsArrayLikeCollection(collectionContract))
             {
                 Type arrayType = collectionContract.ItemType.MakeArrayType();
-                var ci = arrayType.GetConstructor(s_arrayConstructorParameters);
+                var ci = arrayType.GetConstructor(s_arrayConstructorParameters)!;
                 var newArray = ci.Invoke(s_arrayConstructorArguments);
                 return newArray;
             }
             else if (collectionContract.Kind == CollectionKind.GenericDictionary && collectionContract.UnderlyingType.IsInterface)
             {
                 Type type = Globals.TypeOfDictionaryGeneric.MakeGenericType(collectionContract.ItemType.GetGenericArguments());
-                ConstructorInfo ci = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
+                ConstructorInfo ci = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>())!;
                 object newGenericDict = ci.Invoke(Array.Empty<object>());
                 return newGenericDict;
             }
@@ -445,7 +449,7 @@ namespace System.Runtime.Serialization
             {
                 if (collectionContract.UnderlyingType.IsValueType)
                 {
-                    object newValueObject = Activator.CreateInstance(collectionContract.UnderlyingType);
+                    object newValueObject = Activator.CreateInstance(collectionContract.UnderlyingType)!;
                     return newValueObject;
                 }
                 else if (collectionContract.UnderlyingType == Globals.TypeOfIDictionary)
@@ -455,19 +459,19 @@ namespace System.Runtime.Serialization
                 }
                 else
                 {
-                    ConstructorInfo ci = collectionContract.Constructor;
+                    ConstructorInfo ci = collectionContract.Constructor!;
                     object newCollection = ci.Invoke(Array.Empty<object>());
                     return newCollection;
                 }
             }
         }
 
-        private static object ObjectToKeyValuePairGetKey<K, V>(object o)
+        private static object? ObjectToKeyValuePairGetKey<K, V>(object o)
         {
             return ((KeyValue<K, V>)o).Key;
         }
 
-        private static object ObjectToKeyValuePairGetValue<K, V>(object o)
+        private static object? ObjectToKeyValuePairGetValue<K, V>(object o)
         {
             return ((KeyValue<K, V>)o).Value;
         }
@@ -484,7 +488,7 @@ namespace System.Runtime.Serialization
                         XmlObjectSerializerReadContext.ThrowArrayExceededSizeException(arraySize, collectionContract.UnderlyingType);
                     }
 
-                    ((T[])resultCollection)[index] = (T)collectionItem;
+                    ((T[])resultCollection)[index] = (T)collectionItem!;
                     return resultCollection;
                 };
             }
@@ -493,7 +497,7 @@ namespace System.Runtime.Serialization
                 return (resultCollection, collectionItem, index) =>
                 {
                     resultCollection = XmlObjectSerializerReadContext.EnsureArraySize((T[])resultCollection, index);
-                    ((T[])resultCollection)[index] = (T)collectionItem;
+                    ((T[])resultCollection)[index] = (T)collectionItem!;
                     return resultCollection;
                 };
             }
@@ -501,17 +505,17 @@ namespace System.Runtime.Serialization
             {
                 Type keyType = collectionContract.ItemType.GenericTypeArguments[0];
                 Type valueType = collectionContract.ItemType.GenericTypeArguments[1];
-                Func<object, object> objectToKeyValuePairGetKey = s_objectToKeyValuePairGetKey.MakeGenericMethod(keyType, valueType).CreateDelegate<Func<object, object>>();
-                Func<object, object> objectToKeyValuePairGetValue = s_objectToKeyValuePairGetValue.MakeGenericMethod(keyType, valueType).CreateDelegate<Func<object, object>>();
+                Func<object, object?> objectToKeyValuePairGetKey = s_objectToKeyValuePairGetKey.MakeGenericMethod(keyType, valueType).CreateDelegate<Func<object, object?>>();
+                Func<object, object?> objectToKeyValuePairGetValue = s_objectToKeyValuePairGetValue.MakeGenericMethod(keyType, valueType).CreateDelegate<Func<object, object?>>();
 
                 if (collectionContract.Kind == CollectionKind.GenericDictionary)
                 {
                     return (resultCollection, collectionItem, index) =>
                     {
-                        object key = objectToKeyValuePairGetKey(collectionItem);
-                        object value = objectToKeyValuePairGetValue(collectionItem);
+                        object? key = objectToKeyValuePairGetKey(collectionItem!);
+                        object? value = objectToKeyValuePairGetValue(collectionItem!);
 
-                        collectionContract.AddMethod.Invoke(resultCollection, new object[] { key, value });
+                        collectionContract.AddMethod!.Invoke(resultCollection, new object?[] { key, value });
                         return resultCollection;
                     };
                 }
@@ -519,11 +523,11 @@ namespace System.Runtime.Serialization
                 {
                     return (resultCollection, collectionItem, index) =>
                     {
-                        object key = objectToKeyValuePairGetKey(collectionItem);
-                        object value = objectToKeyValuePairGetValue(collectionItem);
+                        object? key = objectToKeyValuePairGetKey(collectionItem!);
+                        object? value = objectToKeyValuePairGetValue(collectionItem!);
 
                         IDictionary dict = (IDictionary)resultCollection;
-                        dict.Add(key, value);
+                        dict.Add(key!, value);
                         return resultCollection;
                     };
                 }
@@ -537,7 +541,7 @@ namespace System.Runtime.Serialization
                 {
                     return (resultCollection, collectionItem, index) =>
                     {
-                        ((ICollection<T>)resultCollection).Add((T)collectionItem);
+                        ((ICollection<T>)resultCollection).Add((T)collectionItem!);
                         return resultCollection;
                     };
                 }
@@ -551,7 +555,7 @@ namespace System.Runtime.Serialization
                 }
                 else
                 {
-                    MethodInfo addMethod = collectionContract.AddMethod;
+                    MethodInfo? addMethod = collectionContract.AddMethod;
                     if (addMethod == null)
                     {
                         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(collectionContract.UnderlyingType))));
@@ -559,18 +563,18 @@ namespace System.Runtime.Serialization
 
                     return (resultCollection, collectionItem, index) =>
                     {
-                        addMethod.Invoke(resultCollection, new object[] { collectionItem });
+                        addMethod.Invoke(resultCollection, new object?[] { collectionItem });
                         return resultCollection;
                     };
                 }
             }
         }
 
-        private bool ReflectionTryReadPrimitiveArray(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString collectionItemName, XmlDictionaryString collectionItemNamespace, Type type, Type itemType, int arraySize, out object resultArray)
+        private bool ReflectionTryReadPrimitiveArray(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString collectionItemName, XmlDictionaryString collectionItemNamespace, Type type, Type itemType, int arraySize, [NotNullWhen(true)] out object? resultArray)
         {
             resultArray = null;
 
-            PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
+            PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
             if (primitiveContract == null)
                 return false;
 
@@ -578,57 +582,71 @@ namespace System.Runtime.Serialization
             {
                 case TypeCode.Boolean:
                     {
-                        bool[] boolArray = null;
-                        xmlReader.TryReadBooleanArray(context, collectionItemName, collectionItemNamespace, arraySize, out boolArray);
-                        resultArray = boolArray;
+                        bool[]? boolArray;
+                        if (xmlReader.TryReadBooleanArray(context, collectionItemName, collectionItemNamespace, arraySize, out boolArray))
+                        {
+                            resultArray = boolArray;
+                        }
                     }
                     break;
                 case TypeCode.DateTime:
                     {
-                        DateTime[] dateTimeArray = null;
-                        xmlReader.TryReadDateTimeArray(context, collectionItemName, collectionItemNamespace, arraySize, out dateTimeArray);
-                        resultArray = dateTimeArray;
+                        DateTime[]? dateTimeArray;
+                        if (xmlReader.TryReadDateTimeArray(context, collectionItemName, collectionItemNamespace, arraySize, out dateTimeArray))
+                        {
+                            resultArray = dateTimeArray;
+                        }
                     }
                     break;
                 case TypeCode.Decimal:
                     {
-                        decimal[] decimalArray = null;
-                        xmlReader.TryReadDecimalArray(context, collectionItemName, collectionItemNamespace, arraySize, out decimalArray);
-                        resultArray = decimalArray;
+                        decimal[]? decimalArray;
+                        if (xmlReader.TryReadDecimalArray(context, collectionItemName, collectionItemNamespace, arraySize, out decimalArray))
+                        {
+                            resultArray = decimalArray;
+                        }
                     }
                     break;
                 case TypeCode.Int32:
                     {
-                        int[] intArray = null;
-                        xmlReader.TryReadInt32Array(context, collectionItemName, collectionItemNamespace, arraySize, out intArray);
-                        resultArray = intArray;
+                        int[]? intArray;
+                        if (xmlReader.TryReadInt32Array(context, collectionItemName, collectionItemNamespace, arraySize, out intArray))
+                        {
+                            resultArray = intArray;
+                        }
                     }
                     break;
                 case TypeCode.Int64:
                     {
-                        long[] longArray = null;
-                        xmlReader.TryReadInt64Array(context, collectionItemName, collectionItemNamespace, arraySize, out longArray);
-                        resultArray = longArray;
+                        long[]? longArray;
+                        if (xmlReader.TryReadInt64Array(context, collectionItemName, collectionItemNamespace, arraySize, out longArray))
+                        {
+                            resultArray = longArray;
+                        }
                     }
                     break;
                 case TypeCode.Single:
                     {
-                        float[] floatArray = null;
-                        xmlReader.TryReadSingleArray(context, collectionItemName, collectionItemNamespace, arraySize, out floatArray);
-                        resultArray = floatArray;
+                        float[]? floatArray;
+                        if (xmlReader.TryReadSingleArray(context, collectionItemName, collectionItemNamespace, arraySize, out floatArray))
+                        {
+                            resultArray = floatArray;
+                        }
                     }
                     break;
                 case TypeCode.Double:
                     {
-                        double[] doubleArray = null;
-                        xmlReader.TryReadDoubleArray(context, collectionItemName, collectionItemNamespace, arraySize, out doubleArray);
-                        resultArray = doubleArray;
+                        double[]? doubleArray;
+                        if (xmlReader.TryReadDoubleArray(context, collectionItemName, collectionItemNamespace, arraySize, out doubleArray))
+                        {
+                            resultArray = doubleArray;
+                        }
                     }
                     break;
                 default:
                     return false;
             }
-            return true;
+            return resultArray != null;
         }
     }
 }
index b21f583..9c45733 100644 (file)
@@ -25,7 +25,7 @@ namespace System.Runtime.Serialization
             _reflectionReader = new ReflectionXmlReader();
         }
 
-        public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces)
+        public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context, XmlDictionaryString[]? memberNames, XmlDictionaryString[]? memberNamespaces)
         {
             return _reflectionReader.ReflectionReadClass(xmlReader, context, memberNames, memberNamespaces, _classContract);
         }
@@ -48,9 +48,11 @@ namespace System.Runtime.Serialization
 
     internal sealed class ReflectionXmlReader : ReflectionReader
     {
-        protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, ClassDataContract classContract, ref object obj)
+        protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract, ref object obj)
         {
-            int memberCount = classContract.MemberNames.Length;
+            Debug.Assert(memberNamespaces != null);
+
+            int memberCount = classContract.MemberNames!.Length;
             context.IncrementItemCount(memberCount);
             int memberIndex = -1;
             int firstRequiredMember;
@@ -60,7 +62,7 @@ namespace System.Runtime.Serialization
             DataMember[] members = new DataMember[memberCount];
             int reflectedMemberCount = ReflectionGetMembers(classContract, members);
             Debug.Assert(reflectedMemberCount == memberCount, "The value returned by ReflectionGetMembers() should equal to memberCount.");
-            ExtensionDataObject extensionData = null;
+            ExtensionDataObject? extensionData = null;
 
             if (classContract.HasExtensionData)
             {
@@ -94,7 +96,7 @@ namespace System.Runtime.Serialization
 
         protected override string GetClassContractNamespace(ClassDataContract classContract)
         {
-            return classContract.StableName.Namespace;
+            return classContract.StableName!.Namespace;
         }
 
         protected override string GetCollectionContractItemName(CollectionDataContract collectionContract)
@@ -107,7 +109,7 @@ namespace System.Runtime.Serialization
             return collectionContract.StableName.Namespace;
         }
 
-        protected override object ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract)
+        protected override object? ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract)
         {
             Debug.Assert(collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary);
             context.ReadAttributes(xmlReader);
@@ -116,7 +118,7 @@ namespace System.Runtime.Serialization
 
         private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequiredMember)
         {
-            int memberCount = contract.MemberNames.Length;
+            int memberCount = contract.MemberNames!.Length;
             bool[] requiredMembers = new bool[memberCount];
             GetRequiredMembers(contract, requiredMembers);
             for (firstRequiredMember = 0; firstRequiredMember < memberCount; firstRequiredMember++)
@@ -128,7 +130,7 @@ namespace System.Runtime.Serialization
         private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers)
         {
             int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers);
-            List<DataMember> members = contract.Members;
+            List<DataMember> members = contract.Members!;
             for (int i = 0; i < members.Count; i++, memberCount++)
             {
                 requiredMembers[memberCount] = members[i].IsRequired;
index 6380108..643f3a6 100644 (file)
@@ -36,7 +36,7 @@ namespace System.Runtime.Serialization
                 if (!ReflectionTryWritePrimitiveArray(xmlWriter, obj, collectionDataContract.UnderlyingType, itemType, itemName, ns))
                 {
                     Array array = (Array)obj;
-                    PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
+                    PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
                     for (int i = 0; i < array.Length; ++i)
                     {
                         _reflectionClassWriter.ReflectionWriteStartElement(xmlWriter, itemType, ns, ns.Value, itemName.Value, 0);
@@ -50,7 +50,7 @@ namespace System.Runtime.Serialization
                 collectionDataContract.IncrementCollectionCount(xmlWriter, obj, context);
 
                 IEnumerator enumerator = collectionDataContract.GetEnumeratorForCollection(obj);
-                PrimitiveDataContract primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(collectionDataContract.UnderlyingType);
+                PrimitiveDataContract? primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(collectionDataContract.UnderlyingType);
 
                 if (primitiveContractForType != null && primitiveContractForType.UnderlyingType != Globals.TypeOfObject)
                 {
@@ -87,7 +87,7 @@ namespace System.Runtime.Serialization
 
         private bool ReflectionTryWritePrimitiveArray(XmlWriterDelegator xmlWriter, object obj, Type type, Type itemType, XmlDictionaryString collectionItemName, XmlDictionaryString itemNamespace)
         {
-            PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
+            PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
             if (primitiveContract == null)
                 return false;
 
@@ -124,16 +124,16 @@ namespace System.Runtime.Serialization
 
     internal sealed class ReflectionXmlClassWriter : ReflectionClassWriter
     {
-        protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[] emptyStringArray)
+        protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[]? emptyStringArray)
         {
             int memberCount = (classContract.BaseContract == null) ? 0 :
                 ReflectionWriteMembers(xmlWriter, obj, context, classContract.BaseContract, derivedMostClassContract, childElementIndex, emptyStringArray);
 
             childElementIndex += memberCount;
 
-            XmlDictionaryString[] memberNames = classContract.MemberNames;
+            XmlDictionaryString[] memberNames = classContract.MemberNames!;
             XmlDictionaryString ns = classContract.Namespace;
-            context.IncrementItemCount(classContract.Members.Count);
+            context.IncrementItemCount(classContract.Members!.Count);
             for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
             {
                 DataMember member = classContract.Members[i];
@@ -148,11 +148,11 @@ namespace System.Runtime.Serialization
                 }
 
                 bool shouldWriteValue = true;
-                object memberValue = null;
+                object? memberValue = null;
                 if (!member.EmitDefaultValue)
                 {
                     memberValue = ReflectionGetMemberValue(obj, member);
-                    object defaultValue = XmlFormatGeneratorStatics.GetDefaultValue(memberType);
+                    object? defaultValue = XmlFormatGeneratorStatics.GetDefaultValue(memberType);
                     if ((memberValue == null && defaultValue == null)
                         || (memberValue != null && memberValue.Equals(defaultValue)))
                     {
@@ -172,14 +172,14 @@ namespace System.Runtime.Serialization
                     {
                         memberValue = ReflectionGetMemberValue(obj, member);
                     }
-                    PrimitiveDataContract primitiveContract = member.MemberPrimitiveContract;
+                    PrimitiveDataContract? primitiveContract = member.MemberPrimitiveContract;
 
                     if (writeXsiType || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, ns, primitiveContract))
                     {
                         ReflectionWriteStartElement(xmlWriter, memberType, ns, ns.Value, member.Name, 0);
-                        if (classContract.ChildElementNamespaces[i + childElementIndex] != null)
+                        if (classContract.ChildElementNamespaces![i + childElementIndex] != null)
                         {
-                            var nsChildElement = classContract.ChildElementNamespaces[i + childElementIndex];
+                            var nsChildElement = classContract.ChildElementNamespaces[i + childElementIndex]!;
                             xmlWriter.WriteNamespaceDecl(nsChildElement);
                         }
                         ReflectionWriteValue(xmlWriter, context, memberType, memberValue, writeXsiType, primitiveContractForParamType: null);
@@ -215,7 +215,7 @@ namespace System.Runtime.Serialization
             xmlWriter.WriteEndElement();
         }
 
-        private bool NeedsPrefix(Type type, XmlDictionaryString ns)
+        private bool NeedsPrefix(Type type, XmlDictionaryString? ns)
         {
             return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0);
         }
@@ -227,14 +227,14 @@ namespace System.Runtime.Serialization
                 return true;
 
             // Check for conflict with derived type members
-            string name = member.Name;
-            string ns = classContract.StableName.Namespace;
-            ClassDataContract currentContract = derivedMostClassContract;
+            string? name = member.Name;
+            string? ns = classContract.StableName.Namespace;
+            ClassDataContract? currentContract = derivedMostClassContract;
             while (currentContract != null && currentContract != classContract)
             {
                 if (ns == currentContract.StableName.Namespace)
                 {
-                    List<DataMember> members = currentContract.Members;
+                    List<DataMember> members = currentContract.Members!;
                     for (int j = 0; j < members.Count; j++)
                     {
                         if (name == members[j].Name)
index 8c36110..d372854 100644 (file)
@@ -6,6 +6,7 @@ using System.Collections;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Globalization;
 using System.IO;
 using System.Reflection;
@@ -18,7 +19,7 @@ namespace System.Runtime.Serialization
     internal class SchemaExporter
     {
         private readonly XmlSchemaSet _schemas;
-        private XmlDocument _xmlDoc;
+        private XmlDocument? _xmlDoc;
         private DataContractSet _dataContractSet;
 
         internal SchemaExporter(XmlSchemaSet schemas, DataContractSet dataContractSet)
@@ -61,7 +62,7 @@ namespace System.Runtime.Serialization
             finally
             {
                 _xmlDoc = null;
-                _dataContractSet = null;
+                _dataContractSet = null!;
             }
         }
 
@@ -70,7 +71,7 @@ namespace System.Runtime.Serialization
             if (!Schemas.Contains(Globals.SerializationNamespace))
             {
                 StringReader reader = new StringReader(Globals.SerializationSchema);
-                XmlSchema schema = XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null);
+                XmlSchema? schema = XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null);
                 if (schema == null)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.CouldNotReadSerializationSchema, Globals.SerializationNamespace)));
                 Schemas.Add(schema);
@@ -104,13 +105,13 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private XmlSchemaElement ExportTopLevelElement(DataContract dataContract, XmlSchema schema)
+        private XmlSchemaElement ExportTopLevelElement(DataContract dataContract, XmlSchema? schema)
         {
-            if (schema == null || dataContract.StableName.Namespace != dataContract.TopLevelElementNamespace.Value)
-                schema = GetSchema(dataContract.TopLevelElementNamespace.Value);
+            if (schema == null || dataContract.StableName.Namespace != dataContract.TopLevelElementNamespace!.Value)
+                schema = GetSchema(dataContract.TopLevelElementNamespace!.Value);
 
             XmlSchemaElement topLevelElement = new XmlSchemaElement();
-            topLevelElement.Name = dataContract.TopLevelElementName.Value;
+            topLevelElement.Name = dataContract.TopLevelElementName!.Value;
             SetElementType(topLevelElement, dataContract, schema);
             topLevelElement.IsNillable = true;
             schema.Items.Add(topLevelElement);
@@ -122,18 +123,18 @@ namespace System.Runtime.Serialization
             XmlSchemaComplexType type = new XmlSchemaComplexType();
             type.Name = classDataContract.StableName.Name;
             schema.Items.Add(type);
-            XmlElement genericInfoElement = null;
+            XmlElement? genericInfoElement = null;
             if (classDataContract.UnderlyingType.IsGenericType)
                 genericInfoElement = ExportGenericInfo(classDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace);
 
             XmlSchemaSequence rootSequence = new XmlSchemaSequence();
-            for (int i = 0; i < classDataContract.Members.Count; i++)
+            for (int i = 0; i < classDataContract.Members!.Count; i++)
             {
                 DataMember dataMember = classDataContract.Members[i];
 
                 XmlSchemaElement element = new XmlSchemaElement();
                 element.Name = dataMember.Name;
-                XmlElement actualTypeElement = null;
+                XmlElement? actualTypeElement = null;
                 DataContract memberTypeContract = _dataContractSet.GetMemberTypeDataContract(dataMember);
                 if (CheckIfMemberHasConflict(dataMember))
                 {
@@ -153,7 +154,7 @@ namespace System.Runtime.Serialization
                 rootSequence.Items.Add(element);
             }
 
-            XmlElement isValueTypeElement = null;
+            XmlElement? isValueTypeElement = null;
             if (classDataContract.BaseContract != null)
             {
                 XmlSchemaComplexContentExtension extension = CreateTypeContent(type, classDataContract.BaseContract.StableName, schema);
@@ -184,7 +185,7 @@ namespace System.Runtime.Serialization
 
         private void SetElementType(XmlSchemaElement element, DataContract dataContract, XmlSchema schema)
         {
-            XmlDataContract xmlDataContract = dataContract as XmlDataContract;
+            XmlDataContract? xmlDataContract = dataContract as XmlDataContract;
             if (xmlDataContract != null && xmlDataContract.IsAnonymous)
             {
                 element.SchemaType = xmlDataContract.XsdType;
@@ -205,7 +206,7 @@ namespace System.Runtime.Serialization
             if (dataMember.HasConflictingNameAndType)
                 return true;
 
-            DataMember conflictingMember = dataMember.ConflictingMember;
+            DataMember? conflictingMember = dataMember.ConflictingMember;
             while (conflictingMember != null)
             {
                 if (conflictingMember.HasConflictingNameAndType)
@@ -216,7 +217,7 @@ namespace System.Runtime.Serialization
             return false;
         }
 
-        private XmlElement ExportEmitDefaultValue(DataMember dataMember)
+        private XmlElement? ExportEmitDefaultValue(DataMember dataMember)
         {
             if (dataMember.EmitDefaultValue)
                 return null;
@@ -249,7 +250,7 @@ namespace System.Runtime.Serialization
 
         private XmlElement ExportGenericInfo(Type clrType, string elementName, string elementNs)
         {
-            Type itemType;
+            Type? itemType;
             int nestedCollectionLevel = 0;
             while (CollectionDataContract.IsCollection(clrType, out itemType))
             {
@@ -262,8 +263,8 @@ namespace System.Runtime.Serialization
                 nestedCollectionLevel++;
             }
 
-            Type[] genericArguments = null;
-            IList<int> genericArgumentCounts = null;
+            Type[]? genericArguments = null;
+            IList<int>? genericArgumentCounts = null;
             if (clrType.IsGenericType)
             {
                 genericArguments = clrType.GetGenericArguments();
@@ -306,6 +307,7 @@ namespace System.Runtime.Serialization
             {
                 int argIndex = 0;
                 int nestedLevel = 0;
+                Debug.Assert(genericArgumentCounts != null);
                 foreach (int genericArgumentCount in genericArgumentCounts)
                 {
                     for (int i = 0; i < genericArgumentCount; i++, argIndex++)
@@ -332,7 +334,7 @@ namespace System.Runtime.Serialization
             return typeElement;
         }
 
-        private XmlElement ExportSurrogateData(object key)
+        private XmlElement? ExportSurrogateData(object key)
         {
             // IDataContractSurrogate is not available on NetCore.
             return null;
@@ -343,7 +345,7 @@ namespace System.Runtime.Serialization
             XmlSchemaComplexType type = new XmlSchemaComplexType();
             type.Name = collectionDataContract.StableName.Name;
             schema.Items.Add(type);
-            XmlElement genericInfoElement = null, isDictionaryElement = null;
+            XmlElement? genericInfoElement = null, isDictionaryElement = null;
             if (collectionDataContract.UnderlyingType.IsGenericType && CollectionDataContract.IsCollectionDataContract(collectionDataContract.UnderlyingType))
                 genericInfoElement = ExportGenericInfo(collectionDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace);
             if (collectionDataContract.IsDictionary)
@@ -358,10 +360,10 @@ namespace System.Runtime.Serialization
             element.MaxOccursString = Globals.OccursUnbounded;
             if (collectionDataContract.IsDictionary)
             {
-                ClassDataContract keyValueContract = collectionDataContract.ItemContract as ClassDataContract;
+                ClassDataContract keyValueContract = (collectionDataContract.ItemContract as ClassDataContract)!;
                 XmlSchemaComplexType keyValueType = new XmlSchemaComplexType();
                 XmlSchemaSequence keyValueSequence = new XmlSchemaSequence();
-                foreach (DataMember dataMember in keyValueContract.Members)
+                foreach (DataMember dataMember in keyValueContract.Members!)
                 {
                     XmlSchemaElement keyValueElement = new XmlSchemaElement();
                     keyValueElement.Name = dataMember.Name;
@@ -402,7 +404,9 @@ namespace System.Runtime.Serialization
         {
             XmlSchemaSimpleType type = new XmlSchemaSimpleType();
             type.Name = enumDataContract.StableName.Name;
-            XmlElement actualTypeElement = (enumDataContract.BaseContractName == DefaultEnumBaseTypeName) ? null : ExportActualType(enumDataContract.BaseContractName);
+            // https://github.com/dotnet/runtime/issues/41448 - enumDataContract.BaseContractName is always null, but this method is not reachable
+            Debug.Assert(enumDataContract.BaseContractName != null, "BaseContractName is always null, but this method is not reachable. Suppressing compiler error.");
+            XmlElement? actualTypeElement = (enumDataContract.BaseContractName == DefaultEnumBaseTypeName) ? null : ExportActualType(enumDataContract.BaseContractName);
             type.Annotation = GetSchemaAnnotation(actualTypeElement, ExportSurrogateData(enumDataContract));
             schema.Items.Add(type);
 
@@ -442,11 +446,11 @@ namespace System.Runtime.Serialization
             XmlSchemaComplexType type = new XmlSchemaComplexType();
             type.Name = dataContract.StableName.Name;
             schema.Items.Add(type);
-            XmlElement genericInfoElement = null;
+            XmlElement? genericInfoElement = null;
             if (dataContract.UnderlyingType.IsGenericType)
                 genericInfoElement = ExportGenericInfo(dataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace);
 
-            XmlElement isValueTypeElement = null;
+            XmlElement? isValueTypeElement = null;
             if (dataContract.BaseContract != null)
             {
                 _ = CreateTypeContent(type, dataContract.BaseContract.StableName, schema);
@@ -478,9 +482,9 @@ namespace System.Runtime.Serialization
 
         private void ExportXmlDataContract(XmlDataContract dataContract)
         {
-            XmlQualifiedName typeQName;
+            XmlQualifiedName? typeQName;
             bool hasRoot;
-            XmlSchemaType xsdType;
+            XmlSchemaType? xsdType;
 
             Type clrType = dataContract.UnderlyingType;
             if (!IsSpecialXmlType(clrType, out typeQName, out xsdType, out hasRoot))
@@ -494,9 +498,9 @@ namespace System.Runtime.Serialization
                     Fx.Assert("XML data contract type name does not match schema name");
                 }
 
-                XmlSchema schema;
+                XmlSchema? schema;
                 if (SchemaHelper.GetSchemaElement(Schemas,
-                    new XmlQualifiedName(dataContract.TopLevelElementName.Value, dataContract.TopLevelElementNamespace.Value),
+                    new XmlQualifiedName(dataContract.TopLevelElementName!.Value, dataContract.TopLevelElementNamespace!.Value),
                     out schema) == null)
                 {
                     XmlSchemaElement topLevelElement = ExportTopLevelElement(dataContract, schema);
@@ -504,7 +508,7 @@ namespace System.Runtime.Serialization
                     ReprocessAll(_schemas);
                 }
 
-                XmlSchemaType anonymousType = xsdType;
+                XmlSchemaType? anonymousType = xsdType;
                 xsdType = SchemaHelper.GetSchemaType(_schemas, typeQName, out schema);
                 if (anonymousType == null && xsdType == null && typeQName.Namespace != XmlSchema.Namespace)
                 {
@@ -515,7 +519,7 @@ namespace System.Runtime.Serialization
                     xsdType.Annotation = GetSchemaAnnotation(
                                            ExportSurrogateData(dataContract),
                                            dataContract.IsValueType ?
-                                             GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(dataContract.IsValueType), schema) :
+                                             GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(dataContract.IsValueType), schema!) :
                                              null
                                          );
                 }
@@ -550,7 +554,7 @@ namespace System.Runtime.Serialization
                     }
                     else
                         continue;
-                    object otherItem = items[qname];
+                    object? otherItem = items[qname];
                     if (otherItem != null)
                     {
                         schema.Items.Remove(item);
@@ -562,9 +566,9 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot)
+        internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName stableName, out XmlSchemaType? xsdType, out bool hasRoot)
         {
-            if (IsSpecialXmlType(type, out stableName, out xsdType, out hasRoot))
+            if (IsSpecialXmlType(type, out stableName!, out xsdType, out hasRoot))
                 return;
             XmlSchemaSet schemas = new XmlSchemaSet();
             schemas.XmlResolver = null;
@@ -573,7 +577,7 @@ namespace System.Runtime.Serialization
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidXmlDataContractName, DataContract.GetClrTypeFullName(type))));
         }
 
-        private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schemas, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot)
+        private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schemas, out XmlQualifiedName stableName, out XmlSchemaType? xsdType, out bool hasRoot)
         {
             xsdType = null;
             hasRoot = true;
@@ -590,7 +594,7 @@ namespace System.Runtime.Serialization
                 xsdType = CreateAnyElementType();
                 hasRoot = false;
             }
-            string methodName = provider.MethodName;
+            string? methodName = provider.MethodName;
             if (methodName == null || methodName.Length == 0)
             {
                 if (!provider.IsAny)
@@ -599,14 +603,14 @@ namespace System.Runtime.Serialization
             }
             else
             {
-                MethodInfo getMethod = clrType.GetMethod(methodName,  /*BindingFlags.DeclaredOnly |*/ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[] { typeof(XmlSchemaSet) }, null);
+                MethodInfo? getMethod = clrType.GetMethod(methodName,  /*BindingFlags.DeclaredOnly |*/ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[] { typeof(XmlSchemaSet) }, null);
                 if (getMethod == null)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName)));
 
                 if (!(Globals.TypeOfXmlQualifiedName.IsAssignableFrom(getMethod.ReturnType)) && !(Globals.TypeOfXmlSchemaType.IsAssignableFrom(getMethod.ReturnType)))
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidReturnTypeOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName, DataContract.GetClrTypeFullName(getMethod.ReturnType), DataContract.GetClrTypeFullName(Globals.TypeOfXmlQualifiedName), typeof(XmlSchemaType))));
 
-                object typeInfo = getMethod.Invoke(null, new object[] { schemas });
+                object? typeInfo = getMethod.Invoke(null, new object[] { schemas });
 
                 if (provider.IsAny)
                 {
@@ -622,11 +626,11 @@ namespace System.Runtime.Serialization
                 }
                 else
                 {
-                    XmlSchemaType providerXsdType = typeInfo as XmlSchemaType;
+                    XmlSchemaType? providerXsdType = typeInfo as XmlSchemaType;
                     if (providerXsdType != null)
                     {
-                        string typeName = providerXsdType.Name;
-                        string typeNs = null;
+                        string? typeName = providerXsdType.Name;
+                        string? typeNs = null;
                         if (typeName == null || typeName.Length == 0)
                         {
                             DataContract.GetDefaultStableName(DataContract.GetClrTypeFullName(clrType), out typeName, out typeNs);
@@ -665,8 +669,8 @@ namespace System.Runtime.Serialization
 
         private static void InvokeGetSchemaMethod(Type clrType, XmlSchemaSet schemas, XmlQualifiedName stableName)
         {
-            IXmlSerializable ixmlSerializable = (IXmlSerializable)Activator.CreateInstance(clrType);
-            XmlSchema schema = ixmlSerializable.GetSchema();
+            IXmlSerializable ixmlSerializable = (IXmlSerializable)Activator.CreateInstance(clrType)!;
+            XmlSchema? schema = ixmlSerializable.GetSchema();
             if (schema == null)
             {
                 AddDefaultDatasetType(schemas, stableName.Name, stableName.Namespace);
@@ -714,13 +718,13 @@ namespace System.Runtime.Serialization
             return anyElementType;
         }
 
-        internal static bool IsSpecialXmlType(Type type, out XmlQualifiedName typeName, out XmlSchemaType xsdType, out bool hasRoot)
+        internal static bool IsSpecialXmlType(Type type, [NotNullWhen(true)] out XmlQualifiedName? typeName, [NotNullWhen(true)] out XmlSchemaType? xsdType, out bool hasRoot)
         {
             xsdType = null;
             hasRoot = true;
             if (type == Globals.TypeOfXmlElement || type == Globals.TypeOfXmlNodeArray)
             {
-                string name = null;
+                string? name = null;
                 if (type == Globals.TypeOfXmlElement)
                 {
                     xsdType = CreateAnyElementType();
@@ -780,7 +784,7 @@ namespace System.Runtime.Serialization
             return annotation;
         }
 
-        private static XmlSchemaAnnotation GetSchemaAnnotation(params XmlNode[] nodes)
+        private static XmlSchemaAnnotation? GetSchemaAnnotation(params XmlNode?[]? nodes)
         {
             if (nodes == null || nodes.Length == 0)
                 return null;
@@ -841,7 +845,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static XmlQualifiedName s_anytypeQualifiedName;
+        private static XmlQualifiedName? s_anytypeQualifiedName;
         internal static XmlQualifiedName AnytypeQualifiedName
         {
             get
@@ -852,7 +856,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static XmlQualifiedName s_stringQualifiedName;
+        private static XmlQualifiedName? s_stringQualifiedName;
         internal static XmlQualifiedName StringQualifiedName
         {
             get
@@ -863,7 +867,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static XmlQualifiedName s_defaultEnumBaseTypeName;
+        private static XmlQualifiedName? s_defaultEnumBaseTypeName;
         internal static XmlQualifiedName DefaultEnumBaseTypeName
         {
             get
@@ -874,7 +878,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static XmlQualifiedName s_enumerationValueAnnotationName;
+        private static XmlQualifiedName? s_enumerationValueAnnotationName;
         internal static XmlQualifiedName EnumerationValueAnnotationName
         {
             get
@@ -885,7 +889,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static XmlQualifiedName s_surrogateDataAnnotationName;
+        private static XmlQualifiedName? s_surrogateDataAnnotationName;
         internal static XmlQualifiedName SurrogateDataAnnotationName
         {
             get
@@ -896,7 +900,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static XmlQualifiedName s_defaultValueAnnotation;
+        private static XmlQualifiedName? s_defaultValueAnnotation;
         internal static XmlQualifiedName DefaultValueAnnotation
         {
             get
@@ -907,7 +911,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static XmlQualifiedName s_actualTypeAnnotationName;
+        private static XmlQualifiedName? s_actualTypeAnnotationName;
         internal static XmlQualifiedName ActualTypeAnnotationName
         {
             get
@@ -918,7 +922,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static XmlQualifiedName s_isDictionaryAnnotationName;
+        private static XmlQualifiedName? s_isDictionaryAnnotationName;
         internal static XmlQualifiedName IsDictionaryAnnotationName
         {
             get
@@ -929,7 +933,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static XmlQualifiedName s_isValueTypeName;
+        private static XmlQualifiedName? s_isValueTypeName;
         internal static XmlQualifiedName IsValueTypeName
         {
             get
index abc9643..8a07b0e 100644 (file)
@@ -12,7 +12,7 @@ namespace System.Runtime.Serialization
     internal static class SchemaHelper
     {
 
-        internal static bool NamespacesEqual(string ns1, string ns2)
+        internal static bool NamespacesEqual(string? ns1, string? ns2)
         {
             if (ns1 == null || ns1.Length == 0)
                 return (ns2 == null || ns2.Length == 0);
@@ -20,7 +20,7 @@ namespace System.Runtime.Serialization
                 return ns1 == ns2;
         }
 
-        internal static XmlSchemaType GetSchemaType(XmlSchemaSet schemas, XmlQualifiedName typeQName, out XmlSchema outSchema)
+        internal static XmlSchemaType? GetSchemaType(XmlSchemaSet schemas, XmlQualifiedName typeQName, out XmlSchema? outSchema)
         {
             outSchema = null;
             ICollection currentSchemas = schemas.Schemas();
@@ -32,7 +32,7 @@ namespace System.Runtime.Serialization
                     outSchema = schema;
                     foreach (XmlSchemaObject schemaObj in schema.Items)
                     {
-                        XmlSchemaType schemaType = schemaObj as XmlSchemaType;
+                        XmlSchemaType? schemaType = schemaObj as XmlSchemaType;
                         if (schemaType != null && schemaType.Name == typeQName.Name)
                         {
                             return schemaType;
@@ -43,7 +43,7 @@ namespace System.Runtime.Serialization
             return null;
         }
 
-        internal static XmlSchemaElement GetSchemaElement(XmlSchemaSet schemas, XmlQualifiedName elementQName, out XmlSchema outSchema)
+        internal static XmlSchemaElement? GetSchemaElement(XmlSchemaSet schemas, XmlQualifiedName elementQName, out XmlSchema? outSchema)
         {
             outSchema = null;
             ICollection currentSchemas = schemas.Schemas();
@@ -55,7 +55,7 @@ namespace System.Runtime.Serialization
                     outSchema = schema;
                     foreach (XmlSchemaObject schemaObj in schema.Items)
                     {
-                        XmlSchemaElement schemaElement = schemaObj as XmlSchemaElement;
+                        XmlSchemaElement? schemaElement = schemaObj as XmlSchemaElement;
                         if (schemaElement != null && schemaElement.Name == elementQName.Name)
                         {
                             return schemaElement;
index dee1799..e9414b2 100644 (file)
@@ -25,12 +25,12 @@ namespace System.Runtime.Serialization
             _count--;
         }
 
-        internal DataContract GetDataContract(XmlQualifiedName qname)
+        internal DataContract? GetDataContract(XmlQualifiedName qname)
         {
             for (int i = (_count - 1); i >= 0; i--)
             {
                 DataContractDictionary dataContractDictionary = dataContractDictionaries[i];
-                DataContract dataContract;
+                DataContract? dataContract;
                 if (dataContractDictionary.TryGetValue(qname, out dataContract))
                     return dataContract;
             }
index 34816e2..2db1622 100644 (file)
@@ -11,7 +11,7 @@ namespace System.Runtime.Serialization
 
         public SpecialTypeDataContract(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(new SpecialTypeDataContractCriticalHelper(type, name, ns))
         {
-            _helper = base.Helper as SpecialTypeDataContractCriticalHelper;
+            _helper = (base.Helper as SpecialTypeDataContractCriticalHelper)!;
         }
 
         public override bool IsBuiltInDataContract => true;
index 354a1d0..ebf41ee 100644 (file)
@@ -6,6 +6,7 @@ namespace System.Runtime.Serialization
     using System;
     using System.Security;
     using System.Runtime.CompilerServices;
+    using System.Diagnostics;
 
     internal sealed class SurrogateDataContract : DataContract
     {
@@ -14,7 +15,7 @@ namespace System.Runtime.Serialization
         internal SurrogateDataContract(Type type, ISerializationSurrogate serializationSurrogate)
             : base(new SurrogateDataContractCriticalHelper(type, serializationSurrogate))
         {
-            _helper = base.Helper as SurrogateDataContractCriticalHelper;
+            _helper = (base.Helper as SurrogateDataContractCriticalHelper)!;
         }
 
         internal ISerializationSurrogate SerializationSurrogate
@@ -22,21 +23,23 @@ namespace System.Runtime.Serialization
             get { return _helper.SerializationSurrogate; }
         }
 
-        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context)
         {
+            Debug.Assert(context != null);
+
             SerializationInfo serInfo = new SerializationInfo(UnderlyingType, XmlObjectSerializer.FormatterConverter, !context.UnsafeTypeForwardingEnabled);
             SerializationSurrogateGetObjectData(obj, serInfo, context.GetStreamingContext());
             context.WriteSerializationInfo(xmlWriter, UnderlyingType, serInfo);
         }
 
         [MethodImpl(MethodImplOptions.NoInlining)]
-        private object SerializationSurrogateSetObjectData(object obj, SerializationInfo serInfo, StreamingContext context)
+        private object? SerializationSurrogateSetObjectData(object obj, SerializationInfo serInfo, StreamingContext context)
         {
             return SerializationSurrogate.SetObjectData(obj, serInfo, context, null);
         }
 
         [MethodImpl(MethodImplOptions.NoInlining)]
-        internal static object GetRealObject(IObjectReference obj, StreamingContext context)
+        internal static object? GetRealObject(IObjectReference obj, StreamingContext context)
         {
             return obj.GetRealObject(context);
         }
@@ -53,15 +56,17 @@ namespace System.Runtime.Serialization
             SerializationSurrogate.GetObjectData(obj, serInfo, context);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context)
         {
+            Debug.Assert(context != null);
+
             xmlReader.Read();
             Type objType = UnderlyingType;
-            object obj = objType.IsArray ? Array.CreateInstance(objType.GetElementType(), 0) : GetUninitializedObject(objType);
+            object obj = objType.IsArray ? Array.CreateInstance(objType.GetElementType()!, 0) : GetUninitializedObject(objType);
             context.AddNewObject(obj);
             string objectId = context.GetObjectId();
             SerializationInfo serInfo = context.ReadSerializationInfo(xmlReader, objType);
-            object newObj = SerializationSurrogateSetObjectData(obj, serInfo, context.GetStreamingContext());
+            object? newObj = SerializationSurrogateSetObjectData(obj, serInfo, context.GetStreamingContext());
             if (newObj == null)
                 newObj = obj;
             if (newObj is IDeserializationCallback)
index 3422aad..7c0a0a9 100644 (file)
@@ -23,7 +23,7 @@ namespace System.Runtime.Serialization
         }
 
         // Here you can provide your own root element Xpath which will replace the Xpath of the top level element
-        public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pathToMember, StringBuilder rootElementXpath, out XmlNamespaceManager namespaces)
+        public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pathToMember, StringBuilder? rootElementXpath, out XmlNamespaceManager namespaces)
         {
             if (type == null)
             {
@@ -67,10 +67,10 @@ namespace System.Runtime.Serialization
 
         private static DataContract ProcessClassDataContract(ClassDataContract contract, ExportContext context, MemberInfo memberNode)
         {
-            string prefix = context.SetNamespace(contract.Namespace.Value);
+            string prefix = context.SetNamespace(contract.Namespace!.Value);
             foreach (DataMember member in GetDataMembers(contract))
             {
-                if (member.MemberInfo.Name == memberNode.Name && member.MemberInfo.DeclaringType.IsAssignableFrom(memberNode.DeclaringType))
+                if (member.MemberInfo.Name == memberNode.Name && member.MemberInfo.DeclaringType!.IsAssignableFrom(memberNode.DeclaringType))
                 {
                     context.WriteChildToContext(member, prefix);
                     return member.MemberTypeContract;
@@ -106,8 +106,8 @@ namespace System.Runtime.Serialization
             public ExportContext(DataContract rootContract)
             {
                 _namespaces = new XmlNamespaceManager(new NameTable());
-                string prefix = SetNamespace(rootContract.TopLevelElementNamespace.Value);
-                _xPathBuilder = new StringBuilder(XPathQueryGenerator.XPathSeparator + prefix + XPathQueryGenerator.NsSeparator + rootContract.TopLevelElementName.Value);
+                string prefix = SetNamespace(rootContract.TopLevelElementNamespace!.Value);
+                _xPathBuilder = new StringBuilder(XPathQueryGenerator.XPathSeparator + prefix + XPathQueryGenerator.NsSeparator + rootContract.TopLevelElementName!.Value);
             }
 
             public ExportContext(StringBuilder rootContractXPath)
@@ -139,7 +139,7 @@ namespace System.Runtime.Serialization
 
             public string SetNamespace(string ns)
             {
-                string prefix = _namespaces.LookupPrefix(ns);
+                string? prefix = _namespaces.LookupPrefix(ns);
                 if (prefix == null || prefix.Length == 0)
                 {
                     prefix = "xg" + (_nextPrefix++).ToString(NumberFormatInfo.InvariantInfo);
index e18a8db..62a1b8b 100644 (file)
@@ -20,17 +20,12 @@ namespace System.Runtime.Serialization
     {
         private readonly XmlDataContractCriticalHelper _helper;
 
-        public XmlDataContract() : base(new XmlDataContractCriticalHelper())
-        {
-            _helper = base.Helper as XmlDataContractCriticalHelper;
-        }
-
         internal XmlDataContract(Type type) : base(new XmlDataContractCriticalHelper(type))
         {
-            _helper = base.Helper as XmlDataContractCriticalHelper;
+            _helper = (base.Helper as XmlDataContractCriticalHelper)!;
         }
 
-        public override DataContractDictionary KnownDataContracts
+        public override DataContractDictionary? KnownDataContracts
         {
             get
             { return _helper.KnownDataContracts; }
@@ -39,7 +34,7 @@ namespace System.Runtime.Serialization
             { _helper.KnownDataContracts = value; }
         }
 
-        internal XmlSchemaType XsdType
+        internal XmlSchemaType? XsdType
         {
             get { return _helper.XsdType; }
             set { _helper.XsdType = value; }
@@ -61,7 +56,7 @@ namespace System.Runtime.Serialization
             { _helper.HasRoot = value; }
         }
 
-        public override XmlDictionaryString TopLevelElementName
+        public override XmlDictionaryString? TopLevelElementName
         {
             get
             { return _helper.TopLevelElementName; }
@@ -70,7 +65,7 @@ namespace System.Runtime.Serialization
             { _helper.TopLevelElementName = value; }
         }
 
-        public override XmlDictionaryString TopLevelElementNamespace
+        public override XmlDictionaryString? TopLevelElementNamespace
         {
             get
             { return _helper.TopLevelElementNamespace; }
@@ -118,18 +113,14 @@ namespace System.Runtime.Serialization
 
         private class XmlDataContractCriticalHelper : DataContract.DataContractCriticalHelper
         {
-            private DataContractDictionary _knownDataContracts;
+            private DataContractDictionary? _knownDataContracts;
             private bool _isKnownTypeAttributeChecked;
-            private XmlDictionaryString _topLevelElementName;
-            private XmlDictionaryString _topLevelElementNamespace;
+            private XmlDictionaryString? _topLevelElementName;
+            private XmlDictionaryString? _topLevelElementNamespace;
             private bool _isTopLevelElementNullable;
             private bool _hasRoot;
-            private CreateXmlSerializableDelegate _createXmlSerializable;
-            private XmlSchemaType _xsdType;
-
-            internal XmlDataContractCriticalHelper()
-            {
-            }
+            private CreateXmlSerializableDelegate? _createXmlSerializable;
+            private XmlSchemaType? _xsdType;
 
             internal XmlDataContractCriticalHelper(Type type) : base(type)
             {
@@ -137,7 +128,7 @@ namespace System.Runtime.Serialization
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type))));
                 if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type))));
-                XmlSchemaType xsdType;
+                XmlSchemaType? xsdType;
                 bool hasRoot;
                 XmlQualifiedName stableName;
                 SchemaExporter.GetXmlTypeInfo(type, out stableName, out xsdType, out hasRoot);
@@ -146,7 +137,7 @@ namespace System.Runtime.Serialization
                 XmlDictionary dictionary = new XmlDictionary();
                 this.Name = dictionary.Add(StableName.Name);
                 this.Namespace = dictionary.Add(StableName.Namespace);
-                object[] xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray();
+                object[]? xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray();
                 if (xmlRootAttributes == null || xmlRootAttributes.Length == 0)
                 {
                     if (hasRoot)
@@ -164,17 +155,17 @@ namespace System.Runtime.Serialization
                         _isTopLevelElementNullable = xmlRootAttribute.IsNullable;
                         string elementName = xmlRootAttribute.ElementName;
                         _topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName));
-                        string elementNs = xmlRootAttribute.Namespace;
+                        string? elementNs = xmlRootAttribute.Namespace;
                         _topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs);
                     }
                     else
                     {
-                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType))));
+                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType!))));
                     }
                 }
             }
 
-            internal override DataContractDictionary KnownDataContracts
+            internal override DataContractDictionary? KnownDataContracts
             {
                 get
                 {
@@ -197,7 +188,7 @@ namespace System.Runtime.Serialization
                 { _knownDataContracts = value; }
             }
 
-            internal XmlSchemaType XsdType
+            internal XmlSchemaType? XsdType
             {
                 get { return _xsdType; }
                 set { _xsdType = value; }
@@ -214,7 +205,7 @@ namespace System.Runtime.Serialization
                 { _hasRoot = value; }
             }
 
-            internal override XmlDictionaryString TopLevelElementName
+            internal override XmlDictionaryString? TopLevelElementName
             {
                 get
                 { return _topLevelElementName; }
@@ -222,7 +213,7 @@ namespace System.Runtime.Serialization
                 { _topLevelElementName = value; }
             }
 
-            internal override XmlDictionaryString TopLevelElementNamespace
+            internal override XmlDictionaryString? TopLevelElementNamespace
             {
                 get
                 { return _topLevelElementNamespace; }
@@ -236,21 +227,21 @@ namespace System.Runtime.Serialization
                 set { _isTopLevelElementNullable = value; }
             }
 
-            internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate
+            internal CreateXmlSerializableDelegate? CreateXmlSerializableDelegate
             {
                 get { return _createXmlSerializable; }
                 set { _createXmlSerializable = value; }
             }
         }
 
-        private ConstructorInfo GetConstructor()
+        private ConstructorInfo? GetConstructor()
         {
             Type type = UnderlyingType;
 
             if (type.IsValueType)
                 return null;
 
-            ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>());
+            ConstructorInfo? ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>());
             if (ctor == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type))));
 
@@ -288,18 +279,18 @@ namespace System.Runtime.Serialization
             {
                 // Special case XElement
                 // codegen the same as 'internal XElement : this("default") { }'
-                ConstructorInfo ctor = GetConstructor();
+                ConstructorInfo ctor = GetConstructor()!;
                 if (!ctor.IsPublic && type.FullName == "System.Xml.Linq.XElement")
                 {
-                    Type xName = type.Assembly.GetType("System.Xml.Linq.XName");
+                    Type? xName = type.Assembly.GetType("System.Xml.Linq.XName");
                     if (xName != null)
                     {
-                        MethodInfo XName_op_Implicit = xName.GetMethod(
+                        MethodInfo? XName_op_Implicit = xName.GetMethod(
                             "op_Implicit",
                             BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public,
                             new Type[] { typeof(string) }
                             );
-                        ConstructorInfo XElement_ctor = type.GetConstructor(
+                        ConstructorInfo? XElement_ctor = type.GetConstructor(
                             BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
                             new Type[] { xName }
                             );
@@ -323,7 +314,7 @@ namespace System.Runtime.Serialization
         ///          since this information is used to determine whether to give the generated code access
         ///          permissions to private members, any changes to the logic should be reviewed.
         /// </SecurityNote>
-        private bool RequiresMemberAccessForCreate(SecurityException securityException)
+        private bool RequiresMemberAccessForCreate(SecurityException? securityException)
         {
             if (!IsTypeVisible(UnderlyingType))
             {
@@ -358,14 +349,14 @@ namespace System.Runtime.Serialization
             }
             else
             {
-                object o = null;
+                object? o = null;
                 if (type == typeof(System.Xml.Linq.XElement))
                 {
-                    o = new System.Xml.Linq.XElement("default");
+                    o = new System.Xml.Linq.XElement("default"!); // TODO-NULLABLE - https://github.com/dotnet/roslyn/issues/39802
                 }
                 else
                 {
-                    ConstructorInfo ctor = GetConstructor();
+                    ConstructorInfo ctor = GetConstructor()!;
                     o = ctor.Invoke(Array.Empty<object>());
                 }
 
@@ -373,7 +364,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
+        public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context)
         {
             if (context == null)
                 XmlObjectSerializerWriteContext.WriteRootIXmlSerializable(xmlWriter, obj);
@@ -381,9 +372,9 @@ namespace System.Runtime.Serialization
                 context.WriteIXmlSerializable(xmlWriter, obj);
         }
 
-        public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
+        public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context)
         {
-            object o;
+            object? o;
             if (context == null)
             {
                 o = XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, this, true /*isMemberType*/);
index ffac56c..fa9a69f 100644 (file)
@@ -10,7 +10,7 @@ namespace System.Runtime.Serialization
 {
     internal static class XmlFormatGeneratorStatics
     {
-        private static MethodInfo s_writeStartElementMethod2;
+        private static MethodInfo? s_writeStartElementMethod2;
         internal static MethodInfo WriteStartElementMethod2
         {
             get
@@ -24,7 +24,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_writeStartElementMethod3;
+        private static MethodInfo? s_writeStartElementMethod3;
         internal static MethodInfo WriteStartElementMethod3
         {
             get
@@ -38,7 +38,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_writeEndElementMethod;
+        private static MethodInfo? s_writeEndElementMethod;
         internal static MethodInfo WriteEndElementMethod
         {
             get
@@ -52,7 +52,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_writeNamespaceDeclMethod;
+        private static MethodInfo? s_writeNamespaceDeclMethod;
         internal static MethodInfo WriteNamespaceDeclMethod
         {
             get
@@ -66,22 +66,25 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static PropertyInfo s_extensionDataProperty;
+        private static PropertyInfo? s_extensionDataProperty;
         internal static PropertyInfo ExtensionDataProperty => s_extensionDataProperty ??
-                                                              (s_extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData"));
+                                                              (s_extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData")!);
 
-        private static ConstructorInfo s_dictionaryEnumeratorCtor;
+        private static ConstructorInfo? s_dictionaryEnumeratorCtor;
         internal static ConstructorInfo DictionaryEnumeratorCtor
         {
             get
             {
                 if (s_dictionaryEnumeratorCtor == null)
+                {
                     s_dictionaryEnumeratorCtor = Globals.TypeOfDictionaryEnumerator.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator });
+                    Debug.Assert(s_dictionaryEnumeratorCtor != null);
+                }
                 return s_dictionaryEnumeratorCtor;
             }
         }
 
-        private static MethodInfo s_ienumeratorMoveNextMethod;
+        private static MethodInfo? s_ienumeratorMoveNextMethod;
         internal static MethodInfo MoveNextMethod
         {
             get
@@ -95,35 +98,35 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_ienumeratorGetCurrentMethod;
+        private static MethodInfo? s_ienumeratorGetCurrentMethod;
         internal static MethodInfo GetCurrentMethod
         {
             get
             {
                 if (s_ienumeratorGetCurrentMethod == null)
                 {
-                    s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current").GetGetMethod();
+                    s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current")!.GetGetMethod();
                     Debug.Assert(s_ienumeratorGetCurrentMethod != null);
                 }
                 return s_ienumeratorGetCurrentMethod;
             }
         }
 
-        private static MethodInfo s_getItemContractMethod;
+        private static MethodInfo? s_getItemContractMethod;
         internal static MethodInfo GetItemContractMethod
         {
             get
             {
                 if (s_getItemContractMethod == null)
                 {
-                    s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers).GetMethod;
+                    s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers)!.GetMethod;
                     Debug.Assert(s_getItemContractMethod != null);
                 }
                 return s_getItemContractMethod;
             }
         }
 
-        private static MethodInfo s_isStartElementMethod2;
+        private static MethodInfo? s_isStartElementMethod2;
         internal static MethodInfo IsStartElementMethod2
         {
             get
@@ -137,7 +140,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_isStartElementMethod0;
+        private static MethodInfo? s_isStartElementMethod0;
         internal static MethodInfo IsStartElementMethod0
         {
             get
@@ -151,7 +154,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getUninitializedObjectMethod;
+        private static MethodInfo? s_getUninitializedObjectMethod;
         internal static MethodInfo GetUninitializedObjectMethod
         {
             get
@@ -165,18 +168,21 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_onDeserializationMethod;
+        private static MethodInfo? s_onDeserializationMethod;
         internal static MethodInfo OnDeserializationMethod
         {
             get
             {
                 if (s_onDeserializationMethod == null)
+                {
                     s_onDeserializationMethod = typeof(IDeserializationCallback).GetMethod("OnDeserialization");
+                    Debug.Assert(s_onDeserializationMethod != null);
+                }
                 return s_onDeserializationMethod;
             }
         }
 
-        private static PropertyInfo s_nodeTypeProperty;
+        private static PropertyInfo? s_nodeTypeProperty;
         internal static PropertyInfo NodeTypeProperty
         {
             get
@@ -190,23 +196,26 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static ConstructorInfo s_extensionDataObjectCtor;
+        private static ConstructorInfo? s_extensionDataObjectCtor;
         internal static ConstructorInfo ExtensionDataObjectCtor => s_extensionDataObjectCtor ??
                                                                    (s_extensionDataObjectCtor =
-                                                                       typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, null, Array.Empty<Type>(), null));
+                                                                       typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, null, Array.Empty<Type>(), null)!);
 
-        private static ConstructorInfo s_hashtableCtor;
+        private static ConstructorInfo? s_hashtableCtor;
         internal static ConstructorInfo HashtableCtor
         {
             get
             {
                 if (s_hashtableCtor == null)
+                {
                     s_hashtableCtor = Globals.TypeOfHashtable.GetConstructor(Globals.ScanAllMembers, Array.Empty<Type>());
+                    Debug.Assert(s_hashtableCtor != null);
+                }
                 return s_hashtableCtor;
             }
         }
 
-        private static MethodInfo s_getStreamingContextMethod;
+        private static MethodInfo? s_getStreamingContextMethod;
         internal static MethodInfo GetStreamingContextMethod
         {
             get
@@ -220,7 +229,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getCollectionMemberMethod;
+        private static MethodInfo? s_getCollectionMemberMethod;
         internal static MethodInfo GetCollectionMemberMethod
         {
             get
@@ -234,7 +243,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_storeCollectionMemberInfoMethod;
+        private static MethodInfo? s_storeCollectionMemberInfoMethod;
         internal static MethodInfo StoreCollectionMemberInfoMethod
         {
             get
@@ -248,7 +257,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_resetCollectionMemberInfoMethod;
+        private static MethodInfo? s_resetCollectionMemberInfoMethod;
         internal static MethodInfo ResetCollectionMemberInfoMethod
         {
             get
@@ -262,7 +271,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_storeIsGetOnlyCollectionMethod;
+        private static MethodInfo? s_storeIsGetOnlyCollectionMethod;
         internal static MethodInfo StoreIsGetOnlyCollectionMethod
         {
             get
@@ -276,7 +285,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_resetIsGetOnlyCollection;
+        private static MethodInfo? s_resetIsGetOnlyCollection;
         internal static MethodInfo ResetIsGetOnlyCollectionMethod
         {
             get
@@ -290,7 +299,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod;
+        private static MethodInfo? s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod;
         internal static MethodInfo ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod
         {
             get
@@ -304,7 +313,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_throwArrayExceededSizeExceptionMethod;
+        private static MethodInfo? s_throwArrayExceededSizeExceptionMethod;
         internal static MethodInfo ThrowArrayExceededSizeExceptionMethod
         {
             get
@@ -318,7 +327,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_incrementItemCountMethod;
+        private static MethodInfo? s_incrementItemCountMethod;
         internal static MethodInfo IncrementItemCountMethod
         {
             get
@@ -332,7 +341,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_internalDeserializeMethod;
+        private static MethodInfo? s_internalDeserializeMethod;
         internal static MethodInfo InternalDeserializeMethod
         {
             get
@@ -346,7 +355,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_moveToNextElementMethod;
+        private static MethodInfo? s_moveToNextElementMethod;
         internal static MethodInfo MoveToNextElementMethod
         {
             get
@@ -360,7 +369,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getMemberIndexMethod;
+        private static MethodInfo? s_getMemberIndexMethod;
         internal static MethodInfo GetMemberIndexMethod
         {
             get
@@ -374,7 +383,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getMemberIndexWithRequiredMembersMethod;
+        private static MethodInfo? s_getMemberIndexWithRequiredMembersMethod;
         internal static MethodInfo GetMemberIndexWithRequiredMembersMethod
         {
             get
@@ -388,7 +397,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_throwRequiredMemberMissingExceptionMethod;
+        private static MethodInfo? s_throwRequiredMemberMissingExceptionMethod;
         internal static MethodInfo ThrowRequiredMemberMissingExceptionMethod
         {
             get
@@ -402,7 +411,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_skipUnknownElementMethod;
+        private static MethodInfo? s_skipUnknownElementMethod;
         internal static MethodInfo SkipUnknownElementMethod
         {
             get
@@ -416,7 +425,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_readIfNullOrRefMethod;
+        private static MethodInfo? s_readIfNullOrRefMethod;
         internal static MethodInfo ReadIfNullOrRefMethod
         {
             get
@@ -430,7 +439,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_readAttributesMethod;
+        private static MethodInfo? s_readAttributesMethod;
         internal static MethodInfo ReadAttributesMethod
         {
             get
@@ -444,7 +453,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_resetAttributesMethod;
+        private static MethodInfo? s_resetAttributesMethod;
         internal static MethodInfo ResetAttributesMethod
         {
             get
@@ -458,7 +467,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getObjectIdMethod;
+        private static MethodInfo? s_getObjectIdMethod;
         internal static MethodInfo GetObjectIdMethod
         {
             get
@@ -472,7 +481,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getArraySizeMethod;
+        private static MethodInfo? s_getArraySizeMethod;
         internal static MethodInfo GetArraySizeMethod
         {
             get
@@ -486,7 +495,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_addNewObjectMethod;
+        private static MethodInfo? s_addNewObjectMethod;
         internal static MethodInfo AddNewObjectMethod
         {
             get
@@ -500,7 +509,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_addNewObjectWithIdMethod;
+        private static MethodInfo? s_addNewObjectWithIdMethod;
         internal static MethodInfo AddNewObjectWithIdMethod
         {
             get
@@ -514,7 +523,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getExistingObjectMethod;
+        private static MethodInfo? s_getExistingObjectMethod;
         internal static MethodInfo GetExistingObjectMethod
         {
             get
@@ -528,18 +537,21 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getRealObjectMethod;
+        private static MethodInfo? s_getRealObjectMethod;
         internal static MethodInfo GetRealObjectMethod
         {
             get
             {
                 if (s_getRealObjectMethod == null)
+                {
                     s_getRealObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetRealObject", Globals.ScanAllMembers);
+                    Debug.Assert(s_getRealObjectMethod != null);
+                }
                 return s_getRealObjectMethod;
             }
         }
 
-        private static MethodInfo s_ensureArraySizeMethod;
+        private static MethodInfo? s_ensureArraySizeMethod;
         internal static MethodInfo EnsureArraySizeMethod
         {
             get
@@ -553,7 +565,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_trimArraySizeMethod;
+        private static MethodInfo? s_trimArraySizeMethod;
         internal static MethodInfo TrimArraySizeMethod
         {
             get
@@ -567,7 +579,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_checkEndOfArrayMethod;
+        private static MethodInfo? s_checkEndOfArrayMethod;
         internal static MethodInfo CheckEndOfArrayMethod
         {
             get
@@ -581,21 +593,21 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getArrayLengthMethod;
+        private static MethodInfo? s_getArrayLengthMethod;
         internal static MethodInfo GetArrayLengthMethod
         {
             get
             {
                 if (s_getArrayLengthMethod == null)
                 {
-                    s_getArrayLengthMethod = Globals.TypeOfArray.GetProperty("Length").GetMethod;
+                    s_getArrayLengthMethod = Globals.TypeOfArray.GetProperty("Length")!.GetMethod;
                     Debug.Assert(s_getArrayLengthMethod != null);
                 }
                 return s_getArrayLengthMethod;
             }
         }
 
-        private static MethodInfo s_createSerializationExceptionMethod;
+        private static MethodInfo? s_createSerializationExceptionMethod;
         internal static MethodInfo CreateSerializationExceptionMethod
         {
             get
@@ -609,18 +621,21 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_readSerializationInfoMethod;
+        private static MethodInfo? s_readSerializationInfoMethod;
         internal static MethodInfo ReadSerializationInfoMethod
         {
             get
             {
                 if (s_readSerializationInfoMethod == null)
+                {
                     s_readSerializationInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadSerializationInfo", Globals.ScanAllMembers);
+                    Debug.Assert(s_readSerializationInfoMethod != null);
+                }
                 return s_readSerializationInfoMethod;
             }
         }
 
-        private static MethodInfo s_createUnexpectedStateExceptionMethod;
+        private static MethodInfo? s_createUnexpectedStateExceptionMethod;
         internal static MethodInfo CreateUnexpectedStateExceptionMethod
         {
             get
@@ -634,7 +649,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_internalSerializeReferenceMethod;
+        private static MethodInfo? s_internalSerializeReferenceMethod;
         internal static MethodInfo InternalSerializeReferenceMethod
         {
             get
@@ -648,7 +663,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_internalSerializeMethod;
+        private static MethodInfo? s_internalSerializeMethod;
         internal static MethodInfo InternalSerializeMethod
         {
             get
@@ -662,7 +677,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_writeNullMethod;
+        private static MethodInfo? s_writeNullMethod;
         internal static MethodInfo WriteNullMethod
         {
             get
@@ -676,7 +691,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_incrementArrayCountMethod;
+        private static MethodInfo? s_incrementArrayCountMethod;
         internal static MethodInfo IncrementArrayCountMethod
         {
             get
@@ -690,7 +705,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_incrementCollectionCountMethod;
+        private static MethodInfo? s_incrementCollectionCountMethod;
         internal static MethodInfo IncrementCollectionCountMethod
         {
             get
@@ -704,7 +719,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_incrementCollectionCountGenericMethod;
+        private static MethodInfo? s_incrementCollectionCountGenericMethod;
         internal static MethodInfo IncrementCollectionCountGenericMethod
         {
             get
@@ -718,7 +733,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getDefaultValueMethod;
+        private static MethodInfo? s_getDefaultValueMethod;
         internal static MethodInfo GetDefaultValueMethod
         {
             get
@@ -732,12 +747,12 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal static object GetDefaultValue(Type type)
+        internal static object? GetDefaultValue(Type type)
         {
             return GetDefaultValueMethod.MakeGenericMethod(type).Invoke(null, Array.Empty<object>());
         }
 
-        private static MethodInfo s_getNullableValueMethod;
+        private static MethodInfo? s_getNullableValueMethod;
         internal static MethodInfo GetNullableValueMethod
         {
             get
@@ -751,7 +766,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_throwRequiredMemberMustBeEmittedMethod;
+        private static MethodInfo? s_throwRequiredMemberMustBeEmittedMethod;
         internal static MethodInfo ThrowRequiredMemberMustBeEmittedMethod
         {
             get
@@ -765,7 +780,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getHasValueMethod;
+        private static MethodInfo? s_getHasValueMethod;
         internal static MethodInfo GetHasValueMethod
         {
             get
@@ -779,19 +794,22 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_writeISerializableMethod;
+        private static MethodInfo? s_writeISerializableMethod;
         internal static MethodInfo WriteISerializableMethod
         {
             get
             {
                 if (s_writeISerializableMethod == null)
+                {
                     s_writeISerializableMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteISerializable", Globals.ScanAllMembers);
+                    Debug.Assert(s_writeISerializableMethod != null);
+                }
                 return s_writeISerializableMethod;
             }
         }
 
 
-        private static MethodInfo s_isMemberTypeSameAsMemberValue;
+        private static MethodInfo? s_isMemberTypeSameAsMemberValue;
         internal static MethodInfo IsMemberTypeSameAsMemberValue
         {
             get
@@ -805,11 +823,11 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_writeExtensionDataMethod;
+        private static MethodInfo? s_writeExtensionDataMethod;
         internal static MethodInfo WriteExtensionDataMethod => s_writeExtensionDataMethod ??
-                                                               (s_writeExtensionDataMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", Globals.ScanAllMembers));
+                                                               (s_writeExtensionDataMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", Globals.ScanAllMembers)!);
 
-        private static MethodInfo s_writeXmlValueMethod;
+        private static MethodInfo? s_writeXmlValueMethod;
         internal static MethodInfo WriteXmlValueMethod
         {
             get
@@ -823,7 +841,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_readXmlValueMethod;
+        private static MethodInfo? s_readXmlValueMethod;
         internal static MethodInfo ReadXmlValueMethod
         {
             get
@@ -837,7 +855,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static PropertyInfo s_namespaceProperty;
+        private static PropertyInfo? s_namespaceProperty;
         internal static PropertyInfo NamespaceProperty
         {
             get
@@ -851,7 +869,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static FieldInfo s_contractNamespacesField;
+        private static FieldInfo? s_contractNamespacesField;
         internal static FieldInfo ContractNamespacesField
         {
             get
@@ -865,7 +883,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static FieldInfo s_memberNamesField;
+        private static FieldInfo? s_memberNamesField;
         internal static FieldInfo MemberNamesField
         {
             get
@@ -879,11 +897,11 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_extensionDataSetExplicitMethodInfo;
+        private static MethodInfo? s_extensionDataSetExplicitMethodInfo;
         internal static MethodInfo ExtensionDataSetExplicitMethodInfo => s_extensionDataSetExplicitMethodInfo ??
-                                                                         (s_extensionDataSetExplicitMethodInfo = typeof(IExtensibleDataObject).GetMethod(Globals.ExtensionDataSetMethod));
+                                                                         (s_extensionDataSetExplicitMethodInfo = typeof(IExtensibleDataObject).GetMethod(Globals.ExtensionDataSetMethod)!);
 
-        private static PropertyInfo s_childElementNamespacesProperty;
+        private static PropertyInfo? s_childElementNamespacesProperty;
         internal static PropertyInfo ChildElementNamespacesProperty
         {
             get
@@ -897,7 +915,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static PropertyInfo s_collectionItemNameProperty;
+        private static PropertyInfo? s_collectionItemNameProperty;
         internal static PropertyInfo CollectionItemNameProperty
         {
             get
@@ -911,7 +929,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static PropertyInfo s_childElementNamespaceProperty;
+        private static PropertyInfo? s_childElementNamespaceProperty;
         internal static PropertyInfo ChildElementNamespaceProperty
         {
             get
@@ -925,7 +943,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getDateTimeOffsetMethod;
+        private static MethodInfo? s_getDateTimeOffsetMethod;
         internal static MethodInfo GetDateTimeOffsetMethod
         {
             get
@@ -939,7 +957,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getDateTimeOffsetAdapterMethod;
+        private static MethodInfo? s_getDateTimeOffsetAdapterMethod;
         internal static MethodInfo GetDateTimeOffsetAdapterMethod
         {
             get
@@ -953,7 +971,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getTypeHandleMethod;
+        private static MethodInfo? s_getTypeHandleMethod;
         internal static MethodInfo GetTypeHandleMethod
         {
             get
@@ -967,7 +985,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_getTypeMethod;
+        private static MethodInfo? s_getTypeMethod;
         internal static MethodInfo GetTypeMethod
         {
             get
@@ -981,7 +999,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static MethodInfo s_throwInvalidDataContractExceptionMethod;
+        private static MethodInfo? s_throwInvalidDataContractExceptionMethod;
         internal static MethodInfo ThrowInvalidDataContractExceptionMethod
         {
             get
@@ -995,7 +1013,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static PropertyInfo s_serializeReadOnlyTypesProperty;
+        private static PropertyInfo? s_serializeReadOnlyTypesProperty;
         internal static PropertyInfo SerializeReadOnlyTypesProperty
         {
             get
@@ -1009,7 +1027,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static PropertyInfo s_classSerializationExceptionMessageProperty;
+        private static PropertyInfo? s_classSerializationExceptionMessageProperty;
         internal static PropertyInfo ClassSerializationExceptionMessageProperty
         {
             get
@@ -1023,7 +1041,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static PropertyInfo s_collectionSerializationExceptionMessageProperty;
+        private static PropertyInfo? s_collectionSerializationExceptionMessageProperty;
         internal static PropertyInfo CollectionSerializationExceptionMessageProperty
         {
             get
index 781e361..7452f50 100644 (file)
@@ -11,6 +11,8 @@ using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Security;
 using System.Runtime.CompilerServices;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization
 {
@@ -21,7 +23,7 @@ namespace System.Runtime.Serialization
 
     public sealed class XmlFormatReaderGenerator
 #else
-    internal delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces);
+    internal delegate object? XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context, XmlDictionaryString[]? memberNames, XmlDictionaryString[]? memberNamespaces);
     internal delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract);
     internal delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract);
 
@@ -57,14 +59,14 @@ namespace System.Runtime.Serialization
         /// </SecurityNote>
         private class CriticalHelper
         {
-            private CodeGenerator _ilg;
-            private LocalBuilder _objectLocal;
-            private Type _objectType;
-            private ArgBuilder _xmlReaderArg;
-            private ArgBuilder _contextArg;
-            private ArgBuilder _memberNamesArg;
-            private ArgBuilder _memberNamespacesArg;
-            private ArgBuilder _collectionContractArg;
+            private CodeGenerator _ilg = null!; // initialized in GenerateXXXReader
+            private LocalBuilder? _objectLocal;
+            private Type? _objectType;
+            private ArgBuilder _xmlReaderArg = null!; // initialized in InitArgs
+            private ArgBuilder _contextArg = null!; // initialized in InitArgs
+            private ArgBuilder _memberNamesArg = null!; // initialized in InitArgs
+            private ArgBuilder _memberNamespacesArg = null!; // initialized in InitArgs
+            private ArgBuilder? _collectionContractArg;
 
             private XmlFormatClassReaderDelegate CreateReflectionXmlClassReader(ClassDataContract classContract)
             {
@@ -101,7 +103,7 @@ namespace System.Runtime.Serialization
                     CreateObject(classContract);
                     _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
                     InvokeOnDeserializing(classContract);
-                    LocalBuilder objectId = null;
+                    LocalBuilder? objectId = null;
                     if (HasFactoryMethod(classContract))
                     {
                         objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead");
@@ -233,7 +235,8 @@ namespace System.Runtime.Serialization
                 _memberNamespacesArg = _ilg.GetArg(3);
             }
 
-
+            [MemberNotNull(nameof(_objectType))]
+            [MemberNotNull(nameof(_objectLocal))]
             private void CreateObject(ClassDataContract classContract)
             {
                 Type type = _objectType = classContract.UnderlyingType;
@@ -244,7 +247,7 @@ namespace System.Runtime.Serialization
 
                 if (classContract.UnderlyingType == Globals.TypeOfDBNull)
                 {
-                    _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value"));
+                    _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value")!);
                     _ilg.Stloc(_objectLocal);
                 }
                 else if (classContract.IsNonAttributedType)
@@ -256,7 +259,7 @@ namespace System.Runtime.Serialization
                     }
                     else
                     {
-                        _ilg.New(classContract.GetNonAttributedTypeConstructor());
+                        _ilg.New(classContract.GetNonAttributedTypeConstructor()!);
                         _ilg.Stloc(_objectLocal);
                     }
                 }
@@ -270,6 +273,9 @@ namespace System.Runtime.Serialization
 
             private void InvokeOnDeserializing(ClassDataContract classContract)
             {
+                Debug.Assert(_objectLocal != null);
+                Debug.Assert(_objectType != null);
+
                 if (classContract.BaseContract != null)
                     InvokeOnDeserializing(classContract.BaseContract);
                 if (classContract.OnDeserializing != null)
@@ -284,6 +290,9 @@ namespace System.Runtime.Serialization
 
             private void InvokeOnDeserialized(ClassDataContract classContract)
             {
+                Debug.Assert(_objectLocal != null);
+                Debug.Assert(_objectType != null);
+
                 if (classContract.BaseContract != null)
                     InvokeOnDeserialized(classContract.BaseContract);
                 if (classContract.OnDeserialized != null)
@@ -301,8 +310,10 @@ namespace System.Runtime.Serialization
                 return Globals.TypeOfIObjectReference.IsAssignableFrom(classContract.UnderlyingType);
             }
 
-            private bool InvokeFactoryMethod(ClassDataContract classContract, LocalBuilder objectId)
+            private bool InvokeFactoryMethod(ClassDataContract classContract, LocalBuilder? objectId)
             {
+                Debug.Assert(_objectLocal != null);
+
                 if (HasFactoryMethod(classContract))
                 {
                     _ilg.Load(_contextArg);
@@ -326,10 +337,10 @@ namespace System.Runtime.Serialization
                     _ilg.Store(extensionDataLocal);
                     ReadMembers(classContract, extensionDataLocal);
 
-                    ClassDataContract currentContract = classContract;
+                    ClassDataContract? currentContract = classContract;
                     while (currentContract != null)
                     {
-                        MethodInfo extensionDataSetMethod = currentContract.ExtensionDataSetMethod;
+                        MethodInfo? extensionDataSetMethod = currentContract.ExtensionDataSetMethod;
                         if (extensionDataSetMethod != null)
                             _ilg.Call(_objectLocal, extensionDataSetMethod, extensionDataLocal);
                         currentContract = currentContract.BaseContract;
@@ -341,9 +352,9 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            private void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal)
+            private void ReadMembers(ClassDataContract classContract, LocalBuilder? extensionDataLocal)
             {
-                int memberCount = classContract.MemberNames.Length;
+                int memberCount = classContract.MemberNames!.Length;
                 _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount);
 
                 LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1);
@@ -351,7 +362,7 @@ namespace System.Runtime.Serialization
                 int firstRequiredMember;
                 bool[] requiredMembers = GetRequiredMembers(classContract, out firstRequiredMember);
                 bool hasRequiredMembers = (firstRequiredMember < memberCount);
-                LocalBuilder requiredIndexLocal = hasRequiredMembers ? _ilg.DeclareLocal(Globals.TypeOfInt, "requiredIndex", firstRequiredMember) : null;
+                LocalBuilder? requiredIndexLocal = hasRequiredMembers ? _ilg.DeclareLocal(Globals.TypeOfInt, "requiredIndex", firstRequiredMember) : null;
 
                 object forReadElements = _ilg.For(null, null, null);
                 _ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, _xmlReaderArg);
@@ -366,18 +377,21 @@ namespace System.Runtime.Serialization
                 _ilg.EndFor();
                 if (hasRequiredMembers)
                 {
-                    _ilg.If(requiredIndexLocal, Cmp.LessThan, memberCount);
+                    _ilg.If(requiredIndexLocal!, Cmp.LessThan, memberCount);
                     _ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMissingExceptionMethod, _xmlReaderArg, memberIndexLocal, requiredIndexLocal, _memberNamesArg);
                     _ilg.EndIf();
                 }
             }
 
-            private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, Label[] memberLabels, LocalBuilder memberIndexLocal, LocalBuilder requiredIndexLocal)
+            private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, Label[] memberLabels, LocalBuilder memberIndexLocal, LocalBuilder? requiredIndexLocal)
             {
+                Debug.Assert(_objectLocal != null);
+                Debug.Assert(_objectType != null);
+
                 int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, requiredMembers,
                     memberLabels, memberIndexLocal, requiredIndexLocal);
 
-                for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
+                for (int i = 0; i < classContract.Members!.Count; i++, memberCount++)
                 {
                     DataMember dataMember = classContract.Members[i];
                     Type memberType = dataMember.MemberType;
@@ -388,10 +402,10 @@ namespace System.Runtime.Serialization
                         for (; nextRequiredIndex < requiredMembers.Length; nextRequiredIndex++)
                             if (requiredMembers[nextRequiredIndex])
                                 break;
-                        _ilg.Set(requiredIndexLocal, nextRequiredIndex);
+                        _ilg.Set(requiredIndexLocal!, nextRequiredIndex);
                     }
 
-                    LocalBuilder value = null;
+                    LocalBuilder? value = null;
 
                     if (dataMember.IsGetOnlyCollection)
                     {
@@ -421,7 +435,7 @@ namespace System.Runtime.Serialization
 
             private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequiredMember)
             {
-                int memberCount = contract.MemberNames.Length;
+                int memberCount = contract.MemberNames!.Length;
                 bool[] requiredMembers = new bool[memberCount];
                 GetRequiredMembers(contract, requiredMembers);
                 for (firstRequiredMember = 0; firstRequiredMember < memberCount; firstRequiredMember++)
@@ -433,7 +447,7 @@ namespace System.Runtime.Serialization
             private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers)
             {
                 int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers);
-                List<DataMember> members = contract.Members;
+                List<DataMember> members = contract.Members!;
                 for (int i = 0; i < members.Count; i++, memberCount++)
                 {
                     requiredMembers[memberCount] = members[i].IsRequired;
@@ -443,7 +457,10 @@ namespace System.Runtime.Serialization
 
             private void ReadISerializable(ClassDataContract classContract)
             {
-                ConstructorInfo ctor = classContract.GetISerializableConstructor();
+                Debug.Assert(_objectLocal != null);
+                Debug.Assert(_objectType != null);
+
+                ConstructorInfo ctor = classContract.GetISerializableConstructor()!;
                 _ilg.LoadAddress(_objectLocal);
                 _ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
                 _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadSerializationInfoMethod, _xmlReaderArg, classContract.UnderlyingType);
@@ -455,7 +472,7 @@ namespace System.Runtime.Serialization
             private LocalBuilder ReadValue(Type type, string name, string ns)
             {
                 LocalBuilder value = _ilg.DeclareLocal(type, "valueRead");
-                LocalBuilder nullableValue = null;
+                LocalBuilder? nullableValue = null;
                 int nullables = 0;
                 while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
                 {
@@ -463,7 +480,7 @@ namespace System.Runtime.Serialization
                     type = type.GetGenericArguments()[0];
                 }
 
-                PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
+                PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
                 if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType)
                 {
                     LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead");
@@ -565,19 +582,20 @@ namespace System.Runtime.Serialization
                 for (int i = 1; i < nullables; i++)
                 {
                     Type type = Globals.TypeOfNullable.MakeGenericType(innerType);
-                    _ilg.New(type.GetConstructor(new Type[] { innerType }));
+                    _ilg.New(type.GetConstructor(new Type[] { innerType })!);
                     innerType = type;
                 }
-                _ilg.Call(outerType.GetConstructor(new Type[] { innerType }));
+                _ilg.Call(outerType.GetConstructor(new Type[] { innerType })!);
             }
 
+            [MemberNotNull(nameof(_objectLocal))]
             private void ReadCollection(CollectionDataContract collectionContract)
             {
                 Type type = collectionContract.UnderlyingType;
                 Type itemType = collectionContract.ItemType;
                 bool isArray = (collectionContract.Kind == CollectionKind.Array);
 
-                ConstructorInfo constructor = collectionContract.Constructor;
+                ConstructorInfo constructor = collectionContract.Constructor!;
 
                 if (type.IsInterface)
                 {
@@ -585,7 +603,7 @@ namespace System.Runtime.Serialization
                     {
                         case CollectionKind.GenericDictionary:
                             type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments());
-                            constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
+                            constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>())!;
                             break;
                         case CollectionKind.Dictionary:
                             type = Globals.TypeOfHashtable;
@@ -638,7 +656,7 @@ namespace System.Runtime.Serialization
 
                 _ilg.If(size, Cmp.EqualTo, -1);
 
-                LocalBuilder growingCollection = null;
+                LocalBuilder? growingCollection = null;
                 if (isArray)
                 {
                     growingCollection = _ilg.DeclareLocal(type, "growingCollection");
@@ -653,6 +671,7 @@ namespace System.Runtime.Serialization
                 LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs);
                 if (isArray)
                 {
+                    Debug.Assert(growingCollection != null);
                     MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType);
                     _ilg.Call(null, ensureArraySizeMethod, growingCollection, i);
                     _ilg.Stloc(growingCollection);
@@ -774,11 +793,13 @@ namespace System.Runtime.Serialization
 
             private bool TryReadPrimitiveArray(Type type, Type itemType, LocalBuilder size)
             {
-                PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
+                Debug.Assert(_objectLocal != null);
+
+                PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
                 if (primitiveContract == null)
                     return false;
 
-                string readArrayMethod = null;
+                string? readArrayMethod = null;
                 switch (itemType.GetTypeCode())
                 {
                     case TypeCode.Boolean:
@@ -813,7 +834,7 @@ namespace System.Runtime.Serialization
                     _ilg.Load(_memberNamespacesArg);
                     _ilg.Load(size);
                     _ilg.Ldloca(_objectLocal);
-                    _ilg.Call(typeof(XmlReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers));
+                    _ilg.Call(typeof(XmlReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers)!);
                     return true;
                 }
                 return false;
@@ -842,14 +863,16 @@ namespace System.Runtime.Serialization
 
             private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract)
             {
+                Debug.Assert(collectionContract.AddMethod != null);
+
                 if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary)
                 {
-                    ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract;
+                    ClassDataContract? keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract;
                     if (keyValuePairContract == null)
                     {
                         DiagnosticUtility.DebugAssert("Failed to create contract for KeyValuePair type");
                     }
-                    DataMember keyMember = keyValuePairContract.Members[0];
+                    DataMember keyMember = keyValuePairContract.Members![0];
                     DataMember valueMember = keyValuePairContract.Members[1];
                     LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name);
                     LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name);
index 2d85157..119bf08 100644 (file)
@@ -11,6 +11,7 @@ using System.Collections.Generic;
 using System.Globalization;
 using System.Security;
 using System.Runtime.CompilerServices;
+using System.Diagnostics;
 
 namespace System.Runtime.Serialization
 {
@@ -49,16 +50,16 @@ namespace System.Runtime.Serialization
         private class CriticalHelper
         {
 #if !USE_REFEMIT
-            private CodeGenerator _ilg;
-            private ArgBuilder _xmlWriterArg;
-            private ArgBuilder _contextArg;
-            private ArgBuilder _dataContractArg;
-            private LocalBuilder _objectLocal;
+            private CodeGenerator _ilg = null!; // initialized in GenerateXXXWriter
+            private ArgBuilder _xmlWriterArg = null!; // initialized in InitArgs
+            private ArgBuilder _contextArg = null!; // initialized in InitArgs
+            private ArgBuilder _dataContractArg = null!; // initialized in InitArgs
+            private LocalBuilder _objectLocal = null!; // initialized in InitArgs
 
             // Used for classes
-            private LocalBuilder _contractNamespacesLocal;
-            private LocalBuilder _memberNamesLocal;
-            private LocalBuilder _childElementNamespacesLocal;
+            private LocalBuilder? _contractNamespacesLocal;
+            private LocalBuilder? _memberNamesLocal;
+            private LocalBuilder? _childElementNamespacesLocal;
             private int _typeIndex = 1;
             private int _childElementIndex;
 #endif
@@ -167,8 +168,8 @@ namespace System.Runtime.Serialization
                 else if (objType.IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter)
                 {
                     ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType);
-                    _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments));
-                    _ilg.New(dc.KeyValuePairAdapterConstructorInfo);
+                    _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments!));
+                    _ilg.New(dc.KeyValuePairAdapterConstructorInfo!);
                 }
                 else
                 {
@@ -214,7 +215,7 @@ namespace System.Runtime.Serialization
                 }
                 else
                 {
-                    if (classContract.ContractNamespaces.Length > 1)
+                    if (classContract.ContractNamespaces!.Length > 1)
                     {
                         _contractNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "contractNamespaces");
                         _ilg.Load(_dataContractArg);
@@ -227,7 +228,7 @@ namespace System.Runtime.Serialization
                     _ilg.LoadMember(XmlFormatGeneratorStatics.MemberNamesField);
                     _ilg.Store(_memberNamesLocal);
 
-                    for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++)
+                    for (int i = 0; i < classContract.ChildElementNamespaces!.Length; i++)
                     {
                         if (classContract.ChildElementNamespaces[i] != null)
                         {
@@ -256,7 +257,7 @@ namespace System.Runtime.Serialization
                 InvokeOnSerialized(classContract);
             }
 
-            private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract)
+            private int WriteMembers(ClassDataContract classContract, LocalBuilder? extensionDataLocal, ClassDataContract derivedMostClassContract)
             {
                 int memberCount = (classContract.BaseContract == null) ? 0 :
                     WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract);
@@ -274,14 +275,14 @@ namespace System.Runtime.Serialization
 
                 _ilg.Store(namespaceLocal);
 
-                int classMemberCount = classContract.Members.Count;
+                int classMemberCount = classContract.Members!.Count;
                 _ilg.Call(thisObj: _contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classMemberCount);
 
                 for (int i = 0; i < classMemberCount; i++, memberCount++)
                 {
                     DataMember member = classContract.Members[i];
                     Type memberType = member.MemberType;
-                    LocalBuilder memberValue = null;
+                    LocalBuilder? memberValue = null;
 
                     _ilg.Load(_contextArg);
                     _ilg.Call(methodInfo: member.IsGetOnlyCollection ?
@@ -297,10 +298,10 @@ namespace System.Runtime.Serialization
                     if (writeXsiType || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, arrayItemIndex: null, ns: namespaceLocal, name: null, nameIndex: i + _childElementIndex))
                     {
                         WriteStartElement(memberType, classContract.Namespace, namespaceLocal, nameLocal: null, nameIndex: i + _childElementIndex);
-                        if (classContract.ChildElementNamespaces[i + _childElementIndex] != null)
+                        if (classContract.ChildElementNamespaces![i + _childElementIndex] != null)
                         {
                             _ilg.Load(_xmlWriterArg);
-                            _ilg.LoadArrayElement(_childElementNamespacesLocal, i + _childElementIndex);
+                            _ilg.LoadArrayElement(_childElementNamespacesLocal!, i + _childElementIndex);
                             _ilg.Call(methodInfo: XmlFormatGeneratorStatics.WriteNamespaceDeclMethod);
                         }
                         if (memberValue == null)
@@ -383,7 +384,9 @@ namespace System.Runtime.Serialization
                 }
                 else
                 {
-                    MethodInfo incrementCollectionCountMethod = null;
+                    Debug.Assert(collectionContract.GetEnumeratorMethod != null);
+
+                    MethodInfo? incrementCollectionCountMethod = null;
                     switch (collectionContract.Kind)
                     {
                         case CollectionKind.Collection:
@@ -405,8 +408,8 @@ namespace System.Runtime.Serialization
                     }
 
                     bool isDictionary = false, isGenericDictionary = false;
-                    Type enumeratorType = null;
-                    Type[] keyValueTypes = null;
+                    Type? enumeratorType = null;
+                    Type[]? keyValueTypes = null;
                     if (collectionContract.Kind == CollectionKind.GenericDictionary)
                     {
                         isGenericDictionary = true;
@@ -423,8 +426,8 @@ namespace System.Runtime.Serialization
                     {
                         enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
                     }
-                    MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
-                    MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
+                    MethodInfo? moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
+                    MethodInfo? getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
                     if (moveNextMethod == null || getCurrentMethod == null)
                     {
                         if (enumeratorType.IsInterface)
@@ -453,9 +456,9 @@ namespace System.Runtime.Serialization
                                 }
                             }
                             if (moveNextMethod == null)
-                                moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
+                                moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!;
                             if (getCurrentMethod == null)
-                                getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
+                                getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!;
                         }
                     }
                     Type elementType = getCurrentMethod.ReturnType;
@@ -470,8 +473,8 @@ namespace System.Runtime.Serialization
                     }
                     else if (isGenericDictionary)
                     {
-                        Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
-                        ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam });
+                        Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes!));
+                        ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam })!;
                         _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam);
                         _ilg.New(dictEnumCtor);
                     }
@@ -505,9 +508,9 @@ namespace System.Runtime.Serialization
                 }
             }
 
-            private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder ns, LocalBuilder name, int nameIndex)
+            private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? memberInfo, LocalBuilder? arrayItemIndex, LocalBuilder ns, LocalBuilder? name, int nameIndex)
             {
-                PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
+                PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
                 if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
                     return false;
 
@@ -542,7 +545,7 @@ namespace System.Runtime.Serialization
                 }
                 else
                 {
-                    _ilg.LoadArrayElement(_memberNamesLocal, nameIndex);
+                    _ilg.LoadArrayElement(_memberNamesLocal!, nameIndex);
                 }
                 // load namespace
                 _ilg.Load(ns);
@@ -553,11 +556,11 @@ namespace System.Runtime.Serialization
 
             private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName, LocalBuilder itemNamespace)
             {
-                PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
+                PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
                 if (primitiveContract == null)
                     return false;
 
-                string writeArrayMethod = null;
+                string? writeArrayMethod = null;
                 switch (itemType.GetTypeCode())
                 {
                     case TypeCode.Boolean:
@@ -590,7 +593,7 @@ namespace System.Runtime.Serialization
                     _ilg.Load(value);
                     _ilg.Load(itemName);
                     _ilg.Load(itemNamespace);
-                    _ilg.Call(typeof(XmlWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }));
+                    _ilg.Call(typeof(XmlWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })!);
                     return true;
                 }
                 return false;
@@ -603,7 +606,7 @@ namespace System.Runtime.Serialization
                                       memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);
                 if (memberType.IsValueType && !isNullableOfT)
                 {
-                    PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
+                    PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
                     if (primitiveContract != null && !writeXsiType)
                         _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue);
                     else
@@ -625,7 +628,7 @@ namespace System.Runtime.Serialization
                     _ilg.If();
                     _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType));
                     _ilg.Else();
-                    PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
+                    PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
                     if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType)
                     {
                         if (isNullableOfT)
@@ -712,7 +715,7 @@ namespace System.Runtime.Serialization
                 return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0);
             }
 
-            private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder nameLocal, int nameIndex)
+            private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder? nameLocal, int nameIndex)
             {
                 bool needsPrefix = NeedsPrefix(type, ns);
                 _ilg.Load(_xmlWriterArg);
@@ -722,7 +725,7 @@ namespace System.Runtime.Serialization
 
                 // localName
                 if (nameLocal == null)
-                    _ilg.LoadArrayElement(_memberNamesLocal, nameIndex);
+                    _ilg.LoadArrayElement(_memberNamesLocal!, nameIndex);
                 else
                     _ilg.Load(nameLocal);
 
@@ -746,12 +749,12 @@ namespace System.Runtime.Serialization
                 // Check for conflict with derived type members
                 string name = member.Name;
                 string ns = classContract.StableName.Namespace;
-                ClassDataContract currentContract = derivedMostClassContract;
+                ClassDataContract? currentContract = derivedMostClassContract;
                 while (currentContract != null && currentContract != classContract)
                 {
                     if (ns == currentContract.StableName.Namespace)
                     {
-                        List<DataMember> members = currentContract.Members;
+                        List<DataMember> members = currentContract.Members!;
                         for (int j = 0; j < members.Count; j++)
                         {
                             if (name == members[j].Name)
index d39117a..4d452bf 100644 (file)
@@ -15,11 +15,11 @@ namespace System.Runtime.Serialization
 
     public abstract class XmlObjectSerializer
     {
-        public abstract void WriteStartObject(XmlDictionaryWriter writer, object graph);
-        public abstract void WriteObjectContent(XmlDictionaryWriter writer, object graph);
+        public abstract void WriteStartObject(XmlDictionaryWriter writer, object? graph);
+        public abstract void WriteObjectContent(XmlDictionaryWriter writer, object? graph);
         public abstract void WriteEndObject(XmlDictionaryWriter writer);
 
-        public virtual void WriteObject(Stream stream, object graph)
+        public virtual void WriteObject(Stream stream, object? graph)
         {
             CheckNull(stream, nameof(stream));
             XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false /*ownsStream*/);
@@ -27,19 +27,19 @@ namespace System.Runtime.Serialization
             writer.Flush();
         }
 
-        public virtual void WriteObject(XmlWriter writer, object graph)
+        public virtual void WriteObject(XmlWriter writer, object? graph)
         {
             CheckNull(writer, nameof(writer));
             WriteObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph);
         }
 
-        public virtual void WriteStartObject(XmlWriter writer, object graph)
+        public virtual void WriteStartObject(XmlWriter writer, object? graph)
         {
             CheckNull(writer, nameof(writer));
             WriteStartObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph);
         }
 
-        public virtual void WriteObjectContent(XmlWriter writer, object graph)
+        public virtual void WriteObjectContent(XmlWriter writer, object? graph)
         {
             CheckNull(writer, nameof(writer));
             WriteObjectContent(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph);
@@ -51,17 +51,17 @@ namespace System.Runtime.Serialization
             WriteEndObject(XmlDictionaryWriter.CreateDictionaryWriter(writer));
         }
 
-        public virtual void WriteObject(XmlDictionaryWriter writer, object graph)
+        public virtual void WriteObject(XmlDictionaryWriter writer, object? graph)
         {
             WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
         }
 
-        internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object graph)
+        internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object? graph)
         {
             WriteObjectHandleExceptions(writer, graph, null);
         }
 
-        internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
+        internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object? graph, DataContractResolver? dataContractResolver)
         {
             try
             {
@@ -80,7 +80,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal virtual DataContractDictionary KnownDataContracts
+        internal virtual DataContractDictionary? KnownDataContracts
         {
             get
             {
@@ -88,24 +88,24 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal virtual void InternalWriteObject(XmlWriterDelegator writer, object graph)
+        internal virtual void InternalWriteObject(XmlWriterDelegator writer, object? graph)
         {
             WriteStartObject(writer.Writer, graph);
             WriteObjectContent(writer.Writer, graph);
             WriteEndObject(writer.Writer);
         }
 
-        internal virtual void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
+        internal virtual void InternalWriteObject(XmlWriterDelegator writer, object? graph, DataContractResolver? dataContractResolver)
         {
             InternalWriteObject(writer, graph);
         }
 
-        internal virtual void InternalWriteStartObject(XmlWriterDelegator writer, object graph)
+        internal virtual void InternalWriteStartObject(XmlWriterDelegator writer, object? graph)
         {
             DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalWriteStartObject should never get called");
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
         }
-        internal virtual void InternalWriteObjectContent(XmlWriterDelegator writer, object graph)
+        internal virtual void InternalWriteObjectContent(XmlWriterDelegator writer, object? graph)
         {
             DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalWriteObjectContent should never get called");
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
@@ -116,7 +116,7 @@ namespace System.Runtime.Serialization
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
         }
 
-        internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer, object graph)
+        internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer, object? graph)
         {
             try
             {
@@ -133,7 +133,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal void WriteObjectContentHandleExceptions(XmlWriterDelegator writer, object graph)
+        internal void WriteObjectContentHandleExceptions(XmlWriterDelegator writer, object? graph)
         {
             try
             {
@@ -171,13 +171,13 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns, bool needsContractNsAtRoot)
+        internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns, bool needsContractNsAtRoot)
         {
             if (name == null) // root name not set explicitly
             {
                 if (!contract.HasRoot)
                     return;
-                contract.WriteRootElement(writer, contract.TopLevelElementName, contract.TopLevelElementNamespace);
+                contract.WriteRootElement(writer, contract.TopLevelElementName!, contract.TopLevelElementNamespace);
             }
             else
             {
@@ -189,7 +189,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString name, XmlDictionaryString ns, DataContract contract)
+        internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString? name, XmlDictionaryString? ns, DataContract contract)
         {
             if (name == null)
                 return false;
@@ -199,7 +199,7 @@ namespace System.Runtime.Serialization
                 return false;
             }
 
-            string contractNs = XmlDictionaryString.GetString(contract.Namespace);
+            string? contractNs = XmlDictionaryString.GetString(contract.Namespace);
             if (string.IsNullOrEmpty(contractNs) || contractNs == XmlDictionaryString.GetString(ns))
                 return false;
 
@@ -217,30 +217,30 @@ namespace System.Runtime.Serialization
                 || (contract.Name.Value == declaredContract.Name.Value && contract.Namespace.Value == declaredContract.Namespace.Value);
         }
 
-        public virtual object ReadObject(Stream stream)
+        public virtual object? ReadObject(Stream stream)
         {
             CheckNull(stream, nameof(stream));
             return ReadObject(XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max));
         }
 
-        public virtual object ReadObject(XmlReader reader)
+        public virtual object? ReadObject(XmlReader reader)
         {
             CheckNull(reader, nameof(reader));
             return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader));
         }
 
-        public virtual object ReadObject(XmlDictionaryReader reader)
+        public virtual object? ReadObject(XmlDictionaryReader reader)
         {
             return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/);
         }
 
-        public virtual object ReadObject(XmlReader reader, bool verifyObjectName)
+        public virtual object? ReadObject(XmlReader reader, bool verifyObjectName)
         {
             CheckNull(reader, nameof(reader));
             return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader), verifyObjectName);
         }
 
-        public abstract object ReadObject(XmlDictionaryReader reader, bool verifyObjectName);
+        public abstract object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName);
 
         public virtual bool IsStartObject(XmlReader reader)
         {
@@ -250,12 +250,12 @@ namespace System.Runtime.Serialization
 
         public abstract bool IsStartObject(XmlDictionaryReader reader);
 
-        internal virtual object InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName)
+        internal virtual object? InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName)
         {
             return ReadObject(reader.UnderlyingReader, verifyObjectName);
         }
 
-        internal virtual object InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver dataContractResolver)
+        internal virtual object? InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver? dataContractResolver)
         {
             return InternalReadObject(reader, verifyObjectName);
         }
@@ -266,12 +266,12 @@ namespace System.Runtime.Serialization
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
         }
 
-        internal object ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName)
+        internal object? ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName)
         {
             return ReadObjectHandleExceptions(reader, verifyObjectName, null);
         }
 
-        internal object ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver dataContractResolver)
+        internal object? ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver? dataContractResolver)
         {
             try
             {
@@ -305,7 +305,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal bool IsRootXmlAny(XmlDictionaryString rootName, DataContract contract)
+        internal bool IsRootXmlAny(XmlDictionaryString? rootName, DataContract contract)
         {
             return (rootName == null) && !contract.HasRoot;
         }
@@ -315,34 +315,34 @@ namespace System.Runtime.Serialization
             return (reader.MoveToElement() || reader.IsStartElement());
         }
 
-        internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns)
+        internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns)
         {
             reader.MoveToElement();
             if (name != null) // root name set explicitly
             {
-                return reader.IsStartElement(name, ns);
+                return reader.IsStartElement(name, ns!); // https://github.com/dotnet/runtime/issues/41395
             }
             else
             {
                 if (!contract.HasRoot)
                     return reader.IsStartElement();
 
-                if (reader.IsStartElement(contract.TopLevelElementName, contract.TopLevelElementNamespace))
+                if (reader.IsStartElement(contract.TopLevelElementName!, contract.TopLevelElementNamespace!))
                     return true;
 
-                ClassDataContract classContract = contract as ClassDataContract;
+                ClassDataContract? classContract = contract as ClassDataContract;
                 if (classContract != null)
                     classContract = classContract.BaseContract;
                 while (classContract != null)
                 {
-                    if (reader.IsStartElement(classContract.TopLevelElementName, classContract.TopLevelElementNamespace))
+                    if (reader.IsStartElement(classContract.TopLevelElementName!, classContract.TopLevelElementNamespace!))
                         return true;
                     classContract = classContract.BaseContract;
                 }
                 if (classContract == null)
                 {
-                    DataContract objectContract = PrimitiveDataContract.GetPrimitiveDataContract(Globals.TypeOfObject);
-                    if (reader.IsStartElement(objectContract.TopLevelElementName, objectContract.TopLevelElementNamespace))
+                    DataContract objectContract = PrimitiveDataContract.GetPrimitiveDataContract(Globals.TypeOfObject)!;
+                    if (reader.IsStartElement(objectContract.TopLevelElementName!, objectContract.TopLevelElementNamespace!))
                         return true;
                 }
                 return false;
@@ -373,28 +373,28 @@ namespace System.Runtime.Serialization
         }
 
         [MethodImpl(MethodImplOptions.NoInlining)]
-        internal static SerializationException CreateSerializationException(string errorMessage, Exception innerException)
+        internal static SerializationException CreateSerializationException(string errorMessage, Exception? innerException)
         {
             return new SerializationException(errorMessage, innerException);
         }
-        internal static string GetTypeInfoError(string errorMessage, Type type, Exception innerException)
+        internal static string GetTypeInfoError(string errorMessage, Type? type, Exception innerException)
         {
             string typeInfo = (type == null) ? string.Empty : SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(type));
             string innerExceptionMessage = (innerException == null) ? string.Empty : innerException.Message;
             return SR.Format(errorMessage, typeInfo, innerExceptionMessage);
         }
 
-        internal virtual Type GetSerializeType(object graph)
+        internal virtual Type? GetSerializeType(object? graph)
         {
             return (graph == null) ? null : graph.GetType();
         }
 
-        internal virtual Type GetDeserializeType()
+        internal virtual Type? GetDeserializeType()
         {
             return null;
         }
 
-        private static IFormatterConverter s_formatterConverter;
+        private static IFormatterConverter? s_formatterConverter;
         internal static IFormatterConverter FormatterConverter
         {
             get
index 1fcb25c..7dd8deb 100644 (file)
@@ -18,20 +18,20 @@ namespace System.Runtime.Serialization
 #endif
     {
         protected XmlObjectSerializer serializer;
-        protected DataContract rootTypeDataContract;
+        protected DataContract? rootTypeDataContract;
         internal ScopedKnownTypes scopedKnownTypes;
-        protected DataContractDictionary serializerKnownDataContracts;
+        protected DataContractDictionary? serializerKnownDataContracts;
         private bool _isSerializerKnownDataContractsSetExplicit;
-        protected IList<Type> serializerKnownTypeList;
+        protected IList<Type>? serializerKnownTypeList;
         private int _itemCount;
         private readonly int _maxItemsInObjectGraph;
         private readonly StreamingContext _streamingContext;
         private readonly bool _ignoreExtensionDataObject;
-        private readonly DataContractResolver _dataContractResolver;
-        private KnownTypeDataContractResolver _knownTypeResolver;
+        private readonly DataContractResolver? _dataContractResolver;
+        private KnownTypeDataContractResolver? _knownTypeResolver;
 
         internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject,
-                                            DataContractResolver dataContractResolver)
+                                            DataContractResolver? dataContractResolver)
         {
             this.serializer = serializer;
             _itemCount = 1;
@@ -46,7 +46,7 @@ namespace System.Runtime.Serialization
         {
         }
 
-        internal XmlObjectSerializerContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
+        internal XmlObjectSerializerContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? dataContractResolver)
             : this(serializer,
             serializer.MaxItemsInObjectGraph,
             default(StreamingContext),
@@ -102,7 +102,7 @@ namespace System.Runtime.Serialization
             get { return _ignoreExtensionDataObject; }
         }
 
-        protected DataContractResolver DataContractResolver
+        protected DataContractResolver? DataContractResolver
         {
             get { return _dataContractResolver; }
         }
@@ -124,7 +124,7 @@ namespace System.Runtime.Serialization
             return GetDataContract(type.TypeHandle, type);
         }
 
-        internal virtual DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
+        internal virtual DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type? type)
         {
             if (IsGetOnlyCollection)
             {
@@ -136,7 +136,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal virtual DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
+        internal virtual DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type? type)
         {
             if (IsGetOnlyCollection)
             {
@@ -171,7 +171,7 @@ namespace System.Runtime.Serialization
         {
             return type;
         }
-        internal virtual DataContractDictionary SerializerKnownDataContracts
+        internal virtual DataContractDictionary? SerializerKnownDataContracts
         {
             get
             {
@@ -185,16 +185,16 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private DataContract GetDataContractFromSerializerKnownTypes(XmlQualifiedName qname)
+        private DataContract? GetDataContractFromSerializerKnownTypes(XmlQualifiedName qname)
         {
-            DataContractDictionary serializerKnownDataContracts = this.SerializerKnownDataContracts;
+            DataContractDictionary? serializerKnownDataContracts = this.SerializerKnownDataContracts;
             if (serializerKnownDataContracts == null)
                 return null;
-            DataContract outDataContract;
+            DataContract? outDataContract;
             return serializerKnownDataContracts.TryGetValue(qname, out outDataContract) ? outDataContract : null;
         }
 
-        internal static DataContractDictionary GetDataContractsForKnownTypes(IList<Type> knownTypeList)
+        internal static DataContractDictionary? GetDataContractsForKnownTypes(IList<Type> knownTypeList)
         {
             if (knownTypeList == null) return null;
             DataContractDictionary dataContracts = new DataContractDictionary();
@@ -210,7 +210,7 @@ namespace System.Runtime.Serialization
             return dataContracts;
         }
 
-        internal bool IsKnownType(DataContract dataContract, DataContractDictionary knownDataContracts, Type declaredType)
+        internal bool IsKnownType(DataContract dataContract, DataContractDictionary? knownDataContracts, Type? declaredType)
         {
             bool knownTypesAddedInCurrentScope = false;
             if (knownDataContracts != null)
@@ -228,21 +228,21 @@ namespace System.Runtime.Serialization
             return isKnownType;
         }
 
-        internal bool IsKnownType(DataContract dataContract, Type declaredType)
+        internal bool IsKnownType(DataContract dataContract, Type? declaredType)
         {
-            DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/, declaredType);
+            DataContract? knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/, declaredType);
             return knownContract != null && knownContract.UnderlyingType == dataContract.UnderlyingType;
         }
 
-        internal Type ResolveNameFromKnownTypes(XmlQualifiedName typeName)
+        internal Type? ResolveNameFromKnownTypes(XmlQualifiedName typeName)
         {
-            DataContract dataContract = ResolveDataContractFromKnownTypes(typeName);
+            DataContract? dataContract = ResolveDataContractFromKnownTypes(typeName);
             return dataContract == null ? null : dataContract.UnderlyingType;
         }
 
-        private DataContract ResolveDataContractFromKnownTypes(XmlQualifiedName typeName)
+        private DataContract? ResolveDataContractFromKnownTypes(XmlQualifiedName typeName)
         {
-            DataContract dataContract = PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace);
+            DataContract? dataContract = PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace);
             if (dataContract == null)
             {
                 dataContract = scopedKnownTypes.GetDataContract(typeName);
@@ -254,17 +254,17 @@ namespace System.Runtime.Serialization
             return dataContract;
         }
 
-        protected DataContract ResolveDataContractFromKnownTypes(string typeName, string typeNs, DataContract memberTypeContract, Type declaredType)
+        protected DataContract? ResolveDataContractFromKnownTypes(string typeName, string? typeNs, DataContract? memberTypeContract, Type? declaredType)
         {
             XmlQualifiedName qname = new XmlQualifiedName(typeName, typeNs);
-            DataContract dataContract;
+            DataContract? dataContract;
             if (_dataContractResolver == null)
             {
                 dataContract = ResolveDataContractFromKnownTypes(qname);
             }
             else
             {
-                Type dataContractType = _dataContractResolver.ResolveName(typeName, typeNs, declaredType, KnownTypeResolver);
+                Type? dataContractType = _dataContractResolver.ResolveName(typeName, typeNs, declaredType, KnownTypeResolver);
                 dataContract = dataContractType == null ? null : GetDataContract(dataContractType);
             }
             if (dataContract == null)
@@ -281,7 +281,7 @@ namespace System.Runtime.Serialization
                         dataContract = rootTypeDataContract;
                     else
                     {
-                        CollectionDataContract collectionContract = rootTypeDataContract as CollectionDataContract;
+                        CollectionDataContract? collectionContract = rootTypeDataContract as CollectionDataContract;
                         while (collectionContract != null)
                         {
                             DataContract itemContract = GetDataContract(GetSurrogatedType(collectionContract.ItemType));
index 927488d..6a36eb7 100644 (file)
@@ -12,6 +12,7 @@ namespace System.Runtime.Serialization
     using System.Xml.Serialization;
     using System.Security;
     using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
+    using System.Diagnostics.CodeAnalysis;
 
 #if USE_REFEMIT
     public class XmlObjectSerializerReadContext : XmlObjectSerializerContext
@@ -19,12 +20,12 @@ namespace System.Runtime.Serialization
     internal class XmlObjectSerializerReadContext : XmlObjectSerializerContext
 #endif
     {
-        internal Attributes attributes;
-        private HybridObjectCache _deserializedObjects;
-        private XmlSerializableReader _xmlSerializableReader;
-        private XmlDocument _xmlDocument;
-        private Attributes _attributesInXmlData;
-        private object _getOnlyCollectionValue;
+        internal Attributes? attributes;
+        private HybridObjectCache? _deserializedObjects;
+        private XmlSerializableReader? _xmlSerializableReader;
+        private XmlDocument? _xmlDocument;
+        private Attributes? _attributesInXmlData;
+        private object? _getOnlyCollectionValue;
         private bool _isGetOnlyCollection;
 
         private HybridObjectCache DeserializedObjects
@@ -48,18 +49,18 @@ namespace System.Runtime.Serialization
 
 
 #if USE_REFEMIT
-        public object GetCollectionMember()
+        public object? GetCollectionMember()
 #else
-        internal object GetCollectionMember()
+        internal object? GetCollectionMember()
 #endif
         {
             return _getOnlyCollectionValue;
         }
 
 #if USE_REFEMIT
-        public void StoreCollectionMemberInfo(object collectionMember)
+        public void StoreCollectionMemberInfo(object? collectionMember)
 #else
-        internal void StoreCollectionMemberInfo(object collectionMember)
+        internal void StoreCollectionMemberInfo(object? collectionMember)
 #endif
         {
             _getOnlyCollectionValue = collectionMember;
@@ -72,6 +73,7 @@ namespace System.Runtime.Serialization
             _isGetOnlyCollection = false;
         }
 
+        [DoesNotReturn]
 #if USE_REFEMIT
         public static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type)
 #else
@@ -81,6 +83,7 @@ namespace System.Runtime.Serialization
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NullValueReturnedForGetOnlyCollection, DataContract.GetClrTypeFullName(type))));
         }
 
+        [DoesNotReturn]
 #if USE_REFEMIT
         public static void ThrowArrayExceededSizeException(int arraySize, Type type)
 #else
@@ -90,7 +93,7 @@ namespace System.Runtime.Serialization
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSize, arraySize, DataContract.GetClrTypeFullName(type))));
         }
 
-        internal static XmlObjectSerializerReadContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
+        internal static XmlObjectSerializerReadContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? dataContractResolver)
         {
             return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null)
                 ? new XmlObjectSerializerReadContextComplex(serializer, rootTypeDataContract, dataContractResolver)
@@ -102,7 +105,7 @@ namespace System.Runtime.Serialization
         {
         }
 
-        internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
+        internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? dataContractResolver)
             : base(serializer, rootTypeDataContract, dataContractResolver)
         {
             this.attributes = new Attributes();
@@ -110,29 +113,29 @@ namespace System.Runtime.Serialization
 
 
 #if USE_REFEMIT
-        public virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
+        public virtual object? InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
 #else
-        internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
+        internal virtual object? InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
 #endif
         {
             DataContract dataContract = GetDataContract(id, declaredTypeHandle);
             return InternalDeserialize(xmlReader, name, ns, Type.GetTypeFromHandle(declaredTypeHandle), ref dataContract);
         }
 
-        internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns)
+        internal virtual object? InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns)
         {
             DataContract dataContract = GetDataContract(declaredType);
             return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract);
         }
 
-        internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns)
+        internal virtual object? InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract? dataContract, string? name, string? ns)
         {
             if (dataContract == null)
-                GetDataContract(declaredType);
+                dataContract = GetDataContract(declaredType);
             return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract);
         }
 
-        protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string name, string ns, ref object retObj)
+        protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string? name, string? ns, ref object? retObj)
         {
             ReadAttributes(reader);
 
@@ -157,9 +160,9 @@ namespace System.Runtime.Serialization
             return false;
         }
 
-        protected object InternalDeserialize(XmlReaderDelegator reader, string name, string ns, Type declaredType, ref DataContract dataContract)
+        protected object? InternalDeserialize(XmlReaderDelegator reader, string? name, string? ns, Type declaredType, ref DataContract dataContract)
         {
-            object retObj = null;
+            object? retObj = null;
             if (TryHandleNullOrRef(reader, dataContract.UnderlyingType, name, ns, ref retObj))
                 return retObj;
 
@@ -170,10 +173,12 @@ namespace System.Runtime.Serialization
                 knownTypesAddedInCurrentScope = true;
             }
 
+            Debug.Assert(attributes != null);
+
             if (attributes.XsiTypeName != null)
             {
-                dataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract, declaredType);
-                if (dataContract == null)
+                DataContract? tempDataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract, declaredType);
+                if (tempDataContract == null)
                 {
                     if (DataContractResolver == null)
                     {
@@ -181,12 +186,13 @@ namespace System.Runtime.Serialization
                     }
                     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotResolvedOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName))));
                 }
+                dataContract = tempDataContract;
                 knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope);
             }
 
             if (dataContract.IsISerializable && attributes.FactoryTypeName != null)
             {
-                DataContract factoryDataContract = ResolveDataContractFromKnownTypes(attributes.FactoryTypeName, attributes.FactoryTypeNamespace, dataContract, declaredType);
+                DataContract? factoryDataContract = ResolveDataContractFromKnownTypes(attributes.FactoryTypeName, attributes.FactoryTypeNamespace, dataContract, declaredType);
                 if (factoryDataContract != null)
                 {
                     if (factoryDataContract.IsISerializable)
@@ -203,7 +209,7 @@ namespace System.Runtime.Serialization
 
             if (knownTypesAddedInCurrentScope)
             {
-                object obj = ReadDataContractValue(dataContract, reader);
+                object? obj = ReadDataContractValue(dataContract, reader);
                 scopedKnownTypes.Pop();
                 return obj;
             }
@@ -213,7 +219,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private bool ReplaceScopedKnownTypesTop(DataContractDictionary knownDataContracts, bool knownTypesAddedInCurrentScope)
+        private bool ReplaceScopedKnownTypesTop(DataContractDictionary? knownDataContracts, bool knownTypesAddedInCurrentScope)
         {
             if (knownTypesAddedInCurrentScope)
             {
@@ -238,9 +244,9 @@ namespace System.Runtime.Serialization
         }
 
 #if USE_REFEMIT
-        public int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData)
+        public int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject? extensionData)
 #else
-        internal int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData)
+        internal int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject? extensionData)
 #endif
         {
             for (int i = memberIndex + 1; i < memberNames.Length; i++)
@@ -253,9 +259,9 @@ namespace System.Runtime.Serialization
         }
 
 #if USE_REFEMIT
-        public int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData)
+        public int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject? extensionData)
 #else
-        internal int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData)
+        internal int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject? extensionData)
 #endif
         {
             for (int i = memberIndex + 1; i < memberNames.Length; i++)
@@ -271,6 +277,7 @@ namespace System.Runtime.Serialization
             return memberNames.Length;
         }
 
+        [DoesNotReturn]
 #if USE_REFEMIT
         public static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames)
 #else
@@ -289,7 +296,7 @@ namespace System.Runtime.Serialization
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.UnexpectedElementExpectingElements, xmlReader.NodeType, xmlReader.LocalName, xmlReader.NamespaceURI, stringBuilder.ToString()))));
         }
 
-        protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex)
+        protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject? extensionData, int memberIndex)
         {
             xmlReader.MoveToContent();
             if (xmlReader.NodeType != XmlNodeType.Element)
@@ -324,6 +331,8 @@ namespace System.Runtime.Serialization
         internal string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable)
 #endif
         {
+            Debug.Assert(attributes != null);
+
             if (attributes.Ref != Globals.NewObjectId)
             {
                 CheckIfTypeSerializable(memberType, isMemberTypeSerializable);
@@ -339,6 +348,7 @@ namespace System.Runtime.Serialization
             return Globals.NewObjectId;
         }
 
+        [MemberNotNull(nameof(attributes))]
 #if USE_REFEMIT
         public virtual void ReadAttributes(XmlReaderDelegator xmlReader)
 #else
@@ -366,6 +376,8 @@ namespace System.Runtime.Serialization
         internal string GetObjectId()
 #endif
         {
+            Debug.Assert(attributes != null);
+
             return attributes.Id;
         }
 
@@ -379,25 +391,27 @@ namespace System.Runtime.Serialization
         }
 
 #if USE_REFEMIT
-        public void AddNewObject(object obj)
+        public void AddNewObject(object? obj)
 #else
-        internal void AddNewObject(object obj)
+        internal void AddNewObject(object? obj)
 #endif
         {
+            Debug.Assert(attributes != null);
+
             AddNewObjectWithId(attributes.Id, obj);
         }
 
 #if USE_REFEMIT
-        public void AddNewObjectWithId(string id, object obj)
+        public void AddNewObjectWithId(string id, object? obj)
 #else
-        internal void AddNewObjectWithId(string id, object obj)
+        internal void AddNewObjectWithId(string id, object? obj)
 #endif
         {
             if (id != Globals.NewObjectId)
                 DeserializedObjects.Add(id, obj);
         }
 
-        public void ReplaceDeserializedObject(string id, object oldObj, object newObj)
+        public void ReplaceDeserializedObject(string id, object? oldObj, object? newObj)
         {
             if (object.ReferenceEquals(oldObj, newObj))
                 return;
@@ -411,19 +425,23 @@ namespace System.Runtime.Serialization
                 // These XmlObjectSerializer implementations do not currently support fix-ups. Hence we
                 // throw in such cases to allow us add fix-up support in the future if we need to.
                 if (DeserializedObjects.IsObjectReferenced(id))
+                {
+                    // https://github.com/dotnet/runtime/issues/41465 - oldObj or newObj may be null below - suppress compiler error by asserting non-null
+                    Debug.Assert(oldObj != null && newObj != null);
                     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.FactoryObjectContainsSelfReference, DataContract.GetClrTypeFullName(oldObj.GetType()), DataContract.GetClrTypeFullName(newObj.GetType()), id)));
+                }
                 DeserializedObjects.Remove(id);
                 DeserializedObjects.Add(id, newObj);
             }
         }
 
 #if USE_REFEMIT
-        public object GetExistingObject(string id, Type type, string name, string ns)
+        public object GetExistingObject(string id, Type? type, string? name, string? ns)
 #else
-        internal object GetExistingObject(string id, Type type, string name, string ns)
+        internal object GetExistingObject(string id, Type? type, string? name, string? ns)
 #endif
         {
-            object retObj = DeserializedObjects.GetObject(id);
+            object? retObj = DeserializedObjects.GetObject(id);
             if (retObj == null)
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DeserializedObjectWithIdNotFound, id)));
             return retObj;
@@ -431,7 +449,7 @@ namespace System.Runtime.Serialization
 
         private object GetExistingObjectOrExtensionData(string id)
         {
-            object retObj = DeserializedObjects.GetObject(id);
+            object? retObj = DeserializedObjects.GetObject(id);
             if (retObj == null)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
@@ -443,7 +461,7 @@ namespace System.Runtime.Serialization
 
         public object GetRealObject(IObjectReference obj, string id)
         {
-            object realObj = SurrogateDataContract.GetRealObject(obj, this.GetStreamingContext());
+            object? realObj = SurrogateDataContract.GetRealObject(obj, this.GetStreamingContext());
             // If GetRealObject returns null, it indicates that the object could not resolve itself because
             // it is missing information. This may occur in a case where multiple IObjectReference instances
             // depend on each other. BinaryFormatter supports this by fixing up the references later. These
@@ -466,7 +484,7 @@ namespace System.Runtime.Serialization
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile));
         }
 
-        internal static void ParseQualifiedName(string qname, XmlReaderDelegator xmlReader, out string name, out string ns, out string prefix)
+        internal static void ParseQualifiedName(string qname, XmlReaderDelegator xmlReader, out string name, out string? ns, out string prefix)
         {
             int colon = qname.IndexOf(':');
             prefix = "";
@@ -532,21 +550,21 @@ namespace System.Runtime.Serialization
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.EndElement, xmlReader));
         }
 
-        internal object ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType)
+        internal object? ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType)
         {
             if (_xmlSerializableReader == null)
                 _xmlSerializableReader = new XmlSerializableReader();
             return ReadIXmlSerializable(_xmlSerializableReader, xmlReader, xmlDataContract, isMemberType);
         }
 
-        internal static object ReadRootIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType)
+        internal static object? ReadRootIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType)
         {
             return ReadIXmlSerializable(new XmlSerializableReader(), xmlReader, xmlDataContract, isMemberType);
         }
 
-        internal static object ReadIXmlSerializable(XmlSerializableReader xmlSerializableReader, XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType)
+        internal static object? ReadIXmlSerializable(XmlSerializableReader xmlSerializableReader, XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType)
         {
-            object obj = null;
+            object? obj = null;
             xmlSerializableReader.BeginRead(xmlReader);
             if (isMemberType && !xmlDataContract.HasRoot)
             {
@@ -558,7 +576,7 @@ namespace System.Runtime.Serialization
                 if (!xmlReader.IsStartElement())
                     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader));
                 XmlDocument xmlDoc = new XmlDocument();
-                obj = (XmlElement)xmlDoc.ReadNode(xmlSerializableReader);
+                obj = (XmlElement?)xmlDoc.ReadNode(xmlSerializableReader);
             }
             else if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlNodeArray)
             {
@@ -595,7 +613,7 @@ namespace System.Runtime.Serialization
 
                 IncrementItemCount(1);
                 ReadAttributes(xmlReader);
-                object value;
+                object? value;
                 if (attributes.Ref != Globals.NewObjectId)
                 {
                     xmlReader.Skip();
@@ -617,17 +635,17 @@ namespace System.Runtime.Serialization
             return serInfo;
         }
 
-        protected virtual DataContract ResolveDataContractFromTypeName()
+        protected virtual DataContract? ResolveDataContractFromTypeName()
         {
+            Debug.Assert(attributes != null);
+
             return (attributes.XsiTypeName == null) ? null : ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, null /*memberTypeContract*/, null);
         }
 
         private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader, int memberIndex)
         {
-            var member = new ExtensionDataMember
+            var member = new ExtensionDataMember(xmlReader.LocalName, xmlReader.NamespaceURI)
             {
-                Name = xmlReader.LocalName,
-                Namespace = xmlReader.NamespaceURI,
                 MemberIndex = memberIndex
             };
 
@@ -635,11 +653,11 @@ namespace System.Runtime.Serialization
             return member;
         }
 
-        public IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader)
+        public IDataNode? ReadExtensionDataValue(XmlReaderDelegator xmlReader)
         {
             ReadAttributes(xmlReader);
             IncrementItemCount(1);
-            IDataNode dataNode = null;
+            IDataNode? dataNode = null;
             if (attributes.Ref != Globals.NewObjectId)
             {
                 xmlReader.Skip();
@@ -654,8 +672,8 @@ namespace System.Runtime.Serialization
             }
             else
             {
-                string dataContractName = null;
-                string dataContractNamespace = null;
+                string? dataContractName = null;
+                string? dataContractNamespace = null;
                 if (attributes.XsiTypeName != null)
                 {
                     dataContractName = attributes.XsiTypeName;
@@ -679,7 +697,7 @@ namespace System.Runtime.Serialization
                 }
                 else
                 {
-                    DataContract dataContract = ResolveDataContractFromTypeName();
+                    DataContract? dataContract = ResolveDataContractFromTypeName();
 
                     if (dataContract == null)
                         dataNode = ReadExtensionDataValue(xmlReader, dataContractName, dataContractNamespace);
@@ -732,14 +750,16 @@ namespace System.Runtime.Serialization
         {
         }
 
-        private IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace)
+        private IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace)
         {
+            Debug.Assert(attributes != null);
+
             StartReadExtensionDataValue(xmlReader);
 
             if (attributes.UnrecognizedAttributesFound)
                 return ReadUnknownXmlData(xmlReader, dataContractName, dataContractNamespace);
 
-            IDictionary<string, string> namespacesInScope = xmlReader.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml);
+            IDictionary<string, string>? namespacesInScope = xmlReader.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml);
             Read(xmlReader);
             xmlReader.MoveToContent();
 
@@ -766,7 +786,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        protected virtual IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace)
+        protected virtual IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace)
         {
             Type valueType = xmlReader.ValueType;
             if (valueType == Globals.TypeOfString)
@@ -784,8 +804,10 @@ namespace System.Runtime.Serialization
             return objNode;
         }
 
-        protected void InitializeExtensionDataNode(IDataNode dataNode, string dataContractName, string dataContractNamespace)
+        protected void InitializeExtensionDataNode(IDataNode dataNode, string? dataContractName, string? dataContractNamespace)
         {
+            Debug.Assert(attributes != null);
+
             dataNode.DataContractName = dataContractName;
             dataNode.DataContractNamespace = dataContractNamespace;
             dataNode.ClrAssemblyName = attributes.ClrAssembly;
@@ -794,14 +816,14 @@ namespace System.Runtime.Serialization
             dataNode.Id = attributes.Id;
         }
 
-        private IDataNode ReadUnknownPrimitiveData(XmlReaderDelegator xmlReader, Type type, string dataContractName, string dataContractNamespace)
+        private IDataNode ReadUnknownPrimitiveData(XmlReaderDelegator xmlReader, Type type, string? dataContractName, string? dataContractNamespace)
         {
             IDataNode dataNode = xmlReader.ReadExtensionData(type);
             InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace);
             return dataNode;
         }
 
-        private ClassDataNode ReadUnknownClassData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace)
+        private ClassDataNode ReadUnknownClassData(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace)
         {
             var dataNode = new ClassDataNode();
             InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace);
@@ -821,8 +843,10 @@ namespace System.Runtime.Serialization
             return dataNode;
         }
 
-        private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace)
+        private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace)
         {
+            Debug.Assert(attributes != null);
+
             var dataNode = new CollectionDataNode();
             InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace);
 
@@ -838,10 +862,10 @@ namespace System.Runtime.Serialization
                     dataNode.ItemName = xmlReader.LocalName;
                     dataNode.ItemNamespace = xmlReader.NamespaceURI;
                 }
-                if (xmlReader.IsStartElement(dataNode.ItemName, dataNode.ItemNamespace))
+                if (xmlReader.IsStartElement(dataNode.ItemName, dataNode.ItemNamespace!))
                 {
                     if (dataNode.Items == null)
-                        dataNode.Items = new List<IDataNode>();
+                        dataNode.Items = new List<IDataNode?>();
                     dataNode.Items.Add(ReadExtensionDataValue(xmlReader));
                 }
                 else
@@ -875,8 +899,10 @@ namespace System.Runtime.Serialization
             return dataNode;
         }
 
-        private ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace)
+        private ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace)
         {
+            Debug.Assert(attributes != null);
+
             var dataNode = new ISerializableDataNode();
             InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace);
 
@@ -895,8 +921,7 @@ namespace System.Runtime.Serialization
                     continue;
                 }
 
-                var member = new ISerializableDataMember();
-                member.Name = xmlReader.LocalName;
+                var member = new ISerializableDataMember(xmlReader.LocalName);
                 member.Value = ReadExtensionDataValue(xmlReader);
                 if (dataNode.Members == null)
                     dataNode.Members = new List<ISerializableDataMember>();
@@ -906,7 +931,7 @@ namespace System.Runtime.Serialization
             return dataNode;
         }
 
-        private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace)
+        private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace)
         {
             XmlDataNode dataNode = new XmlDataNode();
             InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace);
@@ -915,8 +940,8 @@ namespace System.Runtime.Serialization
             if (xmlReader.NodeType == XmlNodeType.EndElement)
                 return dataNode;
 
-            IList<XmlAttribute> xmlAttributes = null;
-            IList<XmlNode> xmlChildNodes = null;
+            IList<XmlAttribute>? xmlAttributes = null;
+            IList<XmlNode>? xmlChildNodes = null;
 
             XmlNodeType nodeType = xmlReader.MoveToContent();
             if (nodeType != XmlNodeType.Text)
@@ -928,7 +953,7 @@ namespace System.Runtime.Serialization
                     {
                         if (xmlAttributes == null)
                             xmlAttributes = new List<XmlAttribute>();
-                        xmlAttributes.Add((XmlAttribute)Document.ReadNode(xmlReader.UnderlyingReader));
+                        xmlAttributes.Add((XmlAttribute)Document.ReadNode(xmlReader.UnderlyingReader)!);
                     }
                 }
                 Read(xmlReader);
@@ -941,7 +966,7 @@ namespace System.Runtime.Serialization
 
                 if (xmlChildNodes == null)
                     xmlChildNodes = new List<XmlNode>();
-                xmlChildNodes.Add(Document.ReadNode(xmlReader.UnderlyingReader));
+                xmlChildNodes.Add(Document.ReadNode(xmlReader.UnderlyingReader)!);
             }
             xmlReader.ReadEndElement();
 
@@ -954,15 +979,15 @@ namespace System.Runtime.Serialization
         // all items have the same name and namespace. To recognize as an ISerializable type, it requires that all
         // items be unqualified. If the XML only contains elements (no attributes or other nodes) is recognized as a
         // class/class hierarchy. Otherwise it is deserialized as XML.
-        private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDictionary<string, string> namespaces,
-            string dataContractName, string dataContractNamespace)
+        private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDictionary<string, string>? namespaces,
+            string? dataContractName, string? dataContractNamespace)
         {
             bool couldBeISerializableData = true;
             bool couldBeCollectionData = true;
             bool couldBeClassData = true;
-            string elementNs = null, elementName = null;
+            string? elementNs = null, elementName = null;
             var xmlChildNodes = new List<XmlNode>();
-            IList<XmlAttribute> xmlAttributes = null;
+            IList<XmlAttribute>? xmlAttributes = null;
             if (namespaces != null)
             {
                 xmlAttributes = new List<XmlAttribute>();
@@ -1001,15 +1026,15 @@ namespace System.Runtime.Serialization
                 if (_attributesInXmlData == null) _attributesInXmlData = new Attributes();
                 _attributesInXmlData.Read(xmlReader);
 
-                XmlNode childNode = Document.ReadNode(xmlReader.UnderlyingReader);
+                XmlNode childNode = Document.ReadNode(xmlReader.UnderlyingReader)!;
                 xmlChildNodes.Add(childNode);
 
                 if (namespaces == null)
                 {
                     if (_attributesInXmlData.XsiTypeName != null)
-                        childNode.Attributes.Append(AddNamespaceDeclaration(_attributesInXmlData.XsiTypePrefix, _attributesInXmlData.XsiTypeNamespace));
+                        childNode.Attributes!.Append(AddNamespaceDeclaration(_attributesInXmlData.XsiTypePrefix, _attributesInXmlData.XsiTypeNamespace));
                     if (_attributesInXmlData.FactoryTypeName != null)
-                        childNode.Attributes.Append(AddNamespaceDeclaration(_attributesInXmlData.FactoryTypePrefix, _attributesInXmlData.FactoryTypeNamespace));
+                        childNode.Attributes!.Append(AddNamespaceDeclaration(_attributesInXmlData.FactoryTypePrefix, _attributesInXmlData.FactoryTypeNamespace));
                 }
             }
             xmlReader.ReadEndElement();
@@ -1046,7 +1071,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal XmlReaderDelegator CreateReaderOverChildNodes(IList<XmlAttribute> xmlAttributes, IList<XmlNode> xmlChildNodes)
+        internal XmlReaderDelegator CreateReaderOverChildNodes(IList<XmlAttribute>? xmlAttributes, IList<XmlNode> xmlChildNodes)
         {
             XmlNode wrapperElement = CreateWrapperXmlElement(Document, xmlAttributes, xmlChildNodes, null, null, null);
             XmlReaderDelegator nodeReader = CreateReaderDelegatorForReader(new XmlNodeReader(wrapperElement));
@@ -1055,11 +1080,11 @@ namespace System.Runtime.Serialization
             return nodeReader;
         }
 
-        internal static XmlNode CreateWrapperXmlElement(XmlDocument document, IList<XmlAttribute> xmlAttributes, IList<XmlNode> xmlChildNodes, string prefix, string localName, string ns)
+        internal static XmlNode CreateWrapperXmlElement(XmlDocument document, IList<XmlAttribute>? xmlAttributes, IList<XmlNode> xmlChildNodes, string? prefix, string? localName, string? ns)
         {
             localName = localName ?? "wrapper";
             ns = ns ?? string.Empty;
-            XmlNode wrapperElement = document.CreateElement(prefix, localName, ns);
+            XmlElement wrapperElement = document.CreateElement(prefix, localName, ns);
             if (xmlAttributes != null)
             {
                 for (int i = 0; i < xmlAttributes.Count; i++)
@@ -1077,7 +1102,7 @@ namespace System.Runtime.Serialization
             return wrapperElement;
         }
 
-        private XmlAttribute AddNamespaceDeclaration(string prefix, string ns)
+        private XmlAttribute AddNamespaceDeclaration(string? prefix, string? ns)
         {
             XmlAttribute attribute = (prefix == null || prefix.Length == 0) ?
                 Document.CreateAttribute(null, Globals.XmlnsPrefix, Globals.XmlnsNamespace) :
@@ -1105,7 +1130,7 @@ namespace System.Runtime.Serialization
             return XmlObjectSerializer.CreateSerializationException(message);
         }
 
-        protected virtual object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
+        protected virtual object? ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
         {
             return dataContract.ReadXmlValue(reader, this);
         }
@@ -1117,6 +1142,8 @@ namespace System.Runtime.Serialization
 
         protected virtual bool IsReadingCollectionExtensionData(XmlReaderDelegator xmlReader)
         {
+            Debug.Assert(attributes != null);
+
             return (attributes.ArraySZSize != -1);
         }
 
index 9727b00..6531828 100644 (file)
@@ -1,6 +1,7 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System.Diagnostics;
 using System.Reflection;
 
 namespace System.Runtime.Serialization
@@ -9,9 +10,9 @@ namespace System.Runtime.Serialization
     {
         private readonly bool _preserveObjectReferences;
         private readonly SerializationMode _mode;
-        private readonly ISerializationSurrogateProvider _serializationSurrogateProvider;
+        private readonly ISerializationSurrogateProvider? _serializationSurrogateProvider;
 
-        internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
+        internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? dataContractResolver)
             : base(serializer, rootTypeDataContract, dataContractResolver)
         {
             _mode = SerializationMode.SharedContract;
@@ -29,7 +30,7 @@ namespace System.Runtime.Serialization
             get { return _mode; }
         }
 
-        internal override object InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
+        internal override object? InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
         {
             if (_mode == SerializationMode.SharedContract)
             {
@@ -44,7 +45,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns)
+        internal override object? InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns)
         {
             if (_mode == SerializationMode.SharedContract)
             {
@@ -59,7 +60,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns)
+        internal override object? InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract? dataContract, string? name, string? ns)
         {
             if (_mode == SerializationMode.SharedContract)
             {
@@ -74,27 +75,31 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns)
+        private object? InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string? name, string? ns)
         {
-            object retObj = null;
+            Debug.Assert(attributes != null);
+
+            object? retObj = null;
             if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj))
                 return retObj;
 
             DataContract dataContract;
-            string assemblyName = attributes.ClrAssembly;
-            string typeName = attributes.ClrType;
+            string? assemblyName = attributes.ClrAssembly;
+            string? typeName = attributes.ClrType;
             if (assemblyName != null && typeName != null)
             {
                 Assembly assembly;
                 Type type;
-                dataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type);
-                if (dataContract == null)
+                DataContract? tempDataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type);
+                if (tempDataContract == null)
                 {
                     if (assembly == null)
                         throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.AssemblyNotFound, assemblyName));
-                    if (type == null)
-                        throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ClrTypeNotFound, assembly.FullName, typeName));
+
+                    throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ClrTypeNotFound, assembly.FullName, typeName));
                 }
+
+                dataContract = tempDataContract;
                 //Array covariance is not supported in XSD. If declared type is array, data is sent in format of base array
                 if (declaredType != null && declaredType.IsArray)
                     dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
@@ -112,8 +117,10 @@ namespace System.Runtime.Serialization
             return ReadDataContractValue(dataContract, xmlReader);
         }
 
-        private object InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, string name, string ns)
+        private object? InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract? surrogateDataContract, string? name, string? ns)
         {
+            Debug.Assert(_serializationSurrogateProvider != null);
+
             DataContract dataContract = surrogateDataContract ??
                 GetDataContract(DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, declaredType));
             if (this.IsGetOnlyCollection && dataContract.UnderlyingType != declaredType)
@@ -122,8 +129,8 @@ namespace System.Runtime.Serialization
             }
             ReadAttributes(xmlReader);
             string objectId = GetObjectId();
-            object oldObj = InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract);
-            object obj = DataContractSurrogateCaller.GetDeserializedObject(_serializationSurrogateProvider, oldObj, dataContract.UnderlyingType, declaredType);
+            object? oldObj = InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract);
+            object? obj = DataContractSurrogateCaller.GetDeserializedObject(_serializationSurrogateProvider, oldObj, dataContract.UnderlyingType, declaredType);
             ReplaceDeserializedObject(objectId, oldObj, obj);
 
             return obj;
@@ -136,7 +143,7 @@ namespace System.Runtime.Serialization
             throw new PlatformNotSupportedException(SR.PlatformNotSupported_NetDataContractSerializer);
         }
 
-        private DataContract ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type)
+        private DataContract? ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type)
         {
             type = ResolveDataContractTypeInSharedTypeMode(assemblyName, typeName, out assembly);
             if (type != null)
@@ -147,8 +154,10 @@ namespace System.Runtime.Serialization
             return null;
         }
 
-        protected override DataContract ResolveDataContractFromTypeName()
+        protected override DataContract? ResolveDataContractFromTypeName()
         {
+            Debug.Assert(attributes != null);
+
             if (_mode == SerializationMode.SharedContract)
             {
                 return base.ResolveDataContractFromTypeName();
@@ -170,7 +179,7 @@ namespace System.Runtime.Serialization
             if (_serializationSurrogateProvider != null)
             {
                 while (memberType.IsArray)
-                    memberType = memberType.GetElementType();
+                    memberType = memberType.GetElementType()!;
                 memberType = DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, memberType);
                 if (!DataContract.IsTypeSerializable(memberType))
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TypeNotSerializable, memberType)));
@@ -208,6 +217,8 @@ namespace System.Runtime.Serialization
         internal override int GetArraySize()
 #endif
         {
+            Debug.Assert(attributes != null);
+
             return _preserveObjectReferences ? attributes.ArraySZSize : -1;
         }
     }
index 6f62f39..1c1948c 100644 (file)
@@ -14,6 +14,7 @@ using System.Xml.Serialization;
 using System.Security;
 using System.Runtime.CompilerServices;
 using ExtensionDataObject = System.Object;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization
 {
@@ -24,22 +25,22 @@ namespace System.Runtime.Serialization
 #endif
     {
         private ObjectReferenceStack _byValObjectsInScope;
-        private XmlSerializableWriter _xmlSerializableWriter;
+        private XmlSerializableWriter? _xmlSerializableWriter;
         private const int depthToCheckCyclicReference = 512;
-        private ObjectToIdCache _serializedObjects;
+        private ObjectToIdCache? _serializedObjects;
         private bool _isGetOnlyCollection;
         private readonly bool _unsafeTypeForwardingEnabled;
         protected bool serializeReadOnlyTypes;
         protected bool preserveObjectReferences;
 
-        internal static XmlObjectSerializerWriteContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
+        internal static XmlObjectSerializerWriteContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? dataContractResolver)
         {
             return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null)
                 ? new XmlObjectSerializerWriteContextComplex(serializer, rootTypeDataContract, dataContractResolver)
                 : new XmlObjectSerializerWriteContext(serializer, rootTypeDataContract, dataContractResolver);
         }
 
-        protected XmlObjectSerializerWriteContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver resolver)
+        protected XmlObjectSerializerWriteContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? resolver)
             : base(serializer, rootTypeDataContract, resolver)
         {
             this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes;
@@ -160,6 +161,8 @@ namespace System.Runtime.Serialization
 
         internal virtual void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
         {
+            Debug.Assert(rootTypeDataContract != null);
+
             bool verifyKnownType = false;
             Type declaredType = rootTypeDataContract.UnderlyingType;
 
@@ -177,7 +180,7 @@ namespace System.Runtime.Serialization
             SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, originalDeclaredTypeHandle, declaredType);
         }
 
-        protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
+        protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type? objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
         {
             bool verifyKnownType = false;
             DataContract dataContract;
@@ -256,7 +259,7 @@ namespace System.Runtime.Serialization
             {
                 if (!IsKnownType(dataContract, declaredType))
                 {
-                    DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/, declaredType);
+                    DataContract? knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/, declaredType);
                     if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType)
                     {
                         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
@@ -282,7 +285,7 @@ namespace System.Runtime.Serialization
             return false;
         }
 
-        internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName)
+        internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string? clrTypeName, string? clrAssemblyName)
         {
             return false;
         }
@@ -310,9 +313,9 @@ namespace System.Runtime.Serialization
             xmlWriter.WriteString(value);
         }
 #if USE_REFEMIT
-        public virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns)
+        public virtual void WriteString(XmlWriterDelegator xmlWriter, string? value, XmlDictionaryString name, XmlDictionaryString ns)
 #else
-        internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal virtual void WriteString(XmlWriterDelegator xmlWriter, string? value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             if (value == null)
@@ -382,9 +385,9 @@ namespace System.Runtime.Serialization
             xmlWriter.WriteQName(value);
         }
 #if USE_REFEMIT
-        public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns)
+        public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName? value, XmlDictionaryString name, XmlDictionaryString ns)
 #else
-        internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName? value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             if (value == null)
@@ -444,7 +447,7 @@ namespace System.Runtime.Serialization
             WriteNull(xmlWriter);
         }
 
-        internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable, XmlDictionaryString name, XmlDictionaryString? ns)
         {
             xmlWriter.WriteStartElement(name, ns);
             WriteNull(xmlWriter, memberType, isMemberTypeSerializable);
@@ -506,7 +509,7 @@ namespace System.Runtime.Serialization
         internal static T GetDefaultValue<T>()
 #endif
         {
-            return default(T);
+            return default(T)!;
         }
 
 #if USE_REFEMIT
@@ -516,7 +519,7 @@ namespace System.Runtime.Serialization
 #endif
         {
             // value.Value will throw if hasValue is false
-            return value.Value;
+            return value!.Value;
         }
 
 #if USE_REFEMIT
@@ -552,17 +555,17 @@ namespace System.Runtime.Serialization
         private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj, XmlSerializableWriter xmlSerializableWriter)
         {
             xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj);
-            IXmlSerializable xmlSerializable = obj as IXmlSerializable;
+            IXmlSerializable? xmlSerializable = obj as IXmlSerializable;
             if (xmlSerializable != null)
                 xmlSerializable.WriteXml(xmlSerializableWriter);
             else
             {
-                XmlElement xmlElement = obj as XmlElement;
+                XmlElement? xmlElement = obj as XmlElement;
                 if (xmlElement != null)
                     xmlElement.WriteTo(xmlSerializableWriter);
                 else
                 {
-                    XmlNode[] xmlNodes = obj as XmlNode[];
+                    XmlNode[]? xmlNodes = obj as XmlNode[];
                     if (xmlNodes != null)
                         foreach (XmlNode xmlNode in xmlNodes)
                             xmlNode.WriteTo(xmlSerializableWriter);
@@ -600,7 +603,7 @@ namespace System.Runtime.Serialization
             {
                 if (DataContractResolver != null)
                 {
-                    XmlDictionaryString typeName, typeNs;
+                    XmlDictionaryString? typeName, typeNs;
                     if (ResolveType(serInfo.ObjectType, objType, out typeName, out typeNs))
                     {
                         xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, typeName, typeNs);
@@ -620,7 +623,7 @@ namespace System.Runtime.Serialization
             {
                 XmlDictionaryString name = DataContract.GetClrTypeString(DataContract.EncodeLocalName(serEntry.Name));
                 xmlWriter.WriteStartElement(name, DictionaryGlobals.EmptyString);
-                object obj = serEntry.Value;
+                object? obj = serEntry.Value;
                 if (obj == null)
                 {
                     WriteNull(xmlWriter);
@@ -646,15 +649,17 @@ namespace System.Runtime.Serialization
 
         private void WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType)
         {
-            XmlDictionaryString typeName, typeNamespace;
+            XmlDictionaryString? typeName, typeNamespace;
             if (ResolveType(objectType, declaredType, out typeName, out typeNamespace))
             {
                 WriteTypeInfo(writer, typeName, typeNamespace);
             }
         }
 
-        private bool ResolveType(Type objectType, Type declaredType, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
+        private bool ResolveType(Type objectType, Type declaredType, [NotNullWhen(true)] out XmlDictionaryString? typeName, [NotNullWhen(true)] out XmlDictionaryString? typeNamespace)
         {
+            Debug.Assert(DataContractResolver != null);
+
             if (!DataContractResolver.TryResolveType(objectType, declaredType, KnownTypeResolver, out typeName, out typeNamespace))
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedFalse, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
@@ -695,7 +700,7 @@ namespace System.Runtime.Serialization
             return false;
         }
 
-        protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace)
+        protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string? dataContractNamespace)
         {
             writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace);
         }
@@ -705,17 +710,17 @@ namespace System.Runtime.Serialization
             writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace);
         }
 
-        public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject extensionData, int memberIndex)
+        public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject? extensionData, int memberIndex)
         {
             if (IgnoreExtensionDataObject || extensionData == null)
                 return;
 
-            IList<ExtensionDataMember> members = extensionData.Members;
+            IList<ExtensionDataMember>? members = extensionData.Members;
             if (members != null)
             {
-                for (int i = 0; i < extensionData.Members.Count; i++)
+                for (int i = 0; i < members.Count; i++)
                 {
-                    ExtensionDataMember member = extensionData.Members[i];
+                    ExtensionDataMember member = members[i];
                     if (member.MemberIndex == memberIndex)
                     {
                         WriteExtensionDataMember(xmlWriter, member);
@@ -727,7 +732,7 @@ namespace System.Runtime.Serialization
         private void WriteExtensionDataMember(XmlWriterDelegator xmlWriter, ExtensionDataMember member)
         {
             xmlWriter.WriteStartElement(member.Name, member.Namespace);
-            IDataNode dataNode = member.Value;
+            IDataNode? dataNode = member.Value;
             WriteExtensionDataValue(xmlWriter, dataNode);
             xmlWriter.WriteEndElement();
         }
@@ -740,7 +745,7 @@ namespace System.Runtime.Serialization
             WriteClrTypeInfo(xmlWriter, dataNode.DataType, dataNode.ClrTypeName, dataNode.ClrAssemblyName);
         }
 
-        internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode dataNode)
+        internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode? dataNode)
         {
             IncrementItemCount(1);
             if (dataNode == null)
@@ -770,7 +775,7 @@ namespace System.Runtime.Serialization
                 {
                     // NOTE: serialize value in DataNode<object> since it may contain non-primitive
                     // deserialized object (ex. empty class)
-                    object o = dataNode.Value;
+                    object? o = dataNode.Value;
                     if (o != null)
                         InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, o.GetType().TypeHandle);
                 }
@@ -783,7 +788,7 @@ namespace System.Runtime.Serialization
 
         internal bool TryWriteDeserializedExtensionData(XmlWriterDelegator xmlWriter, IDataNode dataNode)
         {
-            object o = dataNode.Value;
+            object? o = dataNode.Value;
             if (o == null)
                 return false;
 
@@ -798,7 +803,7 @@ namespace System.Runtime.Serialization
             {
                 WriteExtensionDataTypeInfo(xmlWriter, dataNode);
 
-                IList<ExtensionDataMember> members = dataNode.Members;
+                IList<ExtensionDataMember>? members = dataNode.Members;
                 if (members != null)
                 {
                     for (int i = 0; i < members.Count; i++)
@@ -817,12 +822,12 @@ namespace System.Runtime.Serialization
 
                 WriteArraySize(xmlWriter, dataNode.Size);
 
-                IList<IDataNode> items = dataNode.Items;
+                IList<IDataNode?>? items = dataNode.Items;
                 if (items != null)
                 {
                     for (int i = 0; i < items.Count; i++)
                     {
-                        xmlWriter.WriteStartElement(dataNode.ItemName, dataNode.ItemNamespace);
+                        xmlWriter.WriteStartElement(dataNode.ItemName!, dataNode.ItemNamespace);
                         WriteExtensionDataValue(xmlWriter, items[i]);
                         xmlWriter.WriteEndElement();
                     }
@@ -839,7 +844,7 @@ namespace System.Runtime.Serialization
                 if (dataNode.FactoryTypeName != null)
                     xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, dataNode.FactoryTypeName, dataNode.FactoryTypeNamespace);
 
-                IList<ISerializableDataMember> members = dataNode.Members;
+                IList<ISerializableDataMember>? members = dataNode.Members;
                 if (members != null)
                 {
                     for (int i = 0; i < members.Count; i++)
@@ -857,7 +862,7 @@ namespace System.Runtime.Serialization
         {
             if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode))
             {
-                IList<XmlAttribute> xmlAttributes = dataNode.XmlAttributes;
+                IList<XmlAttribute>? xmlAttributes = dataNode.XmlAttributes;
                 if (xmlAttributes != null)
                 {
                     foreach (XmlAttribute attribute in xmlAttributes)
@@ -865,7 +870,7 @@ namespace System.Runtime.Serialization
                 }
                 WriteExtensionDataTypeInfo(xmlWriter, dataNode);
 
-                IList<XmlNode> xmlChildNodes = dataNode.XmlChildNodes;
+                IList<XmlNode>? xmlChildNodes = dataNode.XmlChildNodes;
                 if (xmlChildNodes != null)
                 {
                     foreach (XmlNode node in xmlChildNodes)
index ce64b62..cac1276 100644 (file)
@@ -21,10 +21,10 @@ namespace System.Runtime.Serialization
     internal class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteContext
 #endif
     {
-        private readonly ISerializationSurrogateProvider _serializationSurrogateProvider;
+        private readonly ISerializationSurrogateProvider? _serializationSurrogateProvider;
         private readonly SerializationMode _mode;
 
-        internal XmlObjectSerializerWriteContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
+        internal XmlObjectSerializerWriteContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? dataContractResolver)
             : base(serializer, rootTypeDataContract, dataContractResolver)
         {
             _mode = SerializationMode.SharedContract;
@@ -47,7 +47,7 @@ namespace System.Runtime.Serialization
             return false;
         }
 
-        internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName)
+        internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string? clrTypeName, string? clrAssemblyName)
         {
             return false;
         }
@@ -64,7 +64,7 @@ namespace System.Runtime.Serialization
                 xmlWriter.WriteString(value);
         }
 
-        internal override void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal override void WriteString(XmlWriterDelegator xmlWriter, string? value, XmlDictionaryString name, XmlDictionaryString? ns)
         {
             if (value == null)
                 WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns);
@@ -121,7 +121,7 @@ namespace System.Runtime.Serialization
                 xmlWriter.WriteQName(value);
         }
 
-        internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName? value, XmlDictionaryString name, XmlDictionaryString? ns)
         {
             if (value == null)
                 WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns);
@@ -179,7 +179,7 @@ namespace System.Runtime.Serialization
             if (_serializationSurrogateProvider != null)
             {
                 while (memberType.IsArray)
-                    memberType = memberType.GetElementType();
+                    memberType = memberType.GetElementType()!;
                 memberType = DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, memberType);
                 if (!DataContract.IsTypeSerializable(memberType))
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TypeNotSerializable, memberType)));
@@ -221,7 +221,7 @@ namespace System.Runtime.Serialization
 
             declaredTypeHandle = declaredType.TypeHandle;
 
-            obj = DataContractSerializer.SurrogateToDataContractType(_serializationSurrogateProvider, obj, declaredType, ref objType);
+            obj = DataContractSerializer.SurrogateToDataContractType(_serializationSurrogateProvider!, obj, declaredType, ref objType);
             objTypeHandle = objType.TypeHandle;
             if (oldObj != obj)
                 objOldId = SerializedObjects.ReassignId(0, oldObj, obj);
index 5faa2ee..ca5b54d 100644 (file)
@@ -5,7 +5,7 @@ using System.Xml;
 using System.Globalization;
 using System.Collections.Generic;
 using System.Xml.Serialization;
-
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization
 {
@@ -16,7 +16,7 @@ namespace System.Runtime.Serialization
 #endif
     {
         protected XmlReader reader;
-        protected XmlDictionaryReader dictionaryReader;
+        protected XmlDictionaryReader? dictionaryReader;
         protected bool isEndOfEmptyElement;
 
         public XmlReaderDelegator(XmlReader reader)
@@ -31,7 +31,7 @@ namespace System.Runtime.Serialization
             get { return reader; }
         }
 
-        internal ExtensionDataReader UnderlyingExtensionDataReader
+        internal ExtensionDataReader? UnderlyingExtensionDataReader
         {
             get { return reader as ExtensionDataReader; }
         }
@@ -41,12 +41,12 @@ namespace System.Runtime.Serialization
             get { return isEndOfEmptyElement ? 0 : reader.AttributeCount; }
         }
 
-        internal string GetAttribute(string name)
+        internal string? GetAttribute(string name)
         {
             return isEndOfEmptyElement ? null : reader.GetAttribute(name);
         }
 
-        internal string GetAttribute(string name, string namespaceUri)
+        internal string? GetAttribute(string name, string namespaceUri)
         {
             return isEndOfEmptyElement ? null : reader.GetAttribute(name, namespaceUri);
         }
@@ -349,11 +349,13 @@ namespace System.Runtime.Serialization
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType));
         }
 
+        [DoesNotReturn]
         private void ThrowConversionException(string value, string type)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, type))));
         }
 
+        [DoesNotReturn]
         private void ThrowNotAtElement()
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement")));
@@ -513,7 +515,8 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal byte[] ReadContentAsBase64(string str)
+        [return: NotNullIfNotNull("str")]
+        internal byte[]? ReadContentAsBase64(string? str)
         {
             if (str == null)
                 return null;
@@ -869,7 +872,8 @@ namespace System.Runtime.Serialization
 
         private XmlQualifiedName ParseQualifiedName(string str)
         {
-            string name, ns, prefix;
+            string name, prefix;
+            string? ns;
             if (str == null || str.Length == 0)
                 name = ns = string.Empty;
             else
@@ -899,7 +903,7 @@ namespace System.Runtime.Serialization
         internal bool TryReadBooleanArray(XmlObjectSerializerReadContext context,
 #endif
             XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
-            int arrayLength, out bool[] array)
+            int arrayLength, [NotNullWhen(true)] out bool[]? array)
         {
             if (dictionaryReader == null)
             {
@@ -933,7 +937,7 @@ namespace System.Runtime.Serialization
         internal virtual bool TryReadDateTimeArray(XmlObjectSerializerReadContext context,
 #endif
             XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
-            int arrayLength, out DateTime[] array)
+            int arrayLength, [NotNullWhen(true)] out DateTime[]? array)
         {
             if (dictionaryReader == null)
             {
@@ -967,7 +971,7 @@ namespace System.Runtime.Serialization
         internal bool TryReadDecimalArray(XmlObjectSerializerReadContext context,
 #endif
             XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
-            int arrayLength, out decimal[] array)
+            int arrayLength, [NotNullWhen(true)] out decimal[]? array)
         {
             if (dictionaryReader == null)
             {
@@ -1001,7 +1005,7 @@ namespace System.Runtime.Serialization
         internal bool TryReadInt32Array(XmlObjectSerializerReadContext context,
 #endif
             XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
-            int arrayLength, out int[] array)
+            int arrayLength, [NotNullWhen(true)] out int[]? array)
         {
             if (dictionaryReader == null)
             {
@@ -1035,7 +1039,7 @@ namespace System.Runtime.Serialization
         internal bool TryReadInt64Array(XmlObjectSerializerReadContext context,
 #endif
             XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
-            int arrayLength, out long[] array)
+            int arrayLength, [NotNullWhen(true)] out long[]? array)
         {
             if (dictionaryReader == null)
             {
@@ -1069,7 +1073,7 @@ namespace System.Runtime.Serialization
         internal bool TryReadSingleArray(XmlObjectSerializerReadContext context,
 #endif
         XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
-            int arrayLength, out float[] array)
+            int arrayLength, [NotNullWhen(true)] out float[]? array)
         {
             if (dictionaryReader == null)
             {
@@ -1103,7 +1107,7 @@ namespace System.Runtime.Serialization
         internal bool TryReadDoubleArray(XmlObjectSerializerReadContext context,
 #endif
             XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
-            int arrayLength, out double[] array)
+            int arrayLength, [NotNullWhen(true)] out double[]? array)
         {
             if (dictionaryReader == null)
             {
@@ -1131,7 +1135,7 @@ namespace System.Runtime.Serialization
             return true;
         }
 
-        internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
+        internal IDictionary<string, string>? GetNamespacesInScope(XmlNamespaceScope scope)
         {
             return (reader is IXmlNamespaceResolver) ? ((IXmlNamespaceResolver)reader).GetNamespacesInScope(scope) : null;
         }
@@ -1139,7 +1143,7 @@ namespace System.Runtime.Serialization
         // IXmlLineInfo members
         internal bool HasLineInfo()
         {
-            IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo;
+            IXmlLineInfo? iXmlLineInfo = reader as IXmlLineInfo;
             return (iXmlLineInfo == null) ? false : iXmlLineInfo.HasLineInfo();
         }
 
@@ -1147,7 +1151,7 @@ namespace System.Runtime.Serialization
         {
             get
             {
-                IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo;
+                IXmlLineInfo? iXmlLineInfo = reader as IXmlLineInfo;
                 return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LineNumber;
             }
         }
@@ -1156,7 +1160,7 @@ namespace System.Runtime.Serialization
         {
             get
             {
-                IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo;
+                IXmlLineInfo? iXmlLineInfo = reader as IXmlLineInfo;
                 return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LinePosition;
             }
         }
@@ -1166,10 +1170,10 @@ namespace System.Runtime.Serialization
         {
             get
             {
-                XmlTextReader xmlTextReader = reader as XmlTextReader;
+                XmlTextReader? xmlTextReader = reader as XmlTextReader;
                 if (xmlTextReader == null)
                 {
-                    IXmlTextParser xmlTextParser = reader as IXmlTextParser;
+                    IXmlTextParser? xmlTextParser = reader as IXmlTextParser;
                     return (xmlTextParser == null) ? false : xmlTextParser.Normalized;
                 }
                 else
@@ -1177,10 +1181,10 @@ namespace System.Runtime.Serialization
             }
             set
             {
-                XmlTextReader xmlTextReader = reader as XmlTextReader;
+                XmlTextReader? xmlTextReader = reader as XmlTextReader;
                 if (xmlTextReader == null)
                 {
-                    IXmlTextParser xmlTextParser = reader as IXmlTextParser;
+                    IXmlTextParser? xmlTextParser = reader as IXmlTextParser;
                     if (xmlTextParser != null)
                         xmlTextParser.Normalized = value;
                 }
@@ -1193,10 +1197,10 @@ namespace System.Runtime.Serialization
         {
             get
             {
-                XmlTextReader xmlTextReader = reader as XmlTextReader;
+                XmlTextReader? xmlTextReader = reader as XmlTextReader;
                 if (xmlTextReader == null)
                 {
-                    IXmlTextParser xmlTextParser = reader as IXmlTextParser;
+                    IXmlTextParser? xmlTextParser = reader as IXmlTextParser;
                     return (xmlTextParser == null) ? WhitespaceHandling.None : xmlTextParser.WhitespaceHandling;
                 }
                 else
@@ -1204,10 +1208,10 @@ namespace System.Runtime.Serialization
             }
             set
             {
-                XmlTextReader xmlTextReader = reader as XmlTextReader;
+                XmlTextReader? xmlTextReader = reader as XmlTextReader;
                 if (xmlTextReader == null)
                 {
-                    IXmlTextParser xmlTextParser = reader as IXmlTextParser;
+                    IXmlTextParser? xmlTextParser = reader as IXmlTextParser;
                     if (xmlTextParser != null)
                         xmlTextParser.WhitespaceHandling = value;
                 }
@@ -1223,7 +1227,7 @@ namespace System.Runtime.Serialization
         internal string Value { get { return reader.Value; } }
         internal Type ValueType { get { return reader.ValueType; } }
         internal int Depth { get { return reader.Depth; } }
-        internal string LookupNamespace(string prefix) { return reader.LookupNamespace(prefix); }
+        internal string? LookupNamespace(string prefix) { return reader.LookupNamespace(prefix); }
         internal bool EOF { get { return reader.EOF; } }
 
         internal void Skip()
index 9356e76..a8a259e 100644 (file)
@@ -12,10 +12,10 @@ namespace System.Runtime.Serialization
 {
     internal class XmlSerializableReader : XmlReader, IXmlLineInfo
     {
-        private XmlReaderDelegator _xmlReader;
+        private XmlReaderDelegator _xmlReader = null!; // initialized in BeginRead
         private int _startDepth;
         private bool _isRootEmptyElement;
-        private XmlReader _innerReader;
+        private XmlReader _innerReader = null!; // initialized in BeginRead
 
         private XmlReader InnerReader
         {
@@ -67,7 +67,7 @@ namespace System.Runtime.Serialization
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.IXmlSerializableIllegalOperation));
         }
 
-        public override XmlReaderSettings Settings { get { return InnerReader.Settings; } }
+        public override XmlReaderSettings? Settings { get { return InnerReader.Settings; } }
         public override XmlNodeType NodeType { get { return InnerReader.NodeType; } }
         public override string Name { get { return InnerReader.Name; } }
         public override string LocalName { get { return InnerReader.LocalName; } }
@@ -76,7 +76,7 @@ namespace System.Runtime.Serialization
         public override bool HasValue { get { return InnerReader.HasValue; } }
         public override string Value { get { return InnerReader.Value; } }
         public override int Depth { get { return InnerReader.Depth; } }
-        public override string BaseURI { get { return InnerReader.BaseURI; } }
+        public override string? BaseURI { get { return InnerReader.BaseURI; } }
         public override bool IsEmptyElement { get { return InnerReader.IsEmptyElement; } }
         public override bool IsDefault { get { return InnerReader.IsDefault; } }
         public override XmlSpace XmlSpace { get { return InnerReader.XmlSpace; } }
@@ -84,8 +84,9 @@ namespace System.Runtime.Serialization
         public override Type ValueType { get { return InnerReader.ValueType; } }
         public override int AttributeCount { get { return InnerReader.AttributeCount; } }
         public override string this[int i] { get { return InnerReader[i]; } }
-        public override string this[string name] { get { return InnerReader[name]; } }
-        public override string this[string name, string namespaceURI] { get { return InnerReader[name, namespaceURI]; } }
+        public override string? this[string name] { get { return InnerReader[name]; } }
+        // TODO-NULLABLE - unnecessary namespaceURI! - https://github.com/dotnet/roslyn/issues/47221
+        public override string? this[string name, string? namespaceURI] { get { return InnerReader[name, namespaceURI!]; } }
         public override bool EOF { get { return InnerReader.EOF; } }
         public override ReadState ReadState { get { return InnerReader.ReadState; } }
         public override XmlNameTable NameTable { get { return InnerReader.NameTable; } }
@@ -94,16 +95,16 @@ namespace System.Runtime.Serialization
         public override bool CanReadValueChunk { get { return InnerReader.CanReadValueChunk; } }
         public override bool HasAttributes { get { return InnerReader.HasAttributes; } }
 
-        public override string GetAttribute(string name) { return InnerReader.GetAttribute(name); }
-        public override string GetAttribute(string name, string namespaceURI) { return InnerReader.GetAttribute(name, namespaceURI); }
+        public override string? GetAttribute(string name) { return InnerReader.GetAttribute(name); }
+        public override string? GetAttribute(string name, string? namespaceURI) { return InnerReader.GetAttribute(name, namespaceURI); }
         public override string GetAttribute(int i) { return InnerReader.GetAttribute(i); }
         public override bool MoveToAttribute(string name) { return InnerReader.MoveToAttribute(name); }
-        public override bool MoveToAttribute(string name, string ns) { return InnerReader.MoveToAttribute(name, ns); }
+        public override bool MoveToAttribute(string name, string? ns) { return InnerReader.MoveToAttribute(name, ns); }
         public override void MoveToAttribute(int i) { InnerReader.MoveToAttribute(i); }
         public override bool MoveToFirstAttribute() { return InnerReader.MoveToFirstAttribute(); }
         public override bool MoveToNextAttribute() { return InnerReader.MoveToNextAttribute(); }
         public override bool MoveToElement() { return InnerReader.MoveToElement(); }
-        public override string LookupNamespace(string prefix) { return InnerReader.LookupNamespace(prefix); }
+        public override string? LookupNamespace(string prefix) { return InnerReader.LookupNamespace(prefix); }
         public override bool ReadAttributeValue() { return InnerReader.ReadAttributeValue(); }
         public override void ResolveEntity() { InnerReader.ResolveEntity(); }
         public override bool IsStartElement() { return InnerReader.IsStartElement(); }
@@ -118,14 +119,14 @@ namespace System.Runtime.Serialization
         public override int ReadContentAsInt() { return InnerReader.ReadContentAsInt(); }
         public override long ReadContentAsLong() { return InnerReader.ReadContentAsLong(); }
         public override string ReadContentAsString() { return InnerReader.ReadContentAsString(); }
-        public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { return InnerReader.ReadContentAs(returnType, namespaceResolver); }
+        public override object ReadContentAs(Type returnType, IXmlNamespaceResolver? namespaceResolver) { return InnerReader.ReadContentAs(returnType, namespaceResolver); }
         public override int ReadContentAsBase64(byte[] buffer, int index, int count) { return InnerReader.ReadContentAsBase64(buffer, index, count); }
         public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { return InnerReader.ReadContentAsBinHex(buffer, index, count); }
         public override int ReadValueChunk(char[] buffer, int index, int count) { return InnerReader.ReadValueChunk(buffer, index, count); }
         // IXmlLineInfo members
         bool IXmlLineInfo.HasLineInfo()
         {
-            IXmlLineInfo xmlLineInfo = InnerReader as IXmlLineInfo;
+            IXmlLineInfo? xmlLineInfo = InnerReader as IXmlLineInfo;
             return (xmlLineInfo == null) ? _xmlReader.HasLineInfo() : xmlLineInfo.HasLineInfo();
         }
 
@@ -133,7 +134,7 @@ namespace System.Runtime.Serialization
         {
             get
             {
-                IXmlLineInfo xmlLineInfo = InnerReader as IXmlLineInfo;
+                IXmlLineInfo? xmlLineInfo = InnerReader as IXmlLineInfo;
                 return (xmlLineInfo == null) ? _xmlReader.LineNumber : xmlLineInfo.LineNumber;
             }
         }
@@ -142,7 +143,7 @@ namespace System.Runtime.Serialization
         {
             get
             {
-                IXmlLineInfo xmlLineInfo = InnerReader as IXmlLineInfo;
+                IXmlLineInfo? xmlLineInfo = InnerReader as IXmlLineInfo;
                 return (xmlLineInfo == null) ? _xmlReader.LinePosition : xmlLineInfo.LinePosition;
             }
         }
index 8779b62..3746d5d 100644 (file)
@@ -21,7 +21,7 @@ namespace System.Runtime.Serialization
                 {
                     if (IsValidAttribute(xmlReader))
                     {
-                        XmlNode node = doc.ReadNode(xmlReader);
+                        XmlNode? node = doc.ReadNode(xmlReader);
                         if (node == null)
                             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile));
                         nodeList.Add(node);
@@ -35,7 +35,7 @@ namespace System.Runtime.Serialization
                 xmlReader.Read();
                 while (xmlReader.Depth > startDepth && xmlReader.NodeType != XmlNodeType.EndElement)
                 {
-                    XmlNode node = doc.ReadNode(xmlReader);
+                    XmlNode? node = doc.ReadNode(xmlReader);
                     if (node == null)
                         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile));
                     nodeList.Add(node);
@@ -52,14 +52,14 @@ namespace System.Runtime.Serialization
                                    xmlReader.LocalName != "xmlns";
         }
 
-        public static void WriteNodes(XmlWriter xmlWriter, XmlNode[] nodes)
+        public static void WriteNodes(XmlWriter xmlWriter, XmlNode?[]? nodes)
         {
             if (xmlWriter == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(xmlWriter));
             if (nodes != null)
                 for (int i = 0; i < nodes.Length; i++)
                     if (nodes[i] != null)
-                        nodes[i].WriteTo(xmlWriter);
+                        nodes[i]!.WriteTo(xmlWriter);
         }
 
         internal static string AddDefaultSchemaMethodName = "AddDefaultSchema";
index 15703f8..f127737 100644 (file)
@@ -9,9 +9,9 @@ namespace System.Runtime.Serialization
 {
     internal class XmlSerializableWriter : XmlWriter
     {
-        private XmlWriter _xmlWriter;
+        private XmlWriter _xmlWriter = null!; // initialized in BeginWrite
         private int _depth;
-        private object _obj;
+        private object? _obj;
 
         internal void BeginWrite(XmlWriter xmlWriter, object obj)
         {
@@ -38,12 +38,12 @@ namespace System.Runtime.Serialization
             if (WriteState == WriteState.Start)
                 _xmlWriter.WriteStartDocument(standalone);
         }
-        public override void WriteDocType(string name, string pubid, string sysid, string subset)
+        public override void WriteDocType(string name, string? pubid, string? sysid, string? subset)
         {
             // XmlSerializer does not write doc type
         }
 
-        public override void WriteStartElement(string prefix, string localName, string ns)
+        public override void WriteStartElement(string? prefix, string localName, string? ns)
         {
             _xmlWriter.WriteStartElement(prefix, localName, ns);
             _depth++;
@@ -70,19 +70,19 @@ namespace System.Runtime.Serialization
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.IXmlSerializableIllegalOperation));
         }
 
-        public override void WriteStartAttribute(string prefix, string localName, string ns)
+        public override void WriteStartAttribute(string? prefix, string localName, string? ns)
         {
             _xmlWriter.WriteStartAttribute(prefix, localName, ns);
         }
 
         public override void WriteEndAttribute() { _xmlWriter.WriteEndAttribute(); }
-        public override void WriteCData(string text) { _xmlWriter.WriteCData(text); }
-        public override void WriteComment(string text) { _xmlWriter.WriteComment(text); }
-        public override void WriteProcessingInstruction(string name, string text) { _xmlWriter.WriteProcessingInstruction(name, text); }
+        public override void WriteCData(string? text) { _xmlWriter.WriteCData(text); }
+        public override void WriteComment(string? text) { _xmlWriter.WriteComment(text); }
+        public override void WriteProcessingInstruction(string name, string? text) { _xmlWriter.WriteProcessingInstruction(name, text); }
         public override void WriteEntityRef(string name) { _xmlWriter.WriteEntityRef(name); }
         public override void WriteCharEntity(char ch) { _xmlWriter.WriteCharEntity(ch); }
-        public override void WriteWhitespace(string ws) { _xmlWriter.WriteWhitespace(ws); }
-        public override void WriteString(string text) { _xmlWriter.WriteString(text); }
+        public override void WriteWhitespace(string? ws) { _xmlWriter.WriteWhitespace(ws); }
+        public override void WriteString(string? text) { _xmlWriter.WriteString(text); }
         public override void WriteSurrogateCharEntity(char lowChar, char highChar) { _xmlWriter.WriteSurrogateCharEntity(lowChar, highChar); }
         public override void WriteChars(char[] buffer, int index, int count) { _xmlWriter.WriteChars(buffer, index, count); }
         public override void WriteRaw(char[] buffer, int index, int count) { _xmlWriter.WriteRaw(buffer, index, count); }
@@ -92,10 +92,10 @@ namespace System.Runtime.Serialization
         public override WriteState WriteState { get { return _xmlWriter.WriteState; } }
         public override void Flush() { _xmlWriter.Flush(); }
         public override void WriteName(string name) { _xmlWriter.WriteName(name); }
-        public override void WriteQualifiedName(string localName, string ns) { _xmlWriter.WriteQualifiedName(localName, ns); }
-        public override string LookupPrefix(string ns) { return _xmlWriter.LookupPrefix(ns); }
+        public override void WriteQualifiedName(string localName, string? ns) { _xmlWriter.WriteQualifiedName(localName, ns); }
+        public override string? LookupPrefix(string ns) { return _xmlWriter.LookupPrefix(ns); }
         public override XmlSpace XmlSpace { get { return _xmlWriter.XmlSpace; } }
-        public override string XmlLang { get { return _xmlWriter.XmlLang; } }
+        public override string? XmlLang { get { return _xmlWriter.XmlLang; } }
         public override void WriteNmToken(string name) { _xmlWriter.WriteNmToken(name); }
     }
 }
index 9422478..cfe9539 100644 (file)
@@ -14,7 +14,7 @@ namespace System.Runtime.Serialization
 #endif
     {
         protected XmlWriter writer;
-        protected XmlDictionaryWriter dictionaryWriter;
+        protected XmlDictionaryWriter? dictionaryWriter;
         internal int depth;
         private int _prefixes;
 
@@ -35,7 +35,7 @@ namespace System.Runtime.Serialization
             writer.Flush();
         }
 
-        internal string LookupPrefix(string ns)
+        internal string? LookupPrefix(string ns)
         {
             return writer.LookupPrefix(ns);
         }
@@ -77,7 +77,7 @@ namespace System.Runtime.Serialization
                 WriteXmlnsAttribute(ns.Value);
         }
 
-        internal void WriteXmlnsAttribute(string ns)
+        internal void WriteXmlnsAttribute(string? ns)
         {
             if (ns != null)
             {
@@ -89,7 +89,7 @@ namespace System.Runtime.Serialization
                         dictionaryWriter.WriteXmlnsAttribute(null, ns);
                     else
                     {
-                        string prefix = writer.LookupPrefix(ns);
+                        string? prefix = writer.LookupPrefix(ns);
                         if (prefix == null)
                         {
                             prefix = string.Format(CultureInfo.InvariantCulture, "d{0}p{1}", depth, _prefixes);
@@ -113,7 +113,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private void WriteStartAttribute(string prefix, string localName, string ns)
+        private void WriteStartAttribute(string? prefix, string localName, string? ns)
         {
             writer.WriteStartAttribute(prefix, localName, ns);
         }
@@ -124,11 +124,11 @@ namespace System.Runtime.Serialization
                 dictionaryWriter.WriteStartAttribute(prefix, localName, namespaceUri);
             else
                 writer.WriteStartAttribute(prefix,
-                    (localName == null ? null : localName.Value),
+                    (localName == null ? null : localName.Value)!,
                     (namespaceUri == null ? null : namespaceUri.Value));
         }
 
-        internal void WriteAttributeString(string prefix, string localName, string ns, string value)
+        internal void WriteAttributeString(string? prefix, string localName, string? ns, string value)
         {
             WriteStartAttribute(prefix, localName, ns);
             WriteAttributeStringValue(value);
@@ -186,7 +186,7 @@ namespace System.Runtime.Serialization
             writer.WriteValue(value);
         }
 
-        internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string name, string ns)
+        internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string name, string? ns)
         {
             WriteXmlnsAttribute(ns);
             WriteStartAttribute(attrPrefix, attrName, attrNs);
@@ -194,7 +194,7 @@ namespace System.Runtime.Serialization
             WriteEndAttribute();
         }
 
-        private void WriteAttributeQualifiedNameValue(string name, string ns)
+        private void WriteAttributeQualifiedNameValue(string name, string? ns)
         {
             writer.WriteQualifiedName(name, ns);
         }
@@ -215,12 +215,12 @@ namespace System.Runtime.Serialization
                 dictionaryWriter.WriteQualifiedName(name, ns);
         }
 
-        internal void WriteStartElement(string localName, string ns)
+        internal void WriteStartElement(string localName, string? ns)
         {
             WriteStartElement(null, localName, ns);
         }
 
-        internal virtual void WriteStartElement(string prefix, string localName, string ns)
+        internal virtual void WriteStartElement(string? prefix, string localName, string? ns)
         {
             writer.WriteStartElement(prefix, localName, ns);
             depth++;
@@ -230,28 +230,28 @@ namespace System.Runtime.Serialization
 #if USE_REFEMIT
         public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
 #else
-        internal void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        internal void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
 #endif
         {
             WriteStartElement(null, localName, namespaceUri);
         }
 
-        internal void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        internal void WriteStartElement(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
             if (dictionaryWriter != null)
                 dictionaryWriter.WriteStartElement(prefix, localName, namespaceUri);
             else
-                writer.WriteStartElement(prefix, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value));
+                writer.WriteStartElement(prefix, (localName == null ? null : localName.Value)!, (namespaceUri == null ? null : namespaceUri.Value));
             depth++;
             _prefixes = 1;
         }
 
-        internal void WriteStartElementPrimitive(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        internal void WriteStartElementPrimitive(XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
             if (dictionaryWriter != null)
                 dictionaryWriter.WriteStartElement(null, localName, namespaceUri);
             else
-                writer.WriteStartElement(null, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value));
+                writer.WriteStartElement(null, (localName == null ? null : localName.Value)!, (namespaceUri == null ? null : namespaceUri.Value));
         }
 
         internal void WriteEndElementPrimitive()
@@ -264,7 +264,7 @@ namespace System.Runtime.Serialization
             get { return writer.WriteState; }
         }
 
-        internal string XmlLang
+        internal string? XmlLang
         {
             get { return writer.XmlLang; }
         }
@@ -427,7 +427,7 @@ namespace System.Runtime.Serialization
                         WriteBase64(((DataNode<byte[]>)dataNode).GetValue());
                     else if (valueType == Globals.TypeOfObject)
                     {
-                        object obj = dataNode.Value;
+                        object? obj = dataNode.Value;
                         if (obj != null)
                             WriteAnyType(obj);
                     }
@@ -460,9 +460,9 @@ namespace System.Runtime.Serialization
             writer.WriteValue(value);
         }
 #if USE_REFEMIT
-        public void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -476,9 +476,9 @@ namespace System.Runtime.Serialization
         }
 
 #if USE_REFEMIT
-        public void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -491,9 +491,9 @@ namespace System.Runtime.Serialization
             writer.WriteValue(value);
         }
 #if USE_REFEMIT
-        public void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -506,9 +506,9 @@ namespace System.Runtime.Serialization
             writer.WriteValue(value);
         }
 #if USE_REFEMIT
-        public void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -521,9 +521,9 @@ namespace System.Runtime.Serialization
             writer.WriteValue(value);
         }
 #if USE_REFEMIT
-        public void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -536,9 +536,9 @@ namespace System.Runtime.Serialization
             writer.WriteValue(value);
         }
 #if USE_REFEMIT
-        public void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -551,9 +551,9 @@ namespace System.Runtime.Serialization
             writer.WriteValue(value);
         }
 #if USE_REFEMIT
-        public void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -561,7 +561,7 @@ namespace System.Runtime.Serialization
             WriteEndElementPrimitive();
         }
 
-        internal virtual void WriteBase64(byte[] bytes)
+        internal virtual void WriteBase64(byte[]? bytes)
         {
             if (bytes == null)
                 return;
@@ -574,9 +574,9 @@ namespace System.Runtime.Serialization
             writer.WriteValue(value);
         }
 #if USE_REFEMIT
-        public void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -589,9 +589,9 @@ namespace System.Runtime.Serialization
             writer.WriteValue(value);
         }
 #if USE_REFEMIT
-        public void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -605,9 +605,9 @@ namespace System.Runtime.Serialization
         }
 #if USE_REFEMIT
         [CLSCompliant(false)]
-        public void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -621,9 +621,9 @@ namespace System.Runtime.Serialization
         }
 #if USE_REFEMIT
         [CLSCompliant(false)]
-        public void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -637,9 +637,9 @@ namespace System.Runtime.Serialization
         }
 #if USE_REFEMIT
         [CLSCompliant(false)]
-        public void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -653,9 +653,9 @@ namespace System.Runtime.Serialization
         }
 #if USE_REFEMIT
         [CLSCompliant(false)]
-        public void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -668,9 +668,9 @@ namespace System.Runtime.Serialization
             writer.WriteValue((int)value);
         }
 #if USE_REFEMIT
-        public void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -683,7 +683,7 @@ namespace System.Runtime.Serialization
             writer.WriteRaw(XmlConvert.ToString(value));
         }
 
-        internal void WriteTimeSpan(char value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteTimeSpan(char value, XmlDictionaryString name, XmlDictionaryString? ns)
         {
             WriteStartElementPrimitive(name, ns);
             writer.WriteRaw(XmlConvert.ToString(value));
@@ -691,9 +691,9 @@ namespace System.Runtime.Serialization
         }
 
 #if USE_REFEMIT
-        public void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -706,9 +706,9 @@ namespace System.Runtime.Serialization
             writer.WriteRaw(value.ToString());
         }
 #if USE_REFEMIT
-        public void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns)
+        public void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString? ns)
 #else
-        internal void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString? ns)
 #endif
         {
             WriteStartElementPrimitive(name, ns);
@@ -716,12 +716,12 @@ namespace System.Runtime.Serialization
             WriteEndElementPrimitive();
         }
 
-        internal void WriteUri(Uri value)
+        internal void WriteUri(Uri? value)
         {
-            writer.WriteString(value.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped));
+            writer.WriteString(value?.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped));
         }
 
-        internal void WriteUri(Uri value, XmlDictionaryString name, XmlDictionaryString ns)
+        internal void WriteUri(Uri? value, XmlDictionaryString name, XmlDictionaryString? ns)
         {
             WriteStartElementPrimitive(name, ns);
             WriteUri(value);
index 11f8494..d240e78 100644 (file)
@@ -12,20 +12,20 @@ namespace System.Runtime.Serialization
 {
     public class XsdDataContractExporter
     {
-        private ExportOptions _options;
-        private XmlSchemaSet _schemas;
-        private DataContractSet _dataContractSet;
+        private ExportOptions? _options;
+        private XmlSchemaSet? _schemas;
+        private DataContractSet? _dataContractSet;
 
         public XsdDataContractExporter()
         {
         }
 
-        public XsdDataContractExporter(XmlSchemaSet schemas)
+        public XsdDataContractExporter(XmlSchemaSet? schemas)
         {
             this._schemas = schemas;
         }
 
-        public ExportOptions Options
+        public ExportOptions? Options
         {
             get { return _options; }
             set { _options = value; }
@@ -79,7 +79,7 @@ namespace System.Runtime.Serialization
 
             TraceExportBegin();
 
-            DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
+            DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
             try
             {
                 foreach (Assembly assembly in assemblies)
@@ -114,7 +114,7 @@ namespace System.Runtime.Serialization
 
             TraceExportBegin();
 
-            DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
+            DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
             try
             {
                 foreach (Type type in types)
@@ -146,7 +146,7 @@ namespace System.Runtime.Serialization
 
             TraceExportBegin();
 
-            DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
+            DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
             try
             {
                 AddType(type);
@@ -172,26 +172,26 @@ namespace System.Runtime.Serialization
             type = GetSurrogatedType(type);
             DataContract dataContract = DataContract.GetDataContract(type);
             DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType);
-            XmlDataContract xmlDataContract = dataContract as XmlDataContract;
+            XmlDataContract? xmlDataContract = dataContract as XmlDataContract;
             if (xmlDataContract != null && xmlDataContract.IsAnonymous)
                 return XmlQualifiedName.Empty;
             return dataContract.StableName;
         }
 
-        public XmlSchemaType GetSchemaType(Type type)
+        public XmlSchemaType? GetSchemaType(Type type)
         {
             if (type == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type)));
             type = GetSurrogatedType(type);
             DataContract dataContract = DataContract.GetDataContract(type);
             DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType);
-            XmlDataContract xmlDataContract = dataContract as XmlDataContract;
+            XmlDataContract? xmlDataContract = dataContract as XmlDataContract;
             if (xmlDataContract != null && xmlDataContract.IsAnonymous)
                 return xmlDataContract.XsdType;
             return null;
         }
 
-        public XmlQualifiedName GetRootElementName(Type type)
+        public XmlQualifiedName? GetRootElementName(Type type)
         {
             if (type == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type)));
@@ -200,7 +200,7 @@ namespace System.Runtime.Serialization
             DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType);
             if (dataContract.HasRoot)
             {
-                return new XmlQualifiedName(dataContract.TopLevelElementName.Value, dataContract.TopLevelElementNamespace.Value);
+                return new XmlQualifiedName(dataContract.TopLevelElementName!.Value, dataContract.TopLevelElementNamespace!.Value);
             }
             else
             {
@@ -261,7 +261,7 @@ namespace System.Runtime.Serialization
             if (assemblies == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(assemblies)));
 
-            DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
+            DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
             try
             {
                 foreach (Assembly assembly in assemblies)
@@ -298,7 +298,7 @@ namespace System.Runtime.Serialization
             if (types == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(types)));
 
-            DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
+            DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
             try
             {
                 foreach (Type type in types)
@@ -332,7 +332,7 @@ namespace System.Runtime.Serialization
             if (type == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type)));
 
-            DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
+            DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet);
             try
             {
                 AddType(type);
index b551e26..76e7640 100644 (file)
@@ -10,8 +10,8 @@ namespace System.Xml
     {
         public TArray[] ReadArray(XmlDictionaryReader reader, TArgument localName, TArgument namespaceUri, int maxArrayLength)
         {
-            TArray[][] arrays = null;
-            TArray[] array = null;
+            TArray[][]? arrays = null;
+            TArray[]? array = null;
             int arrayCount = 0;
             int totalRead = 0;
             int count;
@@ -49,7 +49,7 @@ namespace System.Xml
                 int offset = 0;
                 for (int i = 0; i < arrayCount; i++)
                 {
-                    Array.Copy(arrays[i], 0, newArray, offset, arrays[i].Length);
+                    Array.Copy(arrays![i], 0, newArray, offset, arrays[i].Length);
                     offset += arrays[i].Length;
                 }
                 Array.Copy(array, 0, newArray, offset, totalRead - offset);
index c5f03aa..08416bf 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 using System;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.IO;
 using System.Runtime.Serialization; // For SR
 using System.Text;
@@ -36,21 +38,21 @@ namespace System.Xml
         private static readonly byte[] s_encodingUnicodeBE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'b', (byte)'e' };
 
         private SupportedEncoding _encodingCode;
-        private Encoding _encoding;
-        private readonly Encoder _enc;
-        private readonly Decoder _dec;
+        private Encoding? _encoding;
+        private readonly Encoder? _enc;
+        private readonly Decoder? _dec;
         private readonly bool _isReading;
 
         private readonly Stream _stream;
-        private char[] _chars;
-        private byte[] _bytes;
+        private char[]? _chars;
+        private byte[]? _bytes;
         private int _byteOffset;
         private int _byteCount;
 
         private readonly byte[] _byteBuffer = new byte[1];
 
         // Reading constructor
-        public EncodingStreamWrapper(Stream stream, Encoding encoding)
+        public EncodingStreamWrapper(Stream stream, Encoding? encoding)
         {
             try
             {
@@ -111,6 +113,7 @@ namespace System.Xml
             }
         }
 
+        [MemberNotNull(nameof(_encoding))]
         private void SetReadDocumentEncoding(SupportedEncoding e)
         {
             EnsureBuffers();
@@ -145,7 +148,7 @@ namespace System.Xml
                 _ => throw new XmlException(SR.XmlEncodingNotSupported),
             };
 
-        private static SupportedEncoding GetSupportedEncoding(Encoding encoding)
+        private static SupportedEncoding GetSupportedEncoding(Encoding? encoding)
         {
             if (encoding == null)
                 return SupportedEncoding.None;
@@ -185,6 +188,7 @@ namespace System.Xml
             }
         }
 
+        [MemberNotNull(nameof(_bytes))]
         private SupportedEncoding ReadBOMEncoding(bool notOutOfBand)
         {
             int b1 = _stream.ReadByte();
@@ -279,7 +283,7 @@ namespace System.Xml
             count -= _byteCount;
             while (count > 0)
             {
-                int read = _stream.Read(_bytes, _byteOffset + _byteCount, count);
+                int read = _stream.Read(_bytes!, _byteOffset + _byteCount, count);
                 if (read == 0)
                     break;
 
@@ -288,6 +292,8 @@ namespace System.Xml
             }
         }
 
+        [MemberNotNull(nameof(_bytes))]
+        [MemberNotNull(nameof(_chars))]
         private void EnsureBuffers()
         {
             EnsureByteBuffer();
@@ -295,6 +301,7 @@ namespace System.Xml
                 _chars = new char[BufferLength];
         }
 
+        [MemberNotNull(nameof(_bytes))]
         private void EnsureByteBuffer()
         {
             if (_bytes != null)
@@ -439,7 +446,7 @@ namespace System.Xml
             return ch == (byte)' ' || ch == (byte)'\n' || ch == (byte)'\t' || ch == (byte)'\r';
         }
 
-        internal static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding)
+        internal static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding? encoding)
         {
             if (count < 4)
                 throw new XmlException(SR.UnexpectedEndOfFile);
@@ -600,6 +607,9 @@ namespace System.Xml
                     if (_encodingCode == SupportedEncoding.UTF8)
                         return _stream.Read(buffer, offset, count);
 
+                    Debug.Assert(_bytes != null);
+                    Debug.Assert(_chars != null);
+
                     // No more bytes than can be turned into characters
                     _byteOffset = 0;
                     _byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2);
@@ -612,14 +622,14 @@ namespace System.Xml
                     CleanupCharBreak();
 
                     // Change encoding
-                    int charCount = _encoding.GetChars(_bytes, 0, _byteCount, _chars, 0);
+                    int charCount = _encoding!.GetChars(_bytes, 0, _byteCount, _chars, 0);
                     _byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0);
                 }
 
                 // Give them bytes
                 if (_byteCount < count)
                     count = _byteCount;
-                Buffer.BlockCopy(_bytes, _byteOffset, buffer, offset, count);
+                Buffer.BlockCopy(_bytes!, _byteOffset, buffer, offset, count);
                 _byteOffset += count;
                 _byteCount -= count;
                 return count;
@@ -632,6 +642,8 @@ namespace System.Xml
 
         private void CleanupCharBreak()
         {
+            Debug.Assert(_bytes != null);
+
             int max = _byteOffset + _byteCount;
 
             // Read on 2 byte boundaries
@@ -692,11 +704,14 @@ namespace System.Xml
                 return;
             }
 
+            Debug.Assert(_bytes != null);
+            Debug.Assert(_chars != null);
+
             while (count > 0)
             {
                 int size = _chars.Length < count ? _chars.Length : count;
-                int charCount = _dec.GetChars(buffer, offset, size, _chars, 0, false);
-                _byteCount = _enc.GetBytes(_chars, 0, charCount, _bytes, 0, false);
+                int charCount = _dec!.GetChars(buffer, offset, size, _chars, 0, false);
+                _byteCount = _enc!.GetBytes(_chars, 0, charCount, _bytes, 0, false);
                 _stream.Write(_bytes, 0, _byteCount);
                 offset += size;
                 count -= size;
index 884f4cb..1f1a5bb 100644 (file)
@@ -1,12 +1,14 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System.Diagnostics.CodeAnalysis;
+
 namespace System.Xml
 {
     public interface IXmlDictionary
     {
-        bool TryLookup(string value, out XmlDictionaryString result);
-        bool TryLookup(int key, out XmlDictionaryString result);
-        bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result);
+        bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result);
+        bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? result);
+        bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result);
     }
 }
index ef26d71..92d98ab 100644 (file)
@@ -177,7 +177,7 @@ namespace System.Xml
             return GetString().CompareTo(that.GetString());
         }
 
-        public bool Equals(PrefixHandle prefix2)
+        public bool Equals(PrefixHandle? prefix2)
         {
             if (ReferenceEquals(prefix2, null))
                 return false;
@@ -234,7 +234,7 @@ namespace System.Xml
         {
             return !prefix1.Equals(prefix2);
         }
-        public override bool Equals(object obj)
+        public override bool Equals(object? obj)
         {
             return Equals(obj as PrefixHandle);
         }
index fa9e0b6..3f8fa8b 100644 (file)
@@ -4,7 +4,7 @@
 using System;
 using System.Runtime.Serialization;
 using System.Diagnostics;
-
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
@@ -161,7 +161,7 @@ namespace System.Xml
             }
         }
 
-        public bool TryGetDictionaryString(out XmlDictionaryString value)
+        public bool TryGetDictionaryString([NotNullWhen(true)] out XmlDictionaryString? value)
         {
             if (_type == StringHandleType.Dictionary)
             {
@@ -226,7 +226,7 @@ namespace System.Xml
             return GetString() == _bufferReader.GetString(offset2, length2);
         }
 
-        public bool Equals(StringHandle other)
+        public bool Equals(StringHandle? other)
         {
             if (ReferenceEquals(other, null))
                 return false;
@@ -275,7 +275,7 @@ namespace System.Xml
             else
                 return string.Compare(this.GetString(), that.GetString(), StringComparison.Ordinal);
         }
-        public override bool Equals(object obj)
+        public override bool Equals(object? obj)
         {
             return Equals(obj as StringHandle);
         }
index 07ecd30..95f9aa9 100644 (file)
@@ -7,7 +7,7 @@ namespace System.Xml
     {
         private long _idLow;
         private long _idHigh;
-        private string _s;
+        private string? _s;
         private const int guidLength = 16;
         private const int uuidLength = 45;
 
@@ -310,7 +310,7 @@ namespace System.Xml
             return _s;
         }
 
-        public static bool operator ==(UniqueId id1, UniqueId id2)
+        public static bool operator ==(UniqueId? id1, UniqueId? id2)
         {
             if (object.ReferenceEquals(id1, id2))
                 return true;
@@ -327,12 +327,12 @@ namespace System.Xml
             return id1.ToString() == id2.ToString();
         }
 
-        public static bool operator !=(UniqueId id1, UniqueId id2)
+        public static bool operator !=(UniqueId? id1, UniqueId? id2)
         {
             return !(id1 == id2);
         }
 
-        public override bool Equals(object obj)
+        public override bool Equals(object? obj)
         {
             return this == (obj as UniqueId);
         }
index 01861dd..94a4908 100644 (file)
@@ -5,7 +5,7 @@ using System.Runtime.Serialization;
 using System.Diagnostics;
 using System.Globalization;
 using System.Text;
-
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
@@ -71,7 +71,7 @@ namespace System.Xml
         private ValueHandleType _type;
         private int _offset;
         private int _length;
-        private static Base64Encoding s_base64Encoding;
+        private static Base64Encoding? s_base64Encoding;
         private static readonly string[] s_constStrings = {
                                         "string",
                                         "number",
@@ -818,7 +818,7 @@ namespace System.Xml
             return true;
         }
 
-        public bool TryGetDictionaryString(out XmlDictionaryString value)
+        public bool TryGetDictionaryString([NotNullWhen(true)] out XmlDictionaryString? value)
         {
             if (_type == ValueHandleType.Dictionary)
             {
index b97d8b3..bc1dcea 100644 (file)
@@ -13,7 +13,7 @@ using System.Globalization;
 using System.Runtime.Serialization;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
-
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
@@ -27,43 +27,43 @@ namespace System.Xml
         private readonly XmlBufferReader _bufferReader;
         private XmlNode _node;
         private readonly NamespaceManager _nsMgr;
-        private XmlElementNode[] _elementNodes;
-        private XmlAttributeNode[] _attributeNodes;
+        private XmlElementNode[]? _elementNodes;
+        private XmlAttributeNode[]? _attributeNodes;
         private readonly XmlAtomicTextNode _atomicTextNode;
         private int _depth;
         private int _attributeCount;
         private int _attributeStart;    // Starting index for searching
         private readonly XmlDictionaryReaderQuotas _quotas;
-        private XmlNameTable _nameTable;
-        private XmlDeclarationNode _declarationNode;
-        private XmlComplexTextNode _complexTextNode;
-        private XmlWhitespaceTextNode _whitespaceTextNode;
-        private XmlCDataNode _cdataNode;
-        private XmlCommentNode _commentNode;
+        private XmlNameTable? _nameTable;
+        private XmlDeclarationNode? _declarationNode;
+        private XmlComplexTextNode? _complexTextNode;
+        private XmlWhitespaceTextNode? _whitespaceTextNode;
+        private XmlCDataNode? _cdataNode;
+        private XmlCommentNode? _commentNode;
         private readonly XmlElementNode _rootElementNode;
         private int _attributeIndex;    // Index for iteration
-        private char[] _chars;
-        private string _prefix;
-        private string _localName;
-        private string _ns;
-        private string _value;
+        private char[]? _chars;
+        private string? _prefix;
+        private string? _localName;
+        private string? _ns;
+        private string? _value;
         private int _trailCharCount;
         private int _trailByteCount;
-        private char[] _trailChars;
-        private byte[] _trailBytes;
+        private char[]? _trailChars;
+        private byte[]? _trailBytes;
         private bool _rootElement;
         private bool _readingElement;
-        private AttributeSorter _attributeSorter;
+        private AttributeSorter? _attributeSorter;
         private static readonly XmlInitialNode s_initialNode = new XmlInitialNode(XmlBufferReader.Empty);
         private static readonly XmlEndOfFileNode s_endOfFileNode = new XmlEndOfFileNode(XmlBufferReader.Empty);
         private static readonly XmlClosedNode s_closedNode = new XmlClosedNode(XmlBufferReader.Empty);
-        private static Base64Encoding s_base64Encoding;
-        private static BinHexEncoding s_binHexEncoding;
+        private static Base64Encoding? s_base64Encoding;
+        private static BinHexEncoding? s_binHexEncoding;
         private const string xmlns = "xmlns";
         private const string xml = "xml";
         private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/";
         private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace";
-        private XmlSigningNodeWriter _signingWriter;
+        private XmlSigningNodeWriter? _signingWriter;
         private bool _signing;
 
         protected XmlBaseReader()
@@ -184,7 +184,7 @@ namespace System.Xml
 
         private bool CheckStandalone(int attr)
         {
-            XmlAttributeNode node = _attributeNodes[attr];
+            XmlAttributeNode node = _attributeNodes![attr];
             if (!node.Prefix.IsEmpty)
                 XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlMalformedDecl));
 
@@ -197,9 +197,9 @@ namespace System.Xml
             return true;
         }
 
-        private bool CheckDeclAttribute(int index, string localName, string value, bool checkLower, string valueSR)
+        private bool CheckDeclAttribute(int index, string localName, string? value, bool checkLower, string valueSR)
         {
-            XmlAttributeNode node = _attributeNodes[index];
+            XmlAttributeNode node = _attributeNodes![index];
             if (!node.Prefix.IsEmpty)
                 XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlMalformedDecl));
 
@@ -268,7 +268,7 @@ namespace System.Xml
                 if (_depth == 0)
                     return _rootElementNode;
                 else
-                    return _elementNodes[_depth];
+                    return _elementNodes![_depth];
             }
         }
 
@@ -276,7 +276,7 @@ namespace System.Xml
         {
             if (_depth == 0)
                 XmlExceptionHelper.ThrowInvalidBinaryFormat(this);
-            XmlElementNode elementNode = _elementNodes[_depth];
+            XmlElementNode elementNode = _elementNodes![_depth];
             XmlEndElementNode endElementNode = elementNode.EndElement;
             endElementNode.Namespace = elementNode.Namespace;
             MoveToNode(endElementNode);
@@ -353,7 +353,7 @@ namespace System.Xml
             }
             attributeNode.QNameType = qnameType;
             attributeNode.IsAtomicValue = isAtomicValue;
-            attributeNode.AttributeText.QNameType = qnameType;
+            attributeNode.AttributeText!.QNameType = qnameType;
             attributeNode.AttributeText.IsAtomicValue = isAtomicValue;
             _attributeCount++;
             return attributeNode;
@@ -391,7 +391,7 @@ namespace System.Xml
             _nsMgr.Register(ns);
             XmlAttributeNode attributeNode = AddAttribute(QNameType.Xmlns, false);
             attributeNode.Namespace = ns;
-            attributeNode.AttributeText.Namespace = ns;
+            attributeNode.AttributeText!.Namespace = ns;
             return attributeNode;
         }
 
@@ -466,7 +466,7 @@ namespace System.Xml
             }
         }
 
-        public override string this[string name]
+        public override string? this[string name]
         {
             get
             {
@@ -474,7 +474,7 @@ namespace System.Xml
             }
         }
 
-        public override string this[string localName, string namespaceUri]
+        public override string? this[string localName, string? namespaceUri]
         {
             get
             {
@@ -539,10 +539,10 @@ namespace System.Xml
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative));
             if (index >= _attributeCount)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.OffsetExceedsBufferSize, _attributeCount)));
-            return _attributeNodes[index];
+            return _attributeNodes![index];
         }
 
-        private XmlAttributeNode GetAttributeNode(string name)
+        private XmlAttributeNode? GetAttributeNode(string name)
         {
             if (name == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(name)));
@@ -571,7 +571,7 @@ namespace System.Xml
                 prefix = name.Substring(0, index);
                 localName = name.Substring(index + 1);
             }
-            XmlAttributeNode[] attributeNodes = _attributeNodes;
+            XmlAttributeNode[]? attributeNodes = _attributeNodes;
             int attributeCount = _attributeCount;
             int attributeIndex = _attributeStart;
             for (int i = 0; i < attributeCount; i++)
@@ -580,7 +580,7 @@ namespace System.Xml
                 {
                     attributeIndex = 0;
                 }
-                XmlAttributeNode attributeNode = attributeNodes[attributeIndex];
+                XmlAttributeNode attributeNode = attributeNodes![attributeIndex];
                 if (attributeNode.IsPrefixAndLocalName(prefix, localName))
                 {
                     _attributeStart = attributeIndex;
@@ -590,7 +590,7 @@ namespace System.Xml
             return null;
         }
 
-        private XmlAttributeNode GetAttributeNode(string localName, string namespaceUri)
+        private XmlAttributeNode? GetAttributeNode(string localName, string? namespaceUri)
         {
             if (localName == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName)));
@@ -598,7 +598,7 @@ namespace System.Xml
                 namespaceUri = string.Empty;
             if (!_node.CanGetAttribute)
                 return null;
-            XmlAttributeNode[] attributeNodes = _attributeNodes;
+            XmlAttributeNode[]? attributeNodes = _attributeNodes;
             int attributeCount = _attributeCount;
             int attributeIndex = _attributeStart;
             for (int i = 0; i < attributeCount; i++)
@@ -607,7 +607,7 @@ namespace System.Xml
                 {
                     attributeIndex = 0;
                 }
-                XmlAttributeNode attributeNode = attributeNodes[attributeIndex];
+                XmlAttributeNode attributeNode = attributeNodes![attributeIndex];
                 if (attributeNode.IsLocalNameAndNamespaceUri(localName, namespaceUri))
                 {
                     _attributeStart = attributeIndex;
@@ -617,7 +617,7 @@ namespace System.Xml
             return null;
         }
 
-        private XmlAttributeNode GetAttributeNode(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        private XmlAttributeNode? GetAttributeNode(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
         {
             if (localName == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName)));
@@ -625,7 +625,7 @@ namespace System.Xml
                 namespaceUri = XmlDictionaryString.Empty;
             if (!_node.CanGetAttribute)
                 return null;
-            XmlAttributeNode[] attributeNodes = _attributeNodes;
+            XmlAttributeNode[]? attributeNodes = _attributeNodes;
             int attributeCount = _attributeCount;
             int attributeIndex = _attributeStart;
             for (int i = 0; i < attributeCount; i++)
@@ -634,7 +634,7 @@ namespace System.Xml
                 {
                     attributeIndex = 0;
                 }
-                XmlAttributeNode attributeNode = attributeNodes[attributeIndex];
+                XmlAttributeNode attributeNode = attributeNodes![attributeIndex];
                 if (attributeNode.IsLocalNameAndNamespaceUri(localName, namespaceUri))
                 {
                     _attributeStart = attributeIndex;
@@ -650,25 +650,25 @@ namespace System.Xml
             return GetAttributeNode(index).ValueAsString;
         }
 
-        public override string GetAttribute(string name)
+        public override string? GetAttribute(string name)
         {
-            XmlAttributeNode attributeNode = GetAttributeNode(name);
+            XmlAttributeNode? attributeNode = GetAttributeNode(name);
             if (attributeNode == null)
                 return null;
             return attributeNode.ValueAsString;
         }
 
-        public override string GetAttribute(string localName, string namespaceUri)
+        public override string? GetAttribute(string localName, string? namespaceUri)
         {
-            XmlAttributeNode attributeNode = GetAttributeNode(localName, namespaceUri);
+            XmlAttributeNode? attributeNode = GetAttributeNode(localName, namespaceUri);
             if (attributeNode == null)
                 return null;
             return attributeNode.ValueAsString;
         }
 
-        public override string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public override string? GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
         {
-            XmlAttributeNode attributeNode = GetAttributeNode(localName, namespaceUri);
+            XmlAttributeNode? attributeNode = GetAttributeNode(localName, namespaceUri);
             if (attributeNode == null)
                 return null;
             return attributeNode.ValueAsString;
@@ -706,9 +706,9 @@ namespace System.Xml
             }
         }
 
-        public override string LookupNamespace(string prefix)
+        public override string? LookupNamespace(string prefix)
         {
-            Namespace ns = _nsMgr.LookupNamespace(prefix);
+            Namespace? ns = _nsMgr.LookupNamespace(prefix);
             if (ns != null)
                 return ns.Uri.GetString(NameTable);
             if (prefix == xmlns)
@@ -718,7 +718,7 @@ namespace System.Xml
 
         protected Namespace LookupNamespace(PrefixHandleType prefix)
         {
-            Namespace ns = _nsMgr.LookupNamespace(prefix);
+            Namespace? ns = _nsMgr.LookupNamespace(prefix);
             if (ns == null)
                 XmlExceptionHelper.ThrowUndefinedPrefix(this, PrefixHandle.GetString(prefix));
             return ns;
@@ -726,7 +726,7 @@ namespace System.Xml
 
         protected Namespace LookupNamespace(PrefixHandle prefix)
         {
-            Namespace ns = _nsMgr.LookupNamespace(prefix);
+            Namespace? ns = _nsMgr.LookupNamespace(prefix);
             if (ns == null)
                 XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix.GetString());
             return ns;
@@ -736,7 +736,7 @@ namespace System.Xml
         {
             if (_attributeCount > 0)
             {
-                ProcessAttributes(_attributeNodes, _attributeCount);
+                ProcessAttributes(_attributeNodes!, _attributeCount);
             }
         }
 
@@ -756,7 +756,7 @@ namespace System.Xml
                     {
                         attributeNode.Namespace = NamespaceManager.EmptyNamespace;
                     }
-                    attributeNode.AttributeText.Namespace = attributeNode.Namespace;
+                    attributeNode.AttributeText!.Namespace = attributeNode.Namespace;
                 }
             }
 
@@ -823,16 +823,16 @@ namespace System.Xml
         }
         public override bool MoveToAttribute(string name)
         {
-            XmlNode attributeNode = GetAttributeNode(name);
+            XmlNode? attributeNode = GetAttributeNode(name);
             if (attributeNode == null)
                 return false;
             MoveToNode(attributeNode);
             return true;
         }
 
-        public override bool MoveToAttribute(string localName, string namespaceUri)
+        public override bool MoveToAttribute(string localName, string? namespaceUri)
         {
-            XmlNode attributeNode = GetAttributeNode(localName, namespaceUri);
+            XmlNode? attributeNode = GetAttributeNode(localName, namespaceUri);
             if (attributeNode == null)
                 return false;
             MoveToNode(attributeNode);
@@ -846,7 +846,7 @@ namespace System.Xml
             if (_depth == 0)
                 MoveToDeclaration();
             else
-                MoveToNode(_elementNodes[_depth]);
+                MoveToNode(_elementNodes![_depth]);
             _attributeIndex = -1;
             return true;
         }
@@ -1257,7 +1257,7 @@ namespace System.Xml
                 if (nodeDepth == 0)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlEndElementNoOpenNodes));
                 // If depth is non-zero, then the document isn't what was expected
-                XmlElementNode elementNode = _elementNodes[nodeDepth];
+                XmlElementNode elementNode = _elementNodes![nodeDepth];
                 XmlExceptionHelper.ThrowEndElementExpected(this, elementNode.LocalName.GetString(), elementNode.Namespace.Uri.GetString());
             }
             Read();
@@ -1265,7 +1265,7 @@ namespace System.Xml
 
         public override bool ReadAttributeValue()
         {
-            XmlAttributeTextNode attributeTextNode = _node.AttributeText;
+            XmlAttributeTextNode? attributeTextNode = _node.AttributeText;
             if (attributeTextNode == null)
                 return false;
             MoveToNode(attributeTextNode);
@@ -1428,6 +1428,8 @@ namespace System.Xml
             // If there are any trailing buffer return them.
             if (_trailByteCount > 0)
             {
+                Debug.Assert(_trailBytes != null);
+
                 int actual = Math.Min(_trailByteCount, byteCount);
                 Buffer.BlockCopy(_trailBytes, 0, buffer, offset, actual);
                 _trailByteCount -= actual;
@@ -1455,7 +1457,7 @@ namespace System.Xml
                 // If we didn't align on the boundary, then we might have some remaining characters
                 if (_trailCharCount > 0)
                 {
-                    Array.Copy(_trailChars, 0, chars, charCount, _trailCharCount);
+                    Array.Copy(_trailChars!, 0, chars, charCount, _trailCharCount);
                     charCount += _trailCharCount;
                     _trailCharCount = 0;
                 }
@@ -1687,7 +1689,7 @@ namespace System.Xml
             return ReadContentAsString();
         }
 
-        public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver)
+        public override object ReadContentAs(Type type, IXmlNamespaceResolver? namespaceResolver)
         {
             if (type == typeof(ulong))
             {
@@ -1799,17 +1801,17 @@ namespace System.Xml
             }
         }
 
-        public override bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName)
+        public override bool TryGetLocalNameAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? localName)
         {
             return _node.TryGetLocalNameAsDictionaryString(out localName);
         }
 
-        public override bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString localName)
+        public override bool TryGetNamespaceUriAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? localName)
         {
             return _node.TryGetNamespaceUriAsDictionaryString(out localName);
         }
 
-        public override bool TryGetValueAsDictionaryString(out XmlDictionaryString value)
+        public override bool TryGetValueAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? value)
         {
             return _node.TryGetValueAsDictionaryString(out value);
         }
@@ -1909,7 +1911,7 @@ namespace System.Xml
             string s = string.Empty;
             for (int i = _depth; i > 0; i--)
             {
-                string localName = _elementNodes[i].LocalName.GetString();
+                string localName = _elementNodes![i].LocalName.GetString();
                 if (i != _depth)
                     s += ", ";
                 s += localName;
@@ -1979,7 +1981,7 @@ namespace System.Xml
                 case XmlNodeType.Element:
                     SignStartElement(writer);
                     for (int i = 0; i < _attributeCount; i++)
-                        SignAttribute(writer, _attributeNodes[i]);
+                        SignAttribute(writer, _attributeNodes![i]);
                     writer.WriteEndStartElement(_node.IsEmptyElement);
                     break;
                 case XmlNodeType.Text:
@@ -2022,11 +2024,11 @@ namespace System.Xml
         {
             if (_signing)
             {
-                SignNode(_signingWriter);
+                SignNode(_signingWriter!);
             }
         }
 
-        public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
+        public override void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes)
         {
             if (_signing)
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationStarted));
@@ -2044,7 +2046,7 @@ namespace System.Xml
             if (!_signing)
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationNotStarted));
 
-            _signingWriter.Flush();
+            _signingWriter!.Flush();
             _signingWriter.Close();
             _signing = false;
         }
@@ -2068,7 +2070,7 @@ namespace System.Xml
             private readonly bool _canGetAttribute;
             private readonly bool _canMoveToElement;
             private readonly ReadState _readState;
-            private readonly XmlAttributeTextNode _attributeTextNode;
+            private readonly XmlAttributeTextNode? _attributeTextNode;
             private bool _exitScope;
             private readonly int _depthDelta;
             private bool _isAtomicValue;
@@ -2095,7 +2097,7 @@ namespace System.Xml
                               ValueHandle value,
                               XmlNodeFlags nodeFlags,
                               ReadState readState,
-                              XmlAttributeTextNode attributeTextNode,
+                              XmlAttributeTextNode? attributeTextNode,
                               int depthDelta)
             {
                 _nodeType = nodeType;
@@ -2132,7 +2134,7 @@ namespace System.Xml
             public PrefixHandle Prefix { get { DiagnosticUtility.DebugAssert(_qnameType != QNameType.Xmlns, ""); return _prefix; } }
             public bool CanGetAttribute { get { return _canGetAttribute; } }
             public bool CanMoveToElement { get { return _canMoveToElement; } }
-            public XmlAttributeTextNode AttributeText { get { return _attributeTextNode; } }
+            public XmlAttributeTextNode? AttributeText { get { return _attributeTextNode; } }
             public bool SkipValue { get { return _skipValue; } }
             public ValueHandle Value { get { DiagnosticUtility.DebugAssert(_qnameType != QNameType.Xmlns, ""); return _value; } }
             public int DepthDelta { get { return _depthDelta; } }
@@ -2312,7 +2314,7 @@ namespace System.Xml
                 }
             }
 
-            public bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName)
+            public bool TryGetLocalNameAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? localName)
             {
                 if (_qnameType == QNameType.Normal)
                 {
@@ -2326,7 +2328,7 @@ namespace System.Xml
                 }
             }
 
-            public bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString ns)
+            public bool TryGetNamespaceUriAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? ns)
             {
                 if (_qnameType == QNameType.Normal)
                 {
@@ -2340,7 +2342,7 @@ namespace System.Xml
                 }
             }
 
-            public bool TryGetValueAsDictionaryString(out XmlDictionaryString value)
+            public bool TryGetValueAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? value)
             {
                 if (_qnameType == QNameType.Normal)
                 {
@@ -2462,7 +2464,7 @@ namespace System.Xml
                               ValueHandle value,
                               XmlNodeFlags nodeFlags,
                               ReadState readState,
-                              XmlAttributeTextNode attributeTextNode,
+                              XmlAttributeTextNode? attributeTextNode,
                               int depthDelta)
                 :
                 base(nodeType, prefix, localName, value, nodeFlags, readState, attributeTextNode, depthDelta)
@@ -2621,8 +2623,8 @@ namespace System.Xml
 
         private class AttributeSorter : IComparer
         {
-            private object[] _indeces;
-            private XmlAttributeNode[] _attributeNodes;
+            private object[]? _indeces;
+            private XmlAttributeNode[]? _attributeNodes;
             private int _attributeCount;
             private int _attributeIndex1;
             private int _attributeIndex2;
@@ -2670,7 +2672,7 @@ namespace System.Xml
 
             private bool IsSorted()
             {
-                for (int i = 0; i < _indeces.Length - 1; i++)
+                for (int i = 0; i < _indeces!.Length - 1; i++)
                 {
                     if (Compare(_indeces[i], _indeces[i + 1]) >= 0)
                     {
@@ -2682,12 +2684,12 @@ namespace System.Xml
                 return true;
             }
 
-            public int Compare(object obj1, object obj2)
+            public int Compare(object? obj1, object? obj2)
             {
-                int index1 = (int)obj1;
-                int index2 = (int)obj2;
-                XmlAttributeNode attribute1 = _attributeNodes[index1];
-                XmlAttributeNode attribute2 = _attributeNodes[index2];
+                int index1 = (int)obj1!;
+                int index2 = (int)obj2!;
+                XmlAttributeNode attribute1 = _attributeNodes![index1];
+                XmlAttributeNode attribute2 = _attributeNodes![index2];
 
                 int i = CompareQNameType(attribute1.QNameType, attribute2.QNameType);
                 if (i == 0)
@@ -2720,13 +2722,13 @@ namespace System.Xml
         private class NamespaceManager
         {
             private readonly XmlBufferReader _bufferReader;
-            private Namespace[] _namespaces;
+            private Namespace[]? _namespaces;
             private int _nsCount;
             private int _depth;
-            private readonly Namespace[] _shortPrefixUri;
+            private readonly Namespace?[] _shortPrefixUri;
             private static readonly Namespace s_emptyNamespace = new Namespace(XmlBufferReader.Empty);
-            private static Namespace s_xmlNamespace;
-            private XmlAttribute[] _attributes;
+            private static Namespace? s_xmlNamespace;
+            private XmlAttribute[]? _attributes;
             private int _attributeCount;
             private XmlSpace _space;
             private string _lang;
@@ -2806,12 +2808,9 @@ namespace System.Xml
             {
                 if (_nsCount != 0)
                 {
-                    if (_shortPrefixUri != null)
+                    for (int i = 0; i < _shortPrefixUri.Length; i++)
                     {
-                        for (int i = 0; i < _shortPrefixUri.Length; i++)
-                        {
-                            _shortPrefixUri[i] = null;
-                        }
+                        _shortPrefixUri[i] = null;
                     }
                     _shortPrefixUri[(int)PrefixHandleType.Empty] = s_emptyNamespace;
                     _nsCount = 0;
@@ -2831,7 +2830,7 @@ namespace System.Xml
             {
                 while (_nsCount > 0)
                 {
-                    Namespace nameSpace = _namespaces[_nsCount - 1];
+                    Namespace nameSpace = _namespaces![_nsCount - 1];
                     if (nameSpace.Depth != _depth)
                         break;
                     PrefixHandleType shortPrefix;
@@ -2843,7 +2842,7 @@ namespace System.Xml
                 }
                 while (_attributeCount > 0)
                 {
-                    XmlAttribute attribute = _attributes[_attributeCount - 1];
+                    XmlAttribute attribute = _attributes![_attributeCount - 1];
                     if (attribute.Depth != _depth)
                         break;
                     _space = attribute.XmlSpace;
@@ -2857,7 +2856,7 @@ namespace System.Xml
             {
                 for (int i = 0; i < _nsCount; i++)
                 {
-                    PrefixHandle prefix = _namespaces[i].Prefix;
+                    PrefixHandle prefix = _namespaces![i].Prefix;
                     bool found = false;
                     for (int j = i + 1; j < _nsCount; j++)
                     {
@@ -2952,19 +2951,19 @@ namespace System.Xml
                 return nameSpace;
             }
 
-            public Namespace LookupNamespace(PrefixHandleType prefix)
+            public Namespace? LookupNamespace(PrefixHandleType prefix)
             {
                 return _shortPrefixUri[(int)prefix];
             }
 
-            public Namespace LookupNamespace(PrefixHandle prefix)
+            public Namespace? LookupNamespace(PrefixHandle prefix)
             {
                 PrefixHandleType shortPrefix;
                 if (prefix.TryGetShortPrefix(out shortPrefix))
                     return LookupNamespace(shortPrefix);
                 for (int i = _nsCount - 1; i >= 0; i--)
                 {
-                    Namespace nameSpace = _namespaces[i];
+                    Namespace nameSpace = _namespaces![i];
                     if (nameSpace.Prefix == prefix)
                         return nameSpace;
                 }
@@ -2972,14 +2971,14 @@ namespace System.Xml
                     return XmlNamespace;
                 return null;
             }
-            public Namespace LookupNamespace(string prefix)
+            public Namespace? LookupNamespace(string prefix)
             {
                 PrefixHandleType shortPrefix;
                 if (TryGetShortPrefix(prefix, out shortPrefix))
                     return LookupNamespace(shortPrefix);
                 for (int i = _nsCount - 1; i >= 0; i--)
                 {
-                    Namespace nameSpace = _namespaces[i];
+                    Namespace nameSpace = _namespaces![i];
                     if (nameSpace.Prefix == prefix)
                         return nameSpace;
                 }
@@ -3012,7 +3011,7 @@ namespace System.Xml
             private class XmlAttribute
             {
                 private XmlSpace _space;
-                private string _lang;
+                private string _lang = string.Empty;
                 private int _depth;
 
                 public XmlAttribute()
@@ -3061,8 +3060,8 @@ namespace System.Xml
             private readonly PrefixHandle _prefix;
             private readonly StringHandle _uri;
             private int _depth;
-            private Namespace _outerUri;
-            private string _uriString;
+            private Namespace? _outerUri;
+            private string? _uriString;
 
             public Namespace(XmlBufferReader bufferReader)
             {
@@ -3129,7 +3128,7 @@ namespace System.Xml
                 }
             }
 
-            public Namespace OuterUri
+            public Namespace? OuterUri
             {
                 get
                 {
index c99f9f8..a16eade 100644 (file)
@@ -9,29 +9,30 @@ using System.Globalization;
 using System.Runtime.Serialization;
 using System.Collections.Generic;
 using System.Threading.Tasks;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
     internal abstract class XmlBaseWriter : XmlDictionaryWriter
     {
-        private XmlNodeWriter _writer;
+        private XmlNodeWriter _writer = null!; // initialized in SetOutput
         private readonly NamespaceManager _nsMgr;
-        private Element[] _elements;
+        private Element[]? _elements;
         private int _depth;
-        private string _attributeLocalName;
-        private string _attributeValue;
+        private string? _attributeLocalName;
+        private string? _attributeValue;
         private bool _isXmlAttribute;
         private bool _isXmlnsAttribute;
         private WriteState _writeState;
         private DocumentState _documentState;
-        private byte[] _trailBytes;
+        private byte[]? _trailBytes;
         private int _trailByteCount;
-        private XmlStreamNodeWriter _nodeWriter;
-        private XmlSigningNodeWriter _signingWriter;
+        private XmlStreamNodeWriter _nodeWriter = null!; // initialized in SetOutput
+        private XmlSigningNodeWriter? _signingWriter;
         private bool _inList;
         private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/";
         private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace";
-        private static BinHexEncoding _binhexEncoding;
+        private static BinHexEncoding? _binhexEncoding;
         private static readonly string[] s_prefixes = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
 
         protected XmlBaseWriter()
@@ -108,6 +109,7 @@ namespace System.Xml
             get { return _writeState == WriteState.Closed; }
         }
 
+        [DoesNotReturn]
         protected void ThrowClosed()
         {
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlWriterClosed));
@@ -123,7 +125,7 @@ namespace System.Xml
             }
         }
 
-        public override string XmlLang
+        public override string? XmlLang
         {
             get
             {
@@ -147,7 +149,7 @@ namespace System.Xml
             }
         }
 
-        public override void WriteXmlnsAttribute(string prefix, string ns)
+        public override void WriteXmlnsAttribute(string? prefix, string ns)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -172,7 +174,7 @@ namespace System.Xml
             }
         }
 
-        public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
+        public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -197,7 +199,7 @@ namespace System.Xml
             }
         }
 
-        private void StartAttribute(ref string prefix, string localName, string ns, XmlDictionaryString xNs)
+        private void StartAttribute([AllowNull] ref string prefix, string localName, string? ns, XmlDictionaryString? xNs)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -271,10 +273,10 @@ namespace System.Xml
             else if (prefix.Length == 0)
             {
                 // No prefix specified - try to find a prefix corresponding to the given namespace
-                prefix = _nsMgr.LookupAttributePrefix(ns);
+                string? tempPrefix = _nsMgr.LookupAttributePrefix(ns);
 
                 // If we didn't find anything with the right namespace, generate one.
-                if (prefix == null)
+                if (tempPrefix == null)
                 {
                     // Watch for special values
                     if (ns.Length == xmlnsNamespace.Length && ns == xmlnsNamespace)
@@ -282,8 +284,9 @@ namespace System.Xml
                     if (ns.Length == xmlNamespace.Length && ns == xmlNamespace)
                         throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlSpecificBindingNamespace, "xml", ns)));
 
-                    prefix = GeneratePrefix(ns, xNs);
+                    tempPrefix = GeneratePrefix(ns, xNs);
                 }
+                prefix = tempPrefix;
             }
             else
             {
@@ -292,7 +295,7 @@ namespace System.Xml
             _writeState = WriteState.Attribute;
         }
 
-        public override void WriteStartAttribute(string prefix, string localName, string namespaceUri)
+        public override void WriteStartAttribute(string? prefix, string localName, string? namespaceUri)
         {
             StartAttribute(ref prefix, localName, namespaceUri, null);
             if (!_isXmlnsAttribute)
@@ -301,12 +304,12 @@ namespace System.Xml
             }
         }
 
-        public override void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public override void WriteStartAttribute(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
-            StartAttribute(ref prefix, (localName != null ? localName.Value : null), (namespaceUri != null ? namespaceUri.Value : null), namespaceUri);
+            StartAttribute(ref prefix, (localName != null ? localName.Value : null)!, (namespaceUri != null ? namespaceUri.Value : null), namespaceUri);
             if (!_isXmlnsAttribute)
             {
-                _writer.WriteStartAttribute(prefix, localName);
+                _writer.WriteStartAttribute(prefix, localName!);
             }
         }
 
@@ -325,7 +328,7 @@ namespace System.Xml
                 {
                     if (_attributeLocalName == "lang")
                     {
-                        _nsMgr.AddLangAttribute(_attributeValue);
+                        _nsMgr.AddLangAttribute(_attributeValue!);
                     }
                     else if (_attributeLocalName == "space")
                     {
@@ -353,7 +356,7 @@ namespace System.Xml
 
                 if (_isXmlnsAttribute)
                 {
-                    _nsMgr.AddNamespaceIfNotDeclared(_attributeLocalName, _attributeValue, null);
+                    _nsMgr.AddNamespaceIfNotDeclared(_attributeLocalName!, _attributeValue!, null);
                     _isXmlnsAttribute = false;
                     _attributeLocalName = null;
                     _attributeValue = null;
@@ -389,7 +392,7 @@ namespace System.Xml
                 {
                     if (_attributeLocalName == "lang")
                     {
-                        _nsMgr.AddLangAttribute(_attributeValue);
+                        _nsMgr.AddLangAttribute(_attributeValue!);
                     }
                     else if (_attributeLocalName == "space")
                     {
@@ -417,7 +420,7 @@ namespace System.Xml
 
                 if (_isXmlnsAttribute)
                 {
-                    _nsMgr.AddNamespaceIfNotDeclared(_attributeLocalName, _attributeValue, null);
+                    _nsMgr.AddNamespaceIfNotDeclared(_attributeLocalName!, _attributeValue!, null);
                     _isXmlnsAttribute = false;
                     _attributeLocalName = null;
                     _attributeValue = null;
@@ -433,7 +436,7 @@ namespace System.Xml
             }
         }
 
-        public override void WriteComment(string text)
+        public override void WriteComment(string? text)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -471,7 +474,7 @@ namespace System.Xml
             WriteEndElement();
         }
 
-        public override void WriteCData(string text)
+        public override void WriteCData(string? text)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -491,12 +494,12 @@ namespace System.Xml
             }
         }
 
-        public override void WriteDocType(string name, string pubid, string sysid, string subset)
+        public override void WriteDocType(string name, string? pubid, string? sysid, string? subset)
         {
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.XmlMethodNotSupported, "WriteDocType")));
         }
 
-        private void StartElement(ref string prefix, string localName, string ns, XmlDictionaryString xNs)
+        private void StartElement(ref string? prefix, string localName, string? ns, XmlDictionaryString? xNs)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -541,7 +544,7 @@ namespace System.Xml
             element.LocalName = localName;
         }
 
-        private void PreStartElementAsyncCheck(string prefix, string localName, string ns, XmlDictionaryString xNs)
+        private void PreStartElementAsyncCheck(string? prefix, string localName, string? ns, XmlDictionaryString? xNs)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -556,13 +559,13 @@ namespace System.Xml
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteStartElement", WriteState.ToString())));
         }
 
-        private async Task StartElementAndWriteStartElementAsync(string prefix, string localName, string namespaceUri)
+        private async Task StartElementAndWriteStartElementAsync(string? prefix, string localName, string? namespaceUri)
         {
             prefix = await StartElementAsync(prefix, localName, namespaceUri, null).ConfigureAwait(false);
             await _writer.WriteStartElementAsync(prefix, localName).ConfigureAwait(false);
         }
 
-        private async Task<string> StartElementAsync(string prefix, string localName, string ns, XmlDictionaryString xNs)
+        private async Task<string> StartElementAsync(string? prefix, string localName, string? ns, XmlDictionaryString? xNs)
         {
             await FlushBase64Async().ConfigureAwait(false);
             await AutoCompleteAsync(WriteState.Element).ConfigureAwait(false);
@@ -597,21 +600,21 @@ namespace System.Xml
             return prefix;
         }
 
-        public override void WriteStartElement(string prefix, string localName, string namespaceUri)
+        public override void WriteStartElement(string? prefix, string localName, string? namespaceUri)
         {
             StartElement(ref prefix, localName, namespaceUri, null);
             _writer.WriteStartElement(prefix, localName);
         }
 
-        public override Task WriteStartElementAsync(string prefix, string localName, string namespaceUri)
+        public override Task WriteStartElementAsync(string? prefix, string localName, string? namespaceUri)
         {
             PreStartElementAsyncCheck(prefix, localName, namespaceUri, null);
             return StartElementAndWriteStartElementAsync(prefix, localName, namespaceUri);
         }
 
-        public override void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public override void WriteStartElement(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
-            StartElement(ref prefix, (localName != null ? localName.Value : null), (namespaceUri != null ? namespaceUri.Value : null), namespaceUri);
+            StartElement(ref prefix, localName.Value, (namespaceUri != null ? namespaceUri.Value : null), namespaceUri);
             _writer.WriteStartElement(prefix, localName);
         }
 
@@ -634,8 +637,8 @@ namespace System.Xml
             }
             else
             {
-                Element element = _elements[_depth];
-                _writer.WriteEndElement(element.Prefix, element.LocalName);
+                Element element = _elements![_depth];
+                _writer.WriteEndElement(element.Prefix, element.LocalName!);
             }
 
             ExitScope();
@@ -666,8 +669,8 @@ namespace System.Xml
             }
             else
             {
-                Element element = _elements[_depth];
-                await _writer.WriteEndElementAsync(element.Prefix, element.LocalName).ConfigureAwait(false);
+                Element element = _elements![_depth];
+                await _writer.WriteEndElementAsync(element.Prefix, element.LocalName!).ConfigureAwait(false);
             }
 
             ExitScope();
@@ -699,7 +702,7 @@ namespace System.Xml
 
         private void ExitScope()
         {
-            _elements[_depth].Clear();
+            _elements![_depth].Clear();
             _depth--;
             if (_depth == 0 && _documentState == DocumentState.Document)
                 _documentState = DocumentState.Epilog;
@@ -822,7 +825,7 @@ namespace System.Xml
             return _writer.WriteEndStartElementAsync(false);
         }
 
-        public override string LookupPrefix(string ns)
+        public override string? LookupPrefix(string ns)
         {
             if (ns == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(ns)));
@@ -833,9 +836,9 @@ namespace System.Xml
             return _nsMgr.LookupPrefix(ns);
         }
 
-        private string GetQualifiedNamePrefix(string namespaceUri, XmlDictionaryString xNs)
+        private string GetQualifiedNamePrefix(string namespaceUri, XmlDictionaryString? xNs)
         {
-            string prefix = _nsMgr.LookupPrefix(namespaceUri);
+            string? prefix = _nsMgr.LookupPrefix(namespaceUri);
             if (prefix == null)
             {
                 if (_writeState != WriteState.Attribute)
@@ -846,7 +849,7 @@ namespace System.Xml
             return prefix;
         }
 
-        public override void WriteQualifiedName(string localName, string namespaceUri)
+        public override void WriteQualifiedName(string localName, string? namespaceUri)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -865,7 +868,7 @@ namespace System.Xml
             WriteString(localName);
         }
 
-        public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -911,7 +914,7 @@ namespace System.Xml
         }
 
 
-        public override void WriteProcessingInstruction(string name, string text)
+        public override void WriteProcessingInstruction(string name, string? text)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -972,7 +975,7 @@ namespace System.Xml
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.XmlMethodNotSupported, "WriteNmToken")));
         }
 
-        public override void WriteWhitespace(string whitespace)
+        public override void WriteWhitespace(string? whitespace)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -993,7 +996,7 @@ namespace System.Xml
             WriteString(whitespace);
         }
 
-        public override void WriteString(string value)
+        public override void WriteString(string? value)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -1017,7 +1020,7 @@ namespace System.Xml
             }
         }
 
-        public override void WriteString(XmlDictionaryString value)
+        public override void WriteString(XmlDictionaryString? value)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -1265,7 +1268,7 @@ namespace System.Xml
             }
         }
 
-        public override void WriteValue(string value)
+        public override void WriteValue(string? value)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -1392,7 +1395,7 @@ namespace System.Xml
             }
         }
 
-        public override void WriteValue(XmlDictionaryString value)
+        public override void WriteValue(XmlDictionaryString? value)
         {
             WriteString(value);
         }
@@ -1499,7 +1502,7 @@ namespace System.Xml
                 {
                     while (_trailByteCount < 3 && count > 0)
                     {
-                        _trailBytes[_trailByteCount++] = buffer[offset++];
+                        _trailBytes![_trailByteCount++] = buffer[offset++];
                         count--;
                     }
                 }
@@ -1569,7 +1572,7 @@ namespace System.Xml
                 {
                     while (_trailByteCount < 3 && count > 0)
                     {
-                        _trailBytes[_trailByteCount++] = buffer[offset++];
+                        _trailBytes![_trailByteCount++] = buffer[offset++];
                         count--;
                     }
                 }
@@ -1628,7 +1631,7 @@ namespace System.Xml
             }
         }
 
-        public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
+        public override void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes)
         {
             if (IsClosed)
                 ThrowClosed();
@@ -1648,7 +1651,7 @@ namespace System.Xml
                 ThrowClosed();
             if (!Signing)
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationNotStarted));
-            _signingWriter.Flush();
+            _signingWriter!.Flush();
             _writer = _signingWriter.NodeWriter;
         }
 
@@ -1669,6 +1672,8 @@ namespace System.Xml
 
         private void FlushTrailBytes()
         {
+            Debug.Assert(_trailBytes != null);
+
             if (_attributeValue != null)
                 WriteAttributeText(XmlConverter.Base64Encoding.GetString(_trailBytes, 0, _trailByteCount));
 
@@ -1683,6 +1688,8 @@ namespace System.Xml
 
         private async Task FlushTrailBytesAsync()
         {
+            Debug.Assert(_trailBytes != null);
+
             if (_attributeValue != null)
                 WriteAttributeText(XmlConverter.Base64Encoding.GetString(_trailBytes, 0, _trailByteCount));
 
@@ -1726,7 +1733,7 @@ namespace System.Xml
                 {
                     _writer.WriteListSeparator();
                 }
-                WritePrimitiveValue(array.GetValue(i));
+                WritePrimitiveValue(array.GetValue(i)!); // possible bug to log?
             }
             _inList = false;
             _writer.WriteEndListText();
@@ -1749,19 +1756,19 @@ namespace System.Xml
         {
         }
 
-        private string GeneratePrefix(string ns, XmlDictionaryString xNs)
+        private string GeneratePrefix(string ns, XmlDictionaryString? xNs)
         {
             if (_writeState != WriteState.Element && _writeState != WriteState.Attribute)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidPrefixState, WriteState.ToString())));
 
-            string prefix = _nsMgr.AddNamespace(ns, xNs);
+            string? prefix = _nsMgr.AddNamespace(ns, xNs);
 
             if (prefix != null)
                 return prefix;
 
             while (true)
             {
-                int prefixId = _elements[_depth].PrefixId++;
+                int prefixId = _elements![_depth].PrefixId++;
                 prefix = string.Concat("d", _depth.ToString(CultureInfo.InvariantCulture), "p", prefixId.ToString(CultureInfo.InvariantCulture));
 
                 if (_nsMgr.LookupNamespace(prefix) == null)
@@ -1779,7 +1786,7 @@ namespace System.Xml
 
         private void WriteAttributeText(string value)
         {
-            if (_attributeValue.Length == 0)
+            if (_attributeValue!.Length == 0)
                 _attributeValue = value;
             else
                 _attributeValue += value;
@@ -1787,11 +1794,11 @@ namespace System.Xml
 
         private class Element
         {
-            private string _prefix;
-            private string _localName;
+            private string? _prefix;
+            private string? _localName;
             private int _prefixId;
 
-            public string Prefix
+            public string? Prefix
             {
                 get
                 {
@@ -1803,7 +1810,7 @@ namespace System.Xml
                 }
             }
 
-            public string LocalName
+            public string? LocalName
             {
                 get
                 {
@@ -1845,14 +1852,14 @@ namespace System.Xml
 
         private class NamespaceManager
         {
-            private Namespace[] _namespaces;
-            private Namespace _lastNameSpace;
+            private Namespace[]? _namespaces;
+            private Namespace? _lastNameSpace;
             private int _nsCount;
             private int _depth;
-            private XmlAttribute[] _attributes;
+            private XmlAttribute[]? _attributes;
             private int _attributeCount;
             private XmlSpace _space;
-            private string _lang;
+            private string? _lang;
             private int _nsTop;
             private readonly Namespace _defaultNamespace;
 
@@ -1865,7 +1872,7 @@ namespace System.Xml
                 _defaultNamespace.UriDictionaryString = null;
             }
 
-            public string XmlLang
+            public string? XmlLang
             {
                 get
                 {
@@ -1919,18 +1926,18 @@ namespace System.Xml
                 int i = _nsCount;
                 while (i > 0)
                 {
-                    Namespace nameSpace = _namespaces[i - 1];
+                    Namespace nameSpace = _namespaces![i - 1];
                     if (nameSpace.Depth != _depth)
                         break;
                     i--;
                 }
                 while (i < _nsCount)
                 {
-                    Namespace nameSpace = _namespaces[i];
+                    Namespace nameSpace = _namespaces![i];
                     if (nameSpace.UriDictionaryString != null)
                         writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.UriDictionaryString);
                     else
-                        writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.Uri);
+                        writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.Uri!);
                     i++;
                 }
             }
@@ -1944,7 +1951,7 @@ namespace System.Xml
             {
                 while (_nsCount > 0)
                 {
-                    Namespace nameSpace = _namespaces[_nsCount - 1];
+                    Namespace nameSpace = _namespaces![_nsCount - 1];
                     if (nameSpace.Depth != _depth)
                         break;
                     if (_lastNameSpace == nameSpace)
@@ -1954,7 +1961,7 @@ namespace System.Xml
                 }
                 while (_attributeCount > 0)
                 {
-                    XmlAttribute attribute = _attributes[_attributeCount - 1];
+                    XmlAttribute attribute = _attributes![_attributeCount - 1];
                     if (attribute.Depth != _depth)
                         break;
                     _space = attribute.XmlSpace;
@@ -2001,7 +2008,7 @@ namespace System.Xml
                 _attributeCount++;
             }
 
-            public string AddNamespace(string uri, XmlDictionaryString uriDictionaryString)
+            public string? AddNamespace(string uri, XmlDictionaryString? uriDictionaryString)
             {
                 if (uri.Length == 0)
                 {
@@ -2017,7 +2024,7 @@ namespace System.Xml
                         bool declared = false;
                         for (int j = _nsCount - 1; j >= _nsTop; j--)
                         {
-                            Namespace nameSpace = _namespaces[j];
+                            Namespace nameSpace = _namespaces![j];
                             if (nameSpace.Prefix == prefix)
                             {
                                 declared = true;
@@ -2034,7 +2041,7 @@ namespace System.Xml
                 return null;
             }
 
-            public void AddNamespaceIfNotDeclared(string prefix, string uri, XmlDictionaryString uriDictionaryString)
+            public void AddNamespaceIfNotDeclared(string prefix, string uri, XmlDictionaryString? uriDictionaryString)
             {
                 if (LookupNamespace(prefix) != uri)
                 {
@@ -2042,7 +2049,7 @@ namespace System.Xml
                 }
             }
 
-            public void AddNamespace(string prefix, string uri, XmlDictionaryString uriDictionaryString)
+            public void AddNamespace(string prefix, string uri, XmlDictionaryString? uriDictionaryString)
             {
                 if (prefix.Length >= 3)
                 {
@@ -2059,7 +2066,7 @@ namespace System.Xml
                 Namespace nameSpace;
                 for (int i = _nsCount - 1; i >= 0; i--)
                 {
-                    nameSpace = _namespaces[i];
+                    nameSpace = _namespaces![i];
                     if (nameSpace.Depth != _depth)
                         break;
                     if (nameSpace.Prefix == prefix)
@@ -2077,7 +2084,7 @@ namespace System.Xml
                 if (uri.Length == xmlNamespace.Length && uri[18] == 'X' && uri == xmlNamespace)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlSpecificBindingNamespace, "xml", uri)));
 
-                if (_namespaces.Length == _nsCount)
+                if (_namespaces!.Length == _nsCount)
                 {
                     Namespace[] newNamespaces = new Namespace[_nsCount * 2];
                     Array.Copy(_namespaces, newNamespaces, _nsCount);
@@ -2097,17 +2104,17 @@ namespace System.Xml
                 _lastNameSpace = null;
             }
 
-            public string LookupPrefix(string ns)
+            public string? LookupPrefix(string ns)
             {
                 if (_lastNameSpace != null && _lastNameSpace.Uri == ns)
                     return _lastNameSpace.Prefix;
                 int nsCount = _nsCount;
                 for (int i = nsCount - 1; i >= _nsTop; i--)
                 {
-                    Namespace nameSpace = _namespaces[i];
+                    Namespace nameSpace = _namespaces![i];
                     if (object.ReferenceEquals(nameSpace.Uri, ns))
                     {
-                        string prefix = nameSpace.Prefix;
+                        string? prefix = nameSpace.Prefix;
                         // Make sure that the prefix refers to the namespace in scope
                         bool declared = false;
                         for (int j = i + 1; j < nsCount; j++)
@@ -2127,10 +2134,10 @@ namespace System.Xml
                 }
                 for (int i = nsCount - 1; i >= _nsTop; i--)
                 {
-                    Namespace nameSpace = _namespaces[i];
+                    Namespace nameSpace = _namespaces![i];
                     if (nameSpace.Uri == ns)
                     {
-                        string prefix = nameSpace.Prefix;
+                        string? prefix = nameSpace.Prefix;
                         // Make sure that the prefix refers to the namespace in scope
                         bool declared = false;
                         for (int j = i + 1; j < nsCount; j++)
@@ -2155,7 +2162,7 @@ namespace System.Xml
                     bool emptyPrefixUnassigned = true;
                     for (int i = nsCount - 1; i >= _nsTop; i--)
                     {
-                        if (_namespaces[i].Prefix.Length == 0)
+                        if (_namespaces![i].Prefix!.Length == 0)
                         {
                             emptyPrefixUnassigned = false;
                             break;
@@ -2172,19 +2179,19 @@ namespace System.Xml
                 return null;
             }
 
-            public string LookupAttributePrefix(string ns)
+            public string? LookupAttributePrefix(string ns)
             {
-                if (_lastNameSpace != null && _lastNameSpace.Uri == ns && _lastNameSpace.Prefix.Length != 0)
+                if (_lastNameSpace != null && _lastNameSpace.Uri == ns && _lastNameSpace.Prefix!.Length != 0)
                     return _lastNameSpace.Prefix;
 
                 int nsCount = _nsCount;
                 for (int i = nsCount - 1; i >= _nsTop; i--)
                 {
-                    Namespace nameSpace = _namespaces[i];
+                    Namespace nameSpace = _namespaces![i];
 
                     if (object.ReferenceEquals(nameSpace.Uri, ns))
                     {
-                        string prefix = nameSpace.Prefix;
+                        string prefix = nameSpace.Prefix!;
                         if (prefix.Length != 0)
                         {
                             // Make sure that the prefix refers to the namespace in scope
@@ -2207,10 +2214,10 @@ namespace System.Xml
                 }
                 for (int i = nsCount - 1; i >= _nsTop; i--)
                 {
-                    Namespace nameSpace = _namespaces[i];
+                    Namespace nameSpace = _namespaces![i];
                     if (nameSpace.Uri == ns)
                     {
-                        string prefix = nameSpace.Prefix;
+                        string prefix = nameSpace.Prefix!;
                         if (prefix.Length != 0)
                         {
                             // Make sure that the prefix refers to the namespace in scope
@@ -2236,15 +2243,15 @@ namespace System.Xml
                 return null;
             }
 
-            public string LookupNamespace(string prefix)
+            public string? LookupNamespace(string prefix)
             {
                 int nsCount = _nsCount;
                 if (prefix.Length == 0)
                 {
                     for (int i = nsCount - 1; i >= _nsTop; i--)
                     {
-                        Namespace nameSpace = _namespaces[i];
-                        if (nameSpace.Prefix.Length == 0)
+                        Namespace nameSpace = _namespaces![i];
+                        if (nameSpace.Prefix!.Length == 0)
                             return nameSpace.Uri;
                     }
                     return string.Empty;
@@ -2254,7 +2261,7 @@ namespace System.Xml
                     char prefixChar = prefix[0];
                     for (int i = nsCount - 1; i >= _nsTop; i--)
                     {
-                        Namespace nameSpace = _namespaces[i];
+                        Namespace nameSpace = _namespaces![i];
                         if (nameSpace.PrefixChar == prefixChar)
                             return nameSpace.Uri;
                     }
@@ -2262,7 +2269,7 @@ namespace System.Xml
                 }
                 for (int i = nsCount - 1; i >= _nsTop; i--)
                 {
-                    Namespace nameSpace = _namespaces[i];
+                    Namespace nameSpace = _namespaces![i];
                     if (nameSpace.Prefix == prefix)
                         return nameSpace.Uri;
                 }
@@ -2276,7 +2283,7 @@ namespace System.Xml
             public void Sign(XmlCanonicalWriter signingWriter)
             {
                 int nsCount = _nsCount;
-                Fx.Assert(nsCount >= 1 && _namespaces[0].Prefix.Length == 0 && _namespaces[0].Uri.Length == 0, "");
+                Fx.Assert(nsCount >= 1 && _namespaces![0].Prefix!.Length == 0 && _namespaces[0].Uri!.Length == 0, "");
                 for (int i = 1; i < nsCount; i++)
                 {
                     Namespace nameSpace = _namespaces[i];
@@ -2289,7 +2296,7 @@ namespace System.Xml
 
                     if (!found)
                     {
-                        signingWriter.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.Uri);
+                        signingWriter.WriteXmlnsAttribute(nameSpace.Prefix!, nameSpace.Uri!);
                     }
                 }
             }
@@ -2297,7 +2304,7 @@ namespace System.Xml
             private class XmlAttribute
             {
                 private XmlSpace _space;
-                private string _lang;
+                private string? _lang;
                 private int _depth;
 
                 public XmlAttribute()
@@ -2316,7 +2323,7 @@ namespace System.Xml
                     }
                 }
 
-                public string XmlLang
+                public string? XmlLang
                 {
                     get
                     {
@@ -2348,9 +2355,9 @@ namespace System.Xml
 
             private class Namespace
             {
-                private string _prefix;
-                private string _ns;
-                private XmlDictionaryString _xNs;
+                private string? _prefix;
+                private string? _ns;
+                private XmlDictionaryString? _xNs;
                 private int _depth;
                 private char _prefixChar;
 
@@ -2387,7 +2394,8 @@ namespace System.Xml
                     }
                 }
 
-                public string Prefix
+                [DisallowNull]
+                public string? Prefix
                 {
                     get
                     {
@@ -2403,7 +2411,7 @@ namespace System.Xml
                     }
                 }
 
-                public string Uri
+                public string? Uri
                 {
                     get
                     {
@@ -2415,7 +2423,7 @@ namespace System.Xml
                     }
                 }
 
-                public XmlDictionaryString UriDictionaryString
+                public XmlDictionaryString? UriDictionaryString
                 {
                     get
                     {
index cf177b4..7f7e0e3 100644 (file)
@@ -1,6 +1,7 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System.Diagnostics.CodeAnalysis;
 using System.IO;
 using System.Runtime.Serialization;
 
@@ -9,15 +10,15 @@ namespace System.Xml
     public interface IXmlBinaryReaderInitializer
     {
         void SetInput(byte[] buffer, int offset, int count,
-                            IXmlDictionary dictionary,
+                            IXmlDictionary? dictionary,
                             XmlDictionaryReaderQuotas quotas,
-                            XmlBinaryReaderSession session,
-                            OnXmlDictionaryReaderClose onClose);
+                            XmlBinaryReaderSession? session,
+                            OnXmlDictionaryReaderClose? onClose);
         void SetInput(Stream stream,
-                             IXmlDictionary dictionary,
+                             IXmlDictionary? dictionary,
                              XmlDictionaryReaderQuotas quotas,
-                             XmlBinaryReaderSession session,
-                             OnXmlDictionaryReaderClose onClose);
+                             XmlBinaryReaderSession? session,
+                             OnXmlDictionaryReaderClose? onClose);
     }
 
     internal class XmlBinaryReader : XmlBaseReader, IXmlBinaryReaderInitializer
@@ -34,10 +35,10 @@ namespace System.Xml
         }
 
         public void SetInput(byte[] buffer, int offset, int count,
-                            IXmlDictionary dictionary,
+                            IXmlDictionary? dictionary,
                             XmlDictionaryReaderQuotas quotas,
-                            XmlBinaryReaderSession session,
-                            OnXmlDictionaryReaderClose onClose)
+                            XmlBinaryReaderSession? session,
+                            OnXmlDictionaryReaderClose? onClose)
         {
             if (buffer == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer));
@@ -55,10 +56,10 @@ namespace System.Xml
         }
 
         public void SetInput(Stream stream,
-                             IXmlDictionary dictionary,
+                             IXmlDictionary? dictionary,
                             XmlDictionaryReaderQuotas quotas,
-                            XmlBinaryReaderSession session,
-                            OnXmlDictionaryReaderClose onClose)
+                            XmlBinaryReaderSession? session,
+                            OnXmlDictionaryReaderClose? onClose)
         {
             if (stream == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream));
@@ -67,7 +68,7 @@ namespace System.Xml
             _buffered = false;
         }
 
-        private void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose)
+        private void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session, OnXmlDictionaryReaderClose? onClose)
         {
             MoveToInitial(quotas);
             _maxBytesPerRead = quotas.MaxBytesPerRead;
@@ -726,14 +727,14 @@ namespace System.Xml
                         attributeNode = AddAttribute();
                         attributeNode.Prefix.SetValue(PrefixHandleType.Empty);
                         ReadName(attributeNode.LocalName);
-                        ReadAttributeText(attributeNode.AttributeText);
+                        ReadAttributeText(attributeNode.AttributeText!);
                         break;
                     case XmlBinaryNodeType.Attribute:
                         SkipNodeType();
                         attributeNode = AddAttribute();
                         ReadName(attributeNode.Prefix);
                         ReadName(attributeNode.LocalName);
-                        ReadAttributeText(attributeNode.AttributeText);
+                        ReadAttributeText(attributeNode.AttributeText!);
                         FixXmlAttribute(attributeNode);
                         break;
                     case XmlBinaryNodeType.ShortDictionaryAttribute:
@@ -741,14 +742,14 @@ namespace System.Xml
                         attributeNode = AddAttribute();
                         attributeNode.Prefix.SetValue(PrefixHandleType.Empty);
                         ReadDictionaryName(attributeNode.LocalName);
-                        ReadAttributeText(attributeNode.AttributeText);
+                        ReadAttributeText(attributeNode.AttributeText!);
                         break;
                     case XmlBinaryNodeType.DictionaryAttribute:
                         SkipNodeType();
                         attributeNode = AddAttribute();
                         ReadName(attributeNode.Prefix);
                         ReadDictionaryName(attributeNode.LocalName);
-                        ReadAttributeText(attributeNode.AttributeText);
+                        ReadAttributeText(attributeNode.AttributeText!);
                         break;
                     case XmlBinaryNodeType.XmlnsAttribute:
                         SkipNodeType();
@@ -809,7 +810,7 @@ namespace System.Xml
                         prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryAttributeA);
                         attributeNode.Prefix.SetValue(prefix);
                         ReadDictionaryName(attributeNode.LocalName);
-                        ReadAttributeText(attributeNode.AttributeText);
+                        ReadAttributeText(attributeNode.AttributeText!);
                         break;
                     case XmlBinaryNodeType.PrefixAttributeA:
                     case XmlBinaryNodeType.PrefixAttributeB:
@@ -842,7 +843,7 @@ namespace System.Xml
                         prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixAttributeA);
                         attributeNode.Prefix.SetValue(prefix);
                         ReadName(attributeNode.LocalName);
-                        ReadAttributeText(attributeNode.AttributeText);
+                        ReadAttributeText(attributeNode.AttributeText!);
                         break;
                     default:
                         ProcessAttributes();
@@ -1146,7 +1147,7 @@ namespace System.Xml
             }
         }
 
-        public override bool IsStartArray(out Type type)
+        public override bool IsStartArray([NotNullWhen(true)] out Type? type)
         {
             type = null;
             if (_arrayState != ArrayState.Element)
index 1d8fddf..db7c46c 100644 (file)
@@ -5,6 +5,7 @@ using StringHandle = System.Int64;
 using System.Xml;
 using System.Collections.Generic;
 using System.Runtime.Serialization;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
@@ -12,8 +13,8 @@ namespace System.Xml
     {
         private const int MaxArrayEntries = 2048;
 
-        private XmlDictionaryString[] _strings;
-        private Dictionary<int, XmlDictionaryString> _stringDict;
+        private XmlDictionaryString[]? _strings;
+        private Dictionary<int, XmlDictionaryString>? _stringDict;
 
         public XmlBinaryReaderSession()
         {
@@ -25,7 +26,7 @@ namespace System.Xml
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(id), SR.XmlInvalidID));
             if (value == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value));
-            XmlDictionaryString xmlString;
+            XmlDictionaryString? xmlString;
             if (TryLookup(id, out xmlString))
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlIDDefined));
 
@@ -54,7 +55,7 @@ namespace System.Xml
             return xmlString;
         }
 
-        public bool TryLookup(int key, out XmlDictionaryString result)
+        public bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? result)
         {
             if (_strings != null && key >= 0 && key < _strings.Length)
             {
@@ -70,7 +71,7 @@ namespace System.Xml
             return false;
         }
 
-        public bool TryLookup(string value, out XmlDictionaryString result)
+        public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result)
         {
             if (value == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value));
@@ -104,7 +105,7 @@ namespace System.Xml
             return false;
         }
 
-        public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result)
+        public bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result)
         {
             if (value == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value)));
index 845d948..c353ce3 100644 (file)
@@ -17,13 +17,13 @@ namespace System.Xml
 {
     public interface IXmlBinaryWriterInitializer
     {
-        void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream);
+        void SetOutput(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream);
     }
 
     internal class XmlBinaryNodeWriter : XmlStreamNodeWriter
     {
-        private IXmlDictionary _dictionary;
-        private XmlBinaryWriterSession _session;
+        private IXmlDictionary? _dictionary;
+        private XmlBinaryWriterSession? _session;
         private bool _inAttribute;
         private bool _inList;
         private bool _wroteAttributeValue;
@@ -39,7 +39,7 @@ namespace System.Xml
                                           (int)XmlBinaryNodeType.MaxText < 256, "NodeTypes enumeration messed up");
         }
 
-        public void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream)
+        public void SetOutput(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream)
         {
             _dictionary = dictionary;
             _session = session;
@@ -141,9 +141,9 @@ namespace System.Xml
         {
         }
 
-        public override void WriteStartElement(string prefix, string localName)
+        public override void WriteStartElement(string? prefix, string localName)
         {
-            if (prefix.Length == 0)
+            if (string.IsNullOrEmpty(prefix))
             {
                 WriteNode(XmlBinaryNodeType.ShortElement);
                 WriteName(localName);
@@ -171,7 +171,7 @@ namespace System.Xml
             WriteNode((XmlBinaryNodeType)((int)nodeType + ch));
         }
 
-        public override void WriteStartElement(string prefix, XmlDictionaryString localName)
+        public override void WriteStartElement(string? prefix, XmlDictionaryString localName)
         {
             int key;
             if (!TryGetKey(localName, out key))
@@ -180,7 +180,7 @@ namespace System.Xml
             }
             else
             {
-                if (prefix.Length == 0)
+                if (string.IsNullOrEmpty(prefix))
                 {
                     WriteNode(XmlBinaryNodeType.ShortDictionaryElement);
                     WriteDictionaryString(localName, key);
@@ -212,7 +212,7 @@ namespace System.Xml
             }
         }
 
-        public override void WriteEndElement(string prefix, string localName)
+        public override void WriteEndElement(string? prefix, string localName)
         {
             WriteEndElement();
         }
@@ -303,9 +303,9 @@ namespace System.Xml
             _textNodeOffset = -1;
         }
 
-        public override void WriteXmlnsAttribute(string prefix, string ns)
+        public override void WriteXmlnsAttribute(string? prefix, string ns)
         {
-            if (prefix.Length == 0)
+            if (string.IsNullOrEmpty(prefix))
             {
                 WriteNode(XmlBinaryNodeType.ShortXmlnsAttribute);
                 WriteName(ns);
@@ -318,7 +318,7 @@ namespace System.Xml
             }
         }
 
-        public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
+        public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns)
         {
             int key;
             if (!TryGetKey(ns, out key))
@@ -327,7 +327,7 @@ namespace System.Xml
             }
             else
             {
-                if (prefix.Length == 0)
+                if (string.IsNullOrEmpty(prefix))
                 {
                     WriteNode(XmlBinaryNodeType.ShortDictionaryXmlnsAttribute);
                     WriteDictionaryString(ns, key);
@@ -349,7 +349,7 @@ namespace System.Xml
                 key = s.Key * 2;
                 return true;
             }
-            XmlDictionaryString t;
+            XmlDictionaryString? t;
             if (_dictionary != null && _dictionary.TryLookup(s, out t))
             {
                 DiagnosticUtility.DebugAssert(t.Dictionary == _dictionary, "");
@@ -549,7 +549,7 @@ namespace System.Xml
             Advance(8);
         }
 
-        public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] base64Buffer, int base64Offset, int base64Count)
+        public override void WriteBase64Text(byte[]? trailBytes, int trailByteCount, byte[] base64Buffer, int base64Offset, int base64Count)
         {
             if (_inAttribute)
             {
@@ -566,7 +566,7 @@ namespace System.Xml
                         int offset;
                         byte[] buffer = GetBuffer(trailByteCount, out offset);
                         for (int i = 0; i < trailByteCount; i++)
-                            buffer[offset + i] = trailBytes[i];
+                            buffer[offset + i] = trailBytes![i];
                         Advance(trailByteCount);
                     }
                     if (base64Count > 0)
@@ -968,9 +968,9 @@ namespace System.Xml
 
         private struct AttributeValue
         {
-            private string _captureText;
-            private XmlDictionaryString _captureXText;
-            private MemoryStream _captureStream;
+            private string? _captureText;
+            private XmlDictionaryString? _captureXText;
+            private MemoryStream? _captureStream;
 
             public void Clear()
             {
@@ -986,7 +986,7 @@ namespace System.Xml
                     ArraySegment<byte> arraySegment;
                     bool result = _captureStream.TryGetBuffer(out arraySegment);
                     DiagnosticUtility.DebugAssert(result, "");
-                    _captureText = XmlConverter.Base64Encoding.GetString(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
+                    _captureText = XmlConverter.Base64Encoding.GetString(arraySegment.Array!, arraySegment.Offset, arraySegment.Count);
                     _captureStream = null;
                 }
 
@@ -1018,13 +1018,13 @@ namespace System.Xml
                 }
             }
 
-            public void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count)
+            public void WriteBase64Text(byte[]? trailBytes, int trailByteCount, byte[] buffer, int offset, int count)
             {
                 if (_captureText != null || _captureXText != null)
                 {
                     if (trailByteCount > 0)
                     {
-                        WriteText(XmlConverter.Base64Encoding.GetString(trailBytes, 0, trailByteCount));
+                        WriteText(XmlConverter.Base64Encoding.GetString(trailBytes!, 0, trailByteCount));
                     }
                     WriteText(XmlConverter.Base64Encoding.GetString(buffer, offset, count));
                 }
@@ -1034,7 +1034,7 @@ namespace System.Xml
                         _captureStream = new MemoryStream();
 
                     if (trailByteCount > 0)
-                        _captureStream.Write(trailBytes, 0, trailByteCount);
+                        _captureStream.Write(trailBytes!, 0, trailByteCount);
 
                     _captureStream.Write(buffer, offset, count);
                 }
@@ -1057,7 +1057,7 @@ namespace System.Xml
                     ArraySegment<byte> arraySegment;
                     bool result = _captureStream.TryGetBuffer(out arraySegment);
                     DiagnosticUtility.DebugAssert(result, "");
-                    writer.WriteBase64Text(null, 0, arraySegment.Array, arraySegment.Offset, arraySegment.Count);
+                    writer.WriteBase64Text(null, 0, arraySegment.Array!, arraySegment.Offset, arraySegment.Count);
                     _captureStream = null;
                 }
                 else
@@ -1070,12 +1070,12 @@ namespace System.Xml
 
     internal class XmlBinaryWriter : XmlBaseWriter, IXmlBinaryWriterInitializer
     {
-        private XmlBinaryNodeWriter _writer;
-        private char[] _chars;
-        private byte[] _bytes;
+        private XmlBinaryNodeWriter _writer = null!; // initialized in SetOutput
+        private char[]? _chars;
+        private byte[]? _bytes;
 
 
-        public void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream)
+        public void SetOutput(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream)
         {
             if (stream == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(stream)));
@@ -1095,7 +1095,7 @@ namespace System.Xml
             Type type = reader.ValueType;
             if (type == typeof(string))
             {
-                XmlDictionaryString value;
+                XmlDictionaryString? value;
                 if (reader.TryGetValueAsDictionaryString(out value))
                 {
                     WriteString(value);
@@ -1172,7 +1172,7 @@ namespace System.Xml
                 WriteValue(reader.ReadContentAsObject());
         }
 
-        private void WriteStartArray(string prefix, string localName, string namespaceUri, int count)
+        private void WriteStartArray(string? prefix, string localName, string? namespaceUri, int count)
         {
             StartArray(count);
             _writer.WriteArrayNode();
@@ -1180,7 +1180,7 @@ namespace System.Xml
             WriteEndElement();
         }
 
-        private void WriteStartArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int count)
+        private void WriteStartArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, int count)
         {
             StartArray(count);
             _writer.WriteArrayNode();
@@ -1193,7 +1193,7 @@ namespace System.Xml
             EndArray();
         }
 
-        private unsafe void UnsafeWriteArray(string prefix, string localName, string namespaceUri,
+        private unsafe void UnsafeWriteArray(string? prefix, string localName, string? namespaceUri,
                                XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax)
         {
             WriteStartArray(prefix, localName, namespaceUri, count);
@@ -1201,7 +1201,7 @@ namespace System.Xml
             WriteEndArray();
         }
 
-        private unsafe void UnsafeWriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri,
+        private unsafe void UnsafeWriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri,
                                XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax)
         {
             WriteStartArray(prefix, localName, namespaceUri, count);
@@ -1223,7 +1223,7 @@ namespace System.Xml
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
         }
 
-        public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, bool[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1237,7 +1237,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, bool[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1251,7 +1251,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, short[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1265,7 +1265,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, short[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1279,7 +1279,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, int[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1293,7 +1293,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, int[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1307,7 +1307,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, long[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1321,7 +1321,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, long[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1335,7 +1335,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, float[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1349,7 +1349,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, float[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1363,7 +1363,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, double[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1377,7 +1377,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, double[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1391,7 +1391,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, decimal[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1405,7 +1405,7 @@ namespace System.Xml
             }
         }
 
-        public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
+        public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, decimal[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1420,7 +1420,7 @@ namespace System.Xml
         }
 
         // DateTime
-        public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, DateTime[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1433,7 +1433,7 @@ namespace System.Xml
             }
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, DateTime[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1447,7 +1447,7 @@ namespace System.Xml
         }
 
         // Guid
-        public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, Guid[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1460,7 +1460,7 @@ namespace System.Xml
             }
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, Guid[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1474,7 +1474,7 @@ namespace System.Xml
         }
 
         // TimeSpan
-        public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, TimeSpan[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
@@ -1487,7 +1487,7 @@ namespace System.Xml
             }
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, TimeSpan[] array, int offset, int count)
         {
             {
                 CheckArray(array, offset, count);
index 2bed1f3..1f2078d 100644 (file)
@@ -8,7 +8,7 @@ using System.Diagnostics;
 using System.Runtime.Serialization;
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
-
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
@@ -27,7 +27,7 @@ namespace System.Xml
 
         public virtual bool TryAdd(XmlDictionaryString value, out int key)
         {
-            IntArray keys;
+            IntArray? keys;
             if (value == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value));
 
@@ -75,7 +75,7 @@ namespace System.Xml
 
         internal bool TryLookup(XmlDictionaryString s, out int key)
         {
-            IntArray keys;
+            IntArray? keys;
             if (_maps.TryGetValue(s.Dictionary, out keys))
             {
                 key = (keys[s.Key] - 1);
@@ -103,7 +103,7 @@ namespace System.Xml
 
         private class PriorityDictionary<K, V> where K : class
         {
-            private Dictionary<K, V> _dictionary;
+            private Dictionary<K, V>? _dictionary;
             private readonly Entry[] _list;
             private int _listCount;
             private int _now;
@@ -122,7 +122,7 @@ namespace System.Xml
                     _dictionary.Clear();
             }
 
-            public bool TryGetValue(K key, out V value)
+            public bool TryGetValue(K key, [MaybeNullWhen(false)] out V value)
             {
                 for (int i = 0; i < _listCount; i++)
                 {
index f8357c8..20956f5 100644 (file)
@@ -18,20 +18,20 @@ namespace System.Xml
     internal class XmlBufferReader
     {
         private readonly XmlDictionaryReader _reader;
-        private Stream _stream;
-        private byte[] _streamBuffer;
-        private byte[] _buffer;
+        private Stream? _stream;
+        private byte[]? _streamBuffer;
+        private byte[] _buffer = null!; // initialized by SetBuffer
         private int _offsetMin;
         private int _offsetMax;
-        private IXmlDictionary _dictionary;
-        private XmlBinaryReaderSession _session;
-        private byte[] _guid;
+        private IXmlDictionary? _dictionary;
+        private XmlBinaryReaderSession? _session;
+        private byte[]? _guid;
         private int _offset;
         private const int maxBytesPerChar = 3;
-        private char[] _chars;
+        private char[]? _chars;
         private int _windowOffset;
         private int _windowOffsetMax;
-        private ValueHandle _listValue;
+        private ValueHandle? _listValue;
         private static readonly XmlBufferReader s_empty = new XmlBufferReader(Array.Empty<byte>());
 
         public XmlBufferReader(XmlDictionaryReader reader)
@@ -41,7 +41,7 @@ namespace System.Xml
 
         public XmlBufferReader(byte[] buffer)
         {
-            _reader = null;
+            _reader = null!; // this ctor is only used in 2 places internally, which will never touch _reader
             _buffer = buffer;
         }
 
@@ -70,7 +70,7 @@ namespace System.Xml
         }
 
 
-        public void SetBuffer(Stream stream, IXmlDictionary dictionary, XmlBinaryReaderSession session)
+        public void SetBuffer(Stream stream, IXmlDictionary? dictionary, XmlBinaryReaderSession? session)
         {
             if (_streamBuffer == null)
             {
@@ -81,12 +81,12 @@ namespace System.Xml
             _windowOffsetMax = _streamBuffer.Length;
         }
 
-        public void SetBuffer(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlBinaryReaderSession session)
+        public void SetBuffer(byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlBinaryReaderSession? session)
         {
             SetBuffer(null, buffer, offset, count, dictionary, session);
         }
 
-        private void SetBuffer(Stream stream, byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlBinaryReaderSession session)
+        private void SetBuffer(Stream? stream, byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlBinaryReaderSession? session)
         {
             _stream = stream;
             _buffer = buffer;
@@ -1114,8 +1114,8 @@ namespace System.Xml
                     XmlBinaryNodeType nodeType = GetNodeType();
                     SkipNodeType();
                     DiagnosticUtility.DebugAssert(nodeType != XmlBinaryNodeType.StartListText, "");
-                    ReadValue(nodeType, _listValue);
-                    objects[i] = _listValue.ToObject();
+                    ReadValue(nodeType, _listValue!);
+                    objects[i] = _listValue!.ToObject();
                 }
                 return objects;
             }
@@ -1131,13 +1131,13 @@ namespace System.Xml
             IXmlDictionary keyDictionary;
             if ((key & 1) != 0)
             {
-                keyDictionary = _session;
+                keyDictionary = _session!;
             }
             else
             {
-                keyDictionary = _dictionary;
+                keyDictionary = _dictionary!;
             }
-            XmlDictionaryString s;
+            XmlDictionaryString? s;
             if (!keyDictionary.TryLookup(key >> 1, out s))
                 XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader);
             return s;
@@ -1151,7 +1151,7 @@ namespace System.Xml
                 if (_session == null)
                     XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader);
                 int sessionKey = (key >> 1);
-                XmlDictionaryString xmlString;
+                XmlDictionaryString? xmlString;
                 if (!_session.TryLookup(sessionKey, out xmlString))
                 {
                     if (sessionKey < XmlDictionaryString.MinKey || sessionKey > XmlDictionaryString.MaxKey)
@@ -1164,7 +1164,7 @@ namespace System.Xml
                 if (_dictionary == null)
                     XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader);
                 int staticKey = (key >> 1);
-                XmlDictionaryString xmlString;
+                XmlDictionaryString? xmlString;
                 if (!_dictionary.TryLookup(staticKey, out xmlString))
                 {
                     if (staticKey < XmlDictionaryString.MinKey || staticKey > XmlDictionaryString.MaxKey)
index e7167b7..2bfed4e 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 using System.Collections;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.IO;
 using System.Runtime;
 using System.Runtime.Serialization;
@@ -12,25 +14,25 @@ namespace System.Xml
 {
     internal sealed class XmlCanonicalWriter
     {
-        private XmlUTF8NodeWriter _writer;
-        private MemoryStream _elementStream;
-        private byte[] _elementBuffer;
-        private XmlUTF8NodeWriter _elementWriter;
+        private XmlUTF8NodeWriter _writer = null!; // initialized in SetOutput
+        private MemoryStream _elementStream = null!; // initialized in SetOutput
+        private byte[]? _elementBuffer;
+        private XmlUTF8NodeWriter _elementWriter = null!; // initialized in SetOutput
         private bool _inStartElement;
         private int _depth;
-        private Scope[] _scopes;
+        private Scope[]? _scopes;
         private int _xmlnsAttributeCount;
-        private XmlnsAttribute[] _xmlnsAttributes;
+        private XmlnsAttribute[]? _xmlnsAttributes;
         private int _attributeCount;
-        private Attribute[] _attributes;
+        private Attribute[]? _attributes;
         private Attribute _attribute;
         private Element _element;
-        private byte[] _xmlnsBuffer;
+        private byte[]? _xmlnsBuffer;
         private int _xmlnsOffset;
         private const int maxBytesPerChar = 3;
         private int _xmlnsStartOffset;
         private bool _includeComments;
-        private string[] _inclusivePrefixes;
+        private string[]? _inclusivePrefixes;
         private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/";
 
         private static readonly bool[] s_isEscapedAttributeChar = new bool[]
@@ -52,7 +54,7 @@ namespace System.Xml
         {
         }
 
-        public void SetOutput(Stream stream, bool includeComments, string[] inclusivePrefixes)
+        public void SetOutput(Stream stream, bool includeComments, string[]? inclusivePrefixes)
         {
             if (stream == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream));
@@ -124,7 +126,7 @@ namespace System.Xml
             if (_elementWriter != null)
                 _elementWriter.Close();
             if (_elementStream != null && _elementStream.Length > 512)
-                _elementStream = null;
+                _elementStream = null!;
             _elementBuffer = null;
             if (_scopes != null && _scopes.Length > 16)
                 _scopes = null;
@@ -153,7 +155,7 @@ namespace System.Xml
             }
         }
 
-
+        [MemberNotNull(nameof(_scopes))]
         private void StartElement()
         {
             if (_scopes == null)
@@ -177,7 +179,7 @@ namespace System.Xml
         private void EndElement()
         {
             _depth--;
-            _xmlnsAttributeCount = _scopes[_depth].xmlnsAttributeCount;
+            _xmlnsAttributeCount = _scopes![_depth].xmlnsAttributeCount;
             _xmlnsOffset = _scopes[_depth].xmlnsOffset;
         }
 
@@ -204,7 +206,7 @@ namespace System.Xml
                 // Scan through all the namespace declarations in the outer scope.
                 for (int i = 0; i < _scopes[0].xmlnsAttributeCount; ++i)
                 {
-                    if (IsInclusivePrefix(ref _xmlnsAttributes[i]))
+                    if (IsInclusivePrefix(ref _xmlnsAttributes![i]))
                     {
                         XmlnsAttribute attribute = _xmlnsAttributes[i];
                         AddXmlnsAttribute(ref attribute);
@@ -253,7 +255,7 @@ namespace System.Xml
                 // Scan through all the namespace declarations in the outer scope.
                 for (int i = 0; i < _scopes[0].xmlnsAttributeCount; ++i)
                 {
-                    if (IsInclusivePrefix(ref _xmlnsAttributes[i]))
+                    if (IsInclusivePrefix(ref _xmlnsAttributes![i]))
                     {
                         XmlnsAttribute attribute = _xmlnsAttributes[i];
                         AddXmlnsAttribute(ref attribute);
@@ -264,11 +266,11 @@ namespace System.Xml
 
         private bool IsInclusivePrefix(ref XmlnsAttribute xmlnsAttribute)
         {
-            for (int i = 0; i < _inclusivePrefixes.Length; ++i)
+            for (int i = 0; i < _inclusivePrefixes!.Length; ++i)
             {
                 if (_inclusivePrefixes[i].Length == xmlnsAttribute.prefixLength)
                 {
-                    if (string.Compare(Encoding.UTF8.GetString(_xmlnsBuffer, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength), _inclusivePrefixes[i], StringComparison.Ordinal) == 0)
+                    if (string.Compare(Encoding.UTF8.GetString(_xmlnsBuffer!, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength), _inclusivePrefixes[i], StringComparison.Ordinal) == 0)
                     {
                         return true;
                     }
@@ -286,14 +288,15 @@ namespace System.Xml
             _inStartElement = false;
             ResolvePrefixes();
             _writer.WriteStartElement(_elementBuffer, _element.prefixOffset, _element.prefixLength, _elementBuffer, _element.localNameOffset, _element.localNameLength);
-            for (int i = _scopes[_depth - 1].xmlnsAttributeCount; i < _xmlnsAttributeCount; i++)
+            for (int i = _scopes![_depth - 1].xmlnsAttributeCount; i < _xmlnsAttributeCount; i++)
             {
                 // Check if this prefix with the same namespace has already been rendered.
                 int j = i - 1;
                 bool alreadyReferred = false;
                 while (j >= 0)
                 {
-                    if (Equals(_xmlnsBuffer, _xmlnsAttributes[i].prefixOffset, _xmlnsAttributes[i].prefixLength, _xmlnsBuffer, _xmlnsAttributes[j].prefixOffset, _xmlnsAttributes[j].prefixLength))
+                    Debug.Assert(_xmlnsBuffer != null);
+                    if (Equals(_xmlnsBuffer, _xmlnsAttributes![i].prefixOffset, _xmlnsAttributes[i].prefixLength, _xmlnsBuffer, _xmlnsAttributes[j].prefixOffset, _xmlnsAttributes[j].prefixLength))
                     {
                         // Check if the namespace is also equal.
                         if (Equals(_xmlnsBuffer, _xmlnsAttributes[i].nsOffset, _xmlnsAttributes[i].nsLength, _xmlnsBuffer, _xmlnsAttributes[j].nsOffset, _xmlnsAttributes[j].nsLength))
@@ -320,7 +323,7 @@ namespace System.Xml
 
                 if (!alreadyReferred)
                 {
-                    WriteXmlnsAttribute(ref _xmlnsAttributes[i]);
+                    WriteXmlnsAttribute(ref _xmlnsAttributes![i]);
                 }
             }
             if (_attributeCount > 0)
@@ -332,7 +335,7 @@ namespace System.Xml
 
                 for (int i = 0; i < _attributeCount; i++)
                 {
-                    _writer.WriteText(_elementBuffer, _attributes[i].offset, _attributes[i].length);
+                    _writer.WriteText(_elementBuffer, _attributes![i].offset, _attributes[i].length);
                 }
             }
             _writer.WriteEndStartElement(false);
@@ -355,6 +358,7 @@ namespace System.Xml
             EndElement();
         }
 
+        [MemberNotNull(nameof(_xmlnsBuffer))]
         private void EnsureXmlnsBuffer(int byteCount)
         {
             if (_xmlnsBuffer == null)
@@ -369,6 +373,7 @@ namespace System.Xml
             }
         }
 
+        [MemberNotNull(nameof(_xmlnsAttributes))]
         public void WriteXmlnsAttribute(string prefix, string ns)
         {
             if (prefix == null)
@@ -393,6 +398,7 @@ namespace System.Xml
             AddXmlnsAttribute(ref xmlnsAttribute);
         }
 
+        [MemberNotNull(nameof(_xmlnsAttributes))]
         public void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength)
         {
             if (prefixBuffer == null)
@@ -693,6 +699,7 @@ namespace System.Xml
         {
             if (xmlnsAttribute.referred)
             {
+                Debug.Assert(_xmlnsBuffer != null);
                 _writer.WriteXmlnsAttribute(_xmlnsBuffer, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength, _xmlnsBuffer, xmlnsAttribute.nsOffset, xmlnsAttribute.nsLength);
             }
         }
@@ -706,7 +713,7 @@ namespace System.Xml
                     int attributeMin = i;
                     for (int j = i + 1; j < _attributeCount; j++)
                     {
-                        if (Compare(ref _attributes[j], ref _attributes[attributeMin]) < 0)
+                        if (Compare(ref _attributes![j], ref _attributes[attributeMin]) < 0)
                         {
                             attributeMin = j;
                         }
@@ -714,7 +721,7 @@ namespace System.Xml
 
                     if (attributeMin != i)
                     {
-                        Attribute temp = _attributes[i];
+                        Attribute temp = _attributes![i];
                         _attributes[i] = _attributes[attributeMin];
                         _attributes[attributeMin] = temp;
                     }
@@ -743,6 +750,7 @@ namespace System.Xml
             _attributeCount++;
         }
 
+        [MemberNotNull(nameof(_xmlnsAttributes))]
         private void AddXmlnsAttribute(ref XmlnsAttribute xmlnsAttribute)
         {
             //            Console.WriteLine("{0}={1}", Encoding.UTF8.GetString(xmlnsBuffer, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength),
@@ -778,7 +786,7 @@ namespace System.Xml
             else
             {
                 // Sort the xmlns xmlnsAttribute
-                int xmlnsAttributeIndex = _scopes[_depth - 1].xmlnsAttributeCount;
+                int xmlnsAttributeIndex = _scopes![_depth - 1].xmlnsAttributeCount;
                 bool isNewPrefix = true;
                 while (xmlnsAttributeIndex < _xmlnsAttributeCount)
                 {
@@ -812,13 +820,13 @@ namespace System.Xml
 
         private void ResolvePrefix(int prefixOffset, int prefixLength, out int nsOffset, out int nsLength)
         {
-            int xmlnsAttributeMin = _scopes[_depth - 1].xmlnsAttributeCount;
+            int xmlnsAttributeMin = _scopes![_depth - 1].xmlnsAttributeCount;
 
             // Lookup the attribute; it has to be there.  The decls are in sorted order
             // so we could do a binary search.
             int j = _xmlnsAttributeCount - 1;
-            while (!Equals(_elementBuffer, prefixOffset, prefixLength,
-                           _xmlnsBuffer, _xmlnsAttributes[j].prefixOffset, _xmlnsAttributes[j].prefixLength))
+            while (!Equals(_elementBuffer!, prefixOffset, prefixLength,
+                           _xmlnsBuffer!, _xmlnsAttributes![j].prefixOffset, _xmlnsAttributes[j].prefixLength))
             {
                 j--;
             }
@@ -866,26 +874,26 @@ namespace System.Xml
 
             for (int i = 0; i < _attributeCount; i++)
             {
-                ResolvePrefix(ref _attributes[i]);
+                ResolvePrefix(ref _attributes![i]);
             }
         }
 
         private int Compare(ref XmlnsAttribute xmlnsAttribute1, ref XmlnsAttribute xmlnsAttribute2)
         {
-            return Compare(_xmlnsBuffer,
+            return Compare(_xmlnsBuffer!,
                            xmlnsAttribute1.prefixOffset, xmlnsAttribute1.prefixLength,
                            xmlnsAttribute2.prefixOffset, xmlnsAttribute2.prefixLength);
         }
 
         private int Compare(ref Attribute attribute1, ref Attribute attribute2)
         {
-            int s = Compare(_xmlnsBuffer,
+            int s = Compare(_xmlnsBuffer!,
                             attribute1.nsOffset, attribute1.nsLength,
                             attribute2.nsOffset, attribute2.nsLength);
 
             if (s == 0)
             {
-                s = Compare(_elementBuffer,
+                s = Compare(_elementBuffer!,
                             attribute1.localNameOffset, attribute1.localNameLength,
                             attribute2.localNameOffset, attribute2.localNameLength);
             }
@@ -961,7 +969,7 @@ namespace System.Xml
 
                 Array.Sort(indeces, this);
 
-                Attribute[] attributes = new Attribute[_writer._attributes.Length];
+                Attribute[] attributes = new Attribute[_writer._attributes!.Length];
                 for (int i = 0; i < indeces.Length; i++)
                 {
                     attributes[i] = _writer._attributes[(int)indeces[i]];
@@ -970,11 +978,11 @@ namespace System.Xml
                 _writer._attributes = attributes;
             }
 
-            public int Compare(object obj1, object obj2)
+            public int Compare(object? obj1, object? obj2)
             {
-                int attributeIndex1 = (int)obj1;
-                int attributeIndex2 = (int)obj2;
-                return _writer.Compare(ref _writer._attributes[attributeIndex1], ref _writer._attributes[attributeIndex2]);
+                int attributeIndex1 = (int)obj1!;
+                int attributeIndex2 = (int)obj2!;
+                return _writer.Compare(ref _writer._attributes![attributeIndex1], ref _writer._attributes[attributeIndex2]);
             }
         }
 
index 8badd61..f58260c 100644 (file)
@@ -30,10 +30,10 @@ namespace System.Xml
         public const int MaxUInt64Chars = 32;
         public const int MaxPrimitiveChars = MaxDateTimeChars;
 
-        private static UTF8Encoding s_utf8Encoding;
-        private static UnicodeEncoding s_unicodeEncoding;
+        private static UTF8Encoding? s_utf8Encoding;
+        private static UnicodeEncoding? s_unicodeEncoding;
 
-        private static Base64Encoding s_base64Encoding;
+        private static Base64Encoding? s_base64Encoding;
 
         public static Base64Encoding Base64Encoding
         {
@@ -456,7 +456,7 @@ namespace System.Xml
             else if (value is bool)
                 return ToString((bool)value);
             else
-                return value.ToString();
+                return value.ToString()!; // value can only be an object created by ToList()
         }
 
         public static string ToString(object[] objects)
index bd2326b..49d54b8 100644 (file)
@@ -9,15 +9,15 @@ using System.Collections.Generic;
 using System.Diagnostics;
 using System.Text;
 using System.Runtime.Serialization;
-
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
     public class XmlDictionary : IXmlDictionary
     {
-        private static IXmlDictionary s_empty;
+        private static IXmlDictionary? s_empty;
         private readonly Dictionary<string, XmlDictionaryString> _lookup;
-        private XmlDictionaryString[] _strings;
+        private XmlDictionaryString[]? _strings;
         private int _nextId;
 
         public static IXmlDictionary Empty
@@ -46,7 +46,7 @@ namespace System.Xml
 
         public virtual XmlDictionaryString Add(string value)
         {
-            XmlDictionaryString str;
+            XmlDictionaryString? str;
             if (!_lookup.TryGetValue(value, out str))
             {
                 if (_strings == null)
@@ -68,23 +68,23 @@ namespace System.Xml
             return str;
         }
 
-        public virtual bool TryLookup(string value, out XmlDictionaryString result)
+        public virtual bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result)
         {
             return _lookup.TryGetValue(value, out result);
         }
 
-        public virtual bool TryLookup(int key, out XmlDictionaryString result)
+        public virtual bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? result)
         {
             if (key < 0 || key >= _nextId)
             {
                 result = null;
                 return false;
             }
-            result = _strings[key];
+            result = _strings![key];
             return true;
         }
 
-        public virtual bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result)
+        public virtual bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result)
         {
             if (value == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value)));
@@ -99,19 +99,19 @@ namespace System.Xml
 
         private class EmptyDictionary : IXmlDictionary
         {
-            public bool TryLookup(string value, out XmlDictionaryString result)
+            public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result)
             {
                 result = null;
                 return false;
             }
 
-            public bool TryLookup(int key, out XmlDictionaryString result)
+            public bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? result)
             {
                 result = null;
                 return false;
             }
 
-            public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result)
+            public bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result)
             {
                 result = null;
                 return false;
index e2d186d..bf8e1bc 100644 (file)
@@ -14,7 +14,7 @@ namespace System.Xml
     internal class XmlDictionaryAsyncCheckWriter : XmlDictionaryWriter
     {
         private readonly XmlDictionaryWriter _coreWriter;
-        private Task _lastTask;
+        private Task? _lastTask;
 
         public XmlDictionaryAsyncCheckWriter(XmlDictionaryWriter writer)
         {
@@ -44,7 +44,7 @@ namespace System.Xml
             return task;
         }
 
-        public override XmlWriterSettings Settings
+        public override XmlWriterSettings? Settings
         {
             get
             {
@@ -62,7 +62,7 @@ namespace System.Xml
             }
         }
 
-        public override string XmlLang
+        public override string? XmlLang
         {
             get
             {
@@ -92,7 +92,7 @@ namespace System.Xml
             return SetLastTask(CoreWriter.FlushAsync());
         }
 
-        public override string LookupPrefix(string ns)
+        public override string? LookupPrefix(string ns)
         {
             CheckAsync();
             return CoreWriter.LookupPrefix(ns);
@@ -134,13 +134,13 @@ namespace System.Xml
             return SetLastTask(CoreWriter.WriteBinHexAsync(buffer, index, count));
         }
 
-        public override void WriteCData(string text)
+        public override void WriteCData(string? text)
         {
             CheckAsync();
             CoreWriter.WriteCData(text);
         }
 
-        public override Task WriteCDataAsync(string text)
+        public override Task WriteCDataAsync(string? text)
         {
             CheckAsync();
             return SetLastTask(CoreWriter.WriteCDataAsync(text));
@@ -170,25 +170,25 @@ namespace System.Xml
             return SetLastTask(CoreWriter.WriteCharsAsync(buffer, index, count));
         }
 
-        public override void WriteComment(string text)
+        public override void WriteComment(string? text)
         {
             CheckAsync();
             CoreWriter.WriteComment(text);
         }
 
-        public override Task WriteCommentAsync(string text)
+        public override Task WriteCommentAsync(string? text)
         {
             CheckAsync();
             return SetLastTask(CoreWriter.WriteCommentAsync(text));
         }
 
-        public override void WriteDocType(string name, string pubid, string sysid, string subset)
+        public override void WriteDocType(string name, string? pubid, string? sysid, string? subset)
         {
             CheckAsync();
             CoreWriter.WriteDocType(name, pubid, sysid, subset);
         }
 
-        public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset)
+        public override Task WriteDocTypeAsync(string name, string? pubid, string? sysid, string? subset)
         {
             CheckAsync();
             return SetLastTask(CoreWriter.WriteDocTypeAsync(name, pubid, sysid, subset));
@@ -284,25 +284,25 @@ namespace System.Xml
             return SetLastTask(CoreWriter.WriteNodeAsync(reader, defattr));
         }
 
-        public override void WriteProcessingInstruction(string name, string text)
+        public override void WriteProcessingInstruction(string name, string? text)
         {
             CheckAsync();
             CoreWriter.WriteProcessingInstruction(name, text);
         }
 
-        public override Task WriteProcessingInstructionAsync(string name, string text)
+        public override Task WriteProcessingInstructionAsync(string name, string? text)
         {
             CheckAsync();
             return SetLastTask(CoreWriter.WriteProcessingInstructionAsync(name, text));
         }
 
-        public override void WriteQualifiedName(string localName, string ns)
+        public override void WriteQualifiedName(string localName, string? ns)
         {
             CheckAsync();
             CoreWriter.WriteQualifiedName(localName, ns);
         }
 
-        public override Task WriteQualifiedNameAsync(string localName, string ns)
+        public override Task WriteQualifiedNameAsync(string localName, string? ns)
         {
             CheckAsync();
             return SetLastTask(CoreWriter.WriteQualifiedNameAsync(localName, ns));
@@ -332,7 +332,7 @@ namespace System.Xml
             return SetLastTask(CoreWriter.WriteRawAsync(buffer, index, count));
         }
 
-        public override void WriteStartAttribute(string prefix, string localName, string ns)
+        public override void WriteStartAttribute(string? prefix, string localName, string? ns)
         {
             CheckAsync();
             CoreWriter.WriteStartAttribute(prefix, localName, ns);
@@ -362,25 +362,25 @@ namespace System.Xml
             return SetLastTask(CoreWriter.WriteStartDocumentAsync(standalone));
         }
 
-        public override void WriteStartElement(string prefix, string localName, string ns)
+        public override void WriteStartElement(string? prefix, string localName, string? ns)
         {
             CheckAsync();
             CoreWriter.WriteStartElement(prefix, localName, ns);
         }
 
-        public override Task WriteStartElementAsync(string prefix, string localName, string ns)
+        public override Task WriteStartElementAsync(string? prefix, string localName, string? ns)
         {
             CheckAsync();
             return SetLastTask(CoreWriter.WriteStartElementAsync(prefix, localName, ns));
         }
 
-        public override void WriteString(string text)
+        public override void WriteString(string? text)
         {
             CheckAsync();
             CoreWriter.WriteString(text);
         }
 
-        public override Task WriteStringAsync(string text)
+        public override Task WriteStringAsync(string? text)
         {
             CheckAsync();
             return SetLastTask(CoreWriter.WriteStringAsync(text));
@@ -398,7 +398,7 @@ namespace System.Xml
             return SetLastTask(CoreWriter.WriteSurrogateCharEntityAsync(lowChar, highChar));
         }
 
-        public override void WriteValue(string value)
+        public override void WriteValue(string? value)
         {
             CheckAsync();
             CoreWriter.WriteValue(value);
@@ -452,67 +452,67 @@ namespace System.Xml
             CoreWriter.WriteValue(value);
         }
 
-        public override void WriteWhitespace(string ws)
+        public override void WriteWhitespace(string? ws)
         {
             CheckAsync();
             CoreWriter.WriteWhitespace(ws);
         }
 
-        public override Task WriteWhitespaceAsync(string ws)
+        public override Task WriteWhitespaceAsync(string? ws)
         {
             CheckAsync();
             return SetLastTask(CoreWriter.WriteWhitespaceAsync(ws));
         }
 
-        public override void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public override void WriteStartElement(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
             CheckAsync();
             CoreWriter.WriteStartElement(prefix, localName, namespaceUri);
         }
 
-        public override void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public override void WriteStartAttribute(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
             CheckAsync();
             CoreWriter.WriteStartAttribute(prefix, localName, namespaceUri);
         }
 
-        public override void WriteXmlnsAttribute(string prefix, string namespaceUri)
+        public override void WriteXmlnsAttribute(string? prefix, string namespaceUri)
         {
             CheckAsync();
             CoreWriter.WriteXmlnsAttribute(prefix, namespaceUri);
         }
 
-        public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri)
+        public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString namespaceUri)
         {
             CheckAsync();
             CoreWriter.WriteXmlnsAttribute(prefix, namespaceUri);
         }
 
-        public override void WriteXmlAttribute(string localName, string value)
+        public override void WriteXmlAttribute(string localName, string? value)
         {
             CheckAsync();
             CoreWriter.WriteXmlAttribute(localName, value);
         }
 
-        public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value)
+        public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString? value)
         {
             CheckAsync();
             CoreWriter.WriteXmlAttribute(localName, value);
         }
 
-        public override void WriteString(XmlDictionaryString value)
+        public override void WriteString(XmlDictionaryString? value)
         {
             CheckAsync();
             CoreWriter.WriteString(value);
         }
 
-        public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
             CheckAsync();
             CoreWriter.WriteQualifiedName(localName, namespaceUri);
         }
 
-        public override void WriteValue(XmlDictionaryString value)
+        public override void WriteValue(XmlDictionaryString? value)
         {
             CheckAsync();
             CoreWriter.WriteValue(value);
@@ -545,7 +545,7 @@ namespace System.Xml
             }
         }
 
-        public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
+        public override void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes)
         {
             CheckAsync();
             CoreWriter.StartCanonicalization(stream, includeComments, inclusivePrefixes);
@@ -563,121 +563,121 @@ namespace System.Xml
             CoreWriter.WriteNode(reader, defattr);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, bool[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, bool[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, short[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, short[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, int[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, int[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, long[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, long[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, float[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, float[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, double[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, double[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, decimal[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, decimal[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, DateTime[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, DateTime[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, Guid[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, Guid[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
+        public override void WriteArray(string? prefix, string localName, string? namespaceUri, TimeSpan[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
         }
 
-        public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
+        public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, TimeSpan[] array, int offset, int count)
         {
             CheckAsync();
             CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count);
index 16d9f55..79922c4 100644 (file)
@@ -9,7 +9,7 @@ using System.Diagnostics;
 using System.Text;
 using System.Runtime.Serialization;
 using System.Globalization;
-
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
@@ -24,7 +24,7 @@ namespace System.Xml
             if (reader == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(reader));
 
-            XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader;
+            XmlDictionaryReader? dictionaryReader = reader as XmlDictionaryReader;
 
             if (dictionaryReader == null)
             {
@@ -46,21 +46,21 @@ namespace System.Xml
             return CreateBinaryReader(buffer, offset, count, null, quotas);
         }
 
-        public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas)
+        public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas)
         {
             return CreateBinaryReader(buffer, offset, count, dictionary, quotas, null);
         }
 
-        public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session)
+        public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session)
         {
             return CreateBinaryReader(buffer, offset, count, dictionary, quotas, session, onClose: null);
         }
 
         public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count,
-                                                             IXmlDictionary dictionary,
+                                                             IXmlDictionary? dictionary,
                                                              XmlDictionaryReaderQuotas quotas,
-                                                             XmlBinaryReaderSession session,
-                                                             OnXmlDictionaryReaderClose onClose)
+                                                             XmlBinaryReaderSession? session,
+                                                             OnXmlDictionaryReaderClose? onClose)
         {
             XmlBinaryReader reader = new XmlBinaryReader();
             reader.SetInput(buffer, offset, count, dictionary, quotas, session, onClose);
@@ -72,21 +72,21 @@ namespace System.Xml
             return CreateBinaryReader(stream, null, quotas);
         }
 
-        public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas)
+        public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas)
         {
             return CreateBinaryReader(stream, dictionary, quotas, null);
         }
 
-        public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session)
+        public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session)
         {
             return CreateBinaryReader(stream, dictionary, quotas, session, onClose: null);
         }
 
         public static XmlDictionaryReader CreateBinaryReader(Stream stream,
-                                                             IXmlDictionary dictionary,
+                                                             IXmlDictionary? dictionary,
                                                              XmlDictionaryReaderQuotas quotas,
-                                                             XmlBinaryReaderSession session,
-                                                             OnXmlDictionaryReaderClose onClose)
+                                                             XmlBinaryReaderSession? session,
+                                                             OnXmlDictionaryReaderClose? onClose)
         {
             XmlBinaryReader reader = new XmlBinaryReader();
             reader.SetInput(stream, dictionary, quotas, session, onClose);
@@ -106,9 +106,9 @@ namespace System.Xml
         }
 
         public static XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count,
-                                                           Encoding encoding,
+                                                           Encoding? encoding,
                                                            XmlDictionaryReaderQuotas quotas,
-                                                           OnXmlDictionaryReaderClose onClose)
+                                                           OnXmlDictionaryReaderClose? onClose)
         {
             XmlUTF8TextReader reader = new XmlUTF8TextReader();
             reader.SetInput(buffer, offset, count, encoding, quotas, onClose);
@@ -120,9 +120,9 @@ namespace System.Xml
             return CreateTextReader(stream, null, quotas, null);
         }
 
-        public static XmlDictionaryReader CreateTextReader(Stream stream, Encoding encoding,
+        public static XmlDictionaryReader CreateTextReader(Stream stream, Encoding? encoding,
                                                            XmlDictionaryReaderQuotas quotas,
-                                                           OnXmlDictionaryReaderClose onClose)
+                                                           OnXmlDictionaryReaderClose? onClose)
         {
             XmlUTF8TextReader reader = new XmlUTF8TextReader();
             reader.SetInput(stream, encoding, quotas, onClose);
@@ -142,13 +142,13 @@ namespace System.Xml
             return CreateMtomReader(stream, encodings, null, quotas);
         }
 
-        public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas)
+        public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string? contentType, XmlDictionaryReaderQuotas quotas)
         {
             return CreateMtomReader(stream, encodings, contentType, quotas, int.MaxValue, null);
         }
 
-        public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType,
-            XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose)
+        public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string? contentType,
+            XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose? onClose)
         {
             throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding);
         }
@@ -166,13 +166,13 @@ namespace System.Xml
             return CreateMtomReader(buffer, offset, count, encodings, null, quotas);
         }
 
-        public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas)
+        public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string? contentType, XmlDictionaryReaderQuotas quotas)
         {
             return CreateMtomReader(buffer, offset, count, encodings, contentType, quotas, int.MaxValue, null);
         }
 
-        public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType,
-            XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose)
+        public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string? contentType,
+            XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose? onClose)
         {
             throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding);
         }
@@ -193,7 +193,7 @@ namespace System.Xml
             }
         }
 
-        public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
+        public virtual void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
         }
@@ -349,7 +349,7 @@ namespace System.Xml
             return -1;
         }
 
-        public virtual string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public virtual string? GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
         {
             return GetAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
         }
@@ -399,7 +399,7 @@ namespace System.Xml
 
         protected string ReadContentAsString(int maxStringContentLength)
         {
-            StringBuilder sb = null;
+            StringBuilder? sb = null;
             string result = string.Empty;
             bool done = false;
             while (true)
@@ -480,7 +480,7 @@ namespace System.Xml
                 if (this.NodeType == XmlNodeType.EndElement)
                     return string.Empty;
             }
-            StringBuilder sb = null;
+            StringBuilder? sb = null;
             string result = string.Empty;
             while (IsTextNode(this.NodeType))
             {
@@ -599,7 +599,7 @@ namespace System.Xml
             return read;
         }
 
-        public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver)
+        public override object ReadContentAs(Type type, IXmlNamespaceResolver? namespaceResolver)
         {
             if (type == typeof(Guid[]))
             {
@@ -689,7 +689,7 @@ namespace System.Xml
         {
             string prefix;
             XmlConverter.ToQualifiedName(ReadContentAsString(), out prefix, out localName);
-            namespaceUri = LookupNamespace(prefix);
+            namespaceUri = LookupNamespace(prefix)!;
             if (namespaceUri == null)
                 XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix);
         }
@@ -998,19 +998,19 @@ namespace System.Xml
             namespaceUri = NamespaceURI;
         }
 
-        public virtual bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName)
+        public virtual bool TryGetLocalNameAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? localName)
         {
             localName = null;
             return false;
         }
 
-        public virtual bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString namespaceUri)
+        public virtual bool TryGetNamespaceUriAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? namespaceUri)
         {
             namespaceUri = null;
             return false;
         }
 
-        public virtual bool TryGetValueAsDictionaryString(out XmlDictionaryString value)
+        public virtual bool TryGetValueAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? value)
         {
             value = null;
             return false;
@@ -1030,7 +1030,7 @@ namespace System.Xml
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
         }
 
-        public virtual bool IsStartArray(out Type type)
+        public virtual bool IsStartArray([NotNullWhen(true)] out Type? type)
         {
             type = null;
             return false;
@@ -1328,9 +1328,9 @@ namespace System.Xml
         private class XmlWrappedReader : XmlDictionaryReader, IXmlLineInfo
         {
             private readonly XmlReader _reader;
-            private XmlNamespaceManager _nsMgr;
+            private XmlNamespaceManager? _nsMgr;
 
-            public XmlWrappedReader(XmlReader reader, XmlNamespaceManager nsMgr)
+            public XmlWrappedReader(XmlReader reader, XmlNamespaceManager? nsMgr)
             {
                 _reader = reader;
                 _nsMgr = nsMgr;
@@ -1344,7 +1344,7 @@ namespace System.Xml
                 }
             }
 
-            public override string BaseURI
+            public override string? BaseURI
             {
                 get
                 {
@@ -1389,12 +1389,12 @@ namespace System.Xml
                 return _reader.GetAttribute(index);
             }
 
-            public override string GetAttribute(string name)
+            public override string? GetAttribute(string name)
             {
                 return _reader.GetAttribute(name);
             }
 
-            public override string GetAttribute(string name, string namespaceUri)
+            public override string? GetAttribute(string name, string? namespaceUri)
             {
                 return _reader.GetAttribute(name, namespaceUri);
             }
@@ -1441,7 +1441,7 @@ namespace System.Xml
                 }
             }
 
-            public override string LookupNamespace(string namespaceUri)
+            public override string? LookupNamespace(string namespaceUri)
             {
                 return _reader.LookupNamespace(namespaceUri);
             }
@@ -1456,7 +1456,7 @@ namespace System.Xml
                 return _reader.MoveToAttribute(name);
             }
 
-            public override bool MoveToAttribute(string name, string namespaceUri)
+            public override bool MoveToAttribute(string name, string? namespaceUri)
             {
                 return _reader.MoveToAttribute(name, namespaceUri);
             }
@@ -1574,7 +1574,7 @@ namespace System.Xml
                 }
             }
 
-            public override string this[string name]
+            public override string? this[string name]
             {
                 get
                 {
@@ -1582,11 +1582,12 @@ namespace System.Xml
                 }
             }
 
-            public override string this[string name, string namespaceUri]
+            public override string? this[string name, string? namespaceUri]
             {
                 get
                 {
-                    return _reader[name, namespaceUri];
+                    // TODO-NULLABLE - unnecessary namespaceUri! - https://github.com/dotnet/roslyn/issues/47221
+                    return _reader[name, namespaceUri!];
                 }
             }
 
@@ -1784,14 +1785,14 @@ namespace System.Xml
                 }
             }
 
-            public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver)
+            public override object ReadContentAs(Type type, IXmlNamespaceResolver? namespaceResolver)
             {
                 return _reader.ReadContentAs(type, namespaceResolver);
             }
 
             public bool HasLineInfo()
             {
-                IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
+                IXmlLineInfo? lineInfo = _reader as IXmlLineInfo;
 
                 if (lineInfo == null)
                     return false;
@@ -1803,7 +1804,7 @@ namespace System.Xml
             {
                 get
                 {
-                    IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
+                    IXmlLineInfo? lineInfo = _reader as IXmlLineInfo;
 
                     if (lineInfo == null)
                         return 1;
@@ -1816,7 +1817,7 @@ namespace System.Xml
             {
                 get
                 {
-                    IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
+                    IXmlLineInfo? lineInfo = _reader as IXmlLineInfo;
 
                     if (lineInfo == null)
                         return 1;
index b1f58f5..9adecff 100644 (file)
@@ -6,7 +6,7 @@ using System.Xml;
 using System.Text;
 using System.Diagnostics;
 using System.Runtime.Serialization;
-
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
@@ -18,7 +18,7 @@ namespace System.Xml
         private readonly IXmlDictionary _dictionary;
         private readonly string _value;
         private readonly int _key;
-        private byte[] _buffer;
+        private byte[]? _buffer;
         private static readonly EmptyStringDictionary s_emptyStringDictionary = new EmptyStringDictionary();
 
         public XmlDictionaryString(IXmlDictionary dictionary, string value, int key)
@@ -34,7 +34,8 @@ namespace System.Xml
             _key = key;
         }
 
-        internal static string GetString(XmlDictionaryString s)
+        [return: NotNullIfNotNull("s")]
+        internal static string? GetString(XmlDictionaryString? s)
         {
             if (s == null)
                 return null;
@@ -102,7 +103,7 @@ namespace System.Xml
                 }
             }
 
-            public bool TryLookup(string value, out XmlDictionaryString result)
+            public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result)
             {
                 if (value == null)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value));
@@ -115,7 +116,7 @@ namespace System.Xml
                 return false;
             }
 
-            public bool TryLookup(int key, out XmlDictionaryString result)
+            public bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? result)
             {
                 if (key == 0)
                 {
@@ -126,7 +127,7 @@ namespace System.Xml
                 return false;
             }
 
-            public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result)
+            public bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result)
             {
                 if (value == null)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value)));
index 2f9e81b..6d2fb2d 100644 (file)
@@ -22,17 +22,17 @@ namespace System.Xml
             return CreateBinaryWriter(stream, null);
         }
 
-        public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary)
+        public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary? dictionary)
         {
             return CreateBinaryWriter(stream, dictionary, null);
         }
 
-        public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session)
+        public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session)
         {
             return CreateBinaryWriter(stream, dictionary, session, true);
         }
 
-        public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream)
+        public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream)
         {
             XmlBinaryWriter writer = new XmlBinaryWriter();
             writer.SetOutput(stream, dictionary, session, ownsStream);
@@ -63,7 +63,7 @@ namespace System.Xml
             return CreateMtomWriter(stream, encoding, maxSizeInBytes, startInfo, null, null, true, true);
         }
 
-        public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream)
+        public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string? boundary, string? startUri, bool writeMessageHeaders, bool ownsStream)
         {
             throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding);
         }
@@ -73,7 +73,7 @@ namespace System.Xml
             if (writer == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(writer));
 
-            XmlDictionaryWriter dictionaryWriter = writer as XmlDictionaryWriter;
+            XmlDictionaryWriter? dictionaryWriter = writer as XmlDictionaryWriter;
 
             if (dictionaryWriter == null)
             {
@@ -89,32 +89,32 @@ namespace System.Xml
             return Task.CompletedTask;
         }
 
-        public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
-            WriteStartElement((string)null, localName, namespaceUri);
+            WriteStartElement((string?)null, localName, namespaceUri);
         }
 
-        public virtual void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public virtual void WriteStartElement(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
             WriteStartElement(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
         }
 
-        public void WriteStartAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public void WriteStartAttribute(XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
-            WriteStartAttribute((string)null, localName, namespaceUri);
+            WriteStartAttribute((string?)null, localName, namespaceUri);
         }
 
-        public virtual void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public virtual void WriteStartAttribute(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
             WriteStartAttribute(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
         }
 
-        public void WriteAttributeString(XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
+        public void WriteAttributeString(XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value)
         {
-            WriteAttributeString((string)null, localName, namespaceUri, value);
+            WriteAttributeString((string?)null, localName, namespaceUri, value);
         }
 
-        public virtual void WriteXmlnsAttribute(string prefix, string namespaceUri)
+        public virtual void WriteXmlnsAttribute(string? prefix, string namespaceUri)
         {
             if (namespaceUri == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
@@ -128,46 +128,46 @@ namespace System.Xml
             WriteAttributeString("xmlns", prefix, null, namespaceUri);
         }
 
-        public virtual void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri)
+        public virtual void WriteXmlnsAttribute(string? prefix, XmlDictionaryString namespaceUri)
         {
             WriteXmlnsAttribute(prefix, XmlDictionaryString.GetString(namespaceUri));
         }
 
-        public virtual void WriteXmlAttribute(string localName, string value)
+        public virtual void WriteXmlAttribute(string localName, string? value)
         {
             WriteAttributeString("xml", localName, null, value);
         }
 
-        public virtual void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value)
+        public virtual void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString? value)
         {
             WriteXmlAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(value));
         }
 
-        public void WriteAttributeString(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
+        public void WriteAttributeString(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value)
         {
             WriteStartAttribute(prefix, localName, namespaceUri);
             WriteString(value);
             WriteEndAttribute();
         }
 
-        public void WriteElementString(XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
+        public void WriteElementString(XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value)
         {
-            WriteElementString((string)null, localName, namespaceUri, value);
+            WriteElementString((string?)null, localName, namespaceUri, value);
         }
 
-        public void WriteElementString(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
+        public void WriteElementString(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value)
         {
             WriteStartElement(prefix, localName, namespaceUri);
             WriteString(value);
             WriteEndElement();
         }
 
-        public virtual void WriteString(XmlDictionaryString value)
+        public virtual void WriteString(XmlDictionaryString? value)
         {
             WriteString(XmlDictionaryString.GetString(value));
         }
 
-        public virtual void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
+        public virtual void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
         {
             if (localName == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName)));
@@ -177,7 +177,7 @@ namespace System.Xml
             WriteQualifiedName(localName.Value, namespaceUri.Value);
         }
 
-        public virtual void WriteValue(XmlDictionaryString value)
+        public virtual void WriteValue(XmlDictionaryString? value)
         {
             WriteValue(XmlDictionaryString.GetString(value));
         }
@@ -242,7 +242,7 @@ namespace System.Xml
             }
         }
 
-        public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
+        public virtual void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
         }
@@ -254,8 +254,8 @@ namespace System.Xml
 
         private void WriteElementNode(XmlDictionaryReader reader, bool defattr)
         {
-            XmlDictionaryString localName;
-            XmlDictionaryString namespaceUri;
+            XmlDictionaryString? localName;
+            XmlDictionaryString? namespaceUri;
             if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri))
             {
                 WriteStartElement(reader.Prefix, localName, namespaceUri);
@@ -361,8 +361,8 @@ namespace System.Xml
 
         private void WriteArrayNode(XmlDictionaryReader reader, Type type)
         {
-            XmlDictionaryString localName;
-            XmlDictionaryString namespaceUri;
+            XmlDictionaryString? localName;
+            XmlDictionaryString? namespaceUri;
             if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri))
                 WriteArrayNode(reader, reader.Prefix, localName, namespaceUri, type);
             else
@@ -371,7 +371,7 @@ namespace System.Xml
 
         protected virtual void WriteTextNode(XmlDictionaryReader reader, bool isAttribute)
         {
-            XmlDictionaryString value;
+            XmlDictionaryString? value;
             if (reader.TryGetValueAsDictionaryString(out value))
             {
                 WriteString(value);
@@ -388,7 +388,7 @@ namespace System.Xml
 
         public override void WriteNode(XmlReader reader, bool defattr)
         {
-            XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader;
+            XmlDictionaryReader? dictionaryReader = reader as XmlDictionaryReader;
             if (dictionaryReader != null)
                 WriteNode(dictionaryReader, defattr);
             else
@@ -403,7 +403,7 @@ namespace System.Xml
             do
             {
                 XmlNodeType nodeType = reader.NodeType;
-                Type type;
+                Type? type;
                 if (nodeType == XmlNodeType.Text || nodeType == XmlNodeType.Whitespace || nodeType == XmlNodeType.SignificantWhitespace)
                 {
                     // This will advance if necessary, so we don't need to call Read() explicitly
@@ -463,7 +463,7 @@ namespace System.Xml
         }
 
         // bool
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, bool[] array, int offset, int count)
         {
             CheckArray(array, offset, count);
             for (int i = 0; i < count; i++)
@@ -474,13 +474,13 @@ namespace System.Xml
             }
         }
 
-        public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, bool[] array, int offset, int count)
         {
             WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
         }
 
         // Int16
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, short[] array, int offset, int count)
         {
             CheckArray(array, offset, count);
             for (int i = 0; i < count; i++)
@@ -491,13 +491,13 @@ namespace System.Xml
             }
         }
 
-        public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, short[] array, int offset, int count)
         {
             WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
         }
 
         // Int32
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, int[] array, int offset, int count)
         {
             CheckArray(array, offset, count);
             for (int i = 0; i < count; i++)
@@ -508,13 +508,13 @@ namespace System.Xml
             }
         }
 
-        public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, int[] array, int offset, int count)
         {
             WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
         }
 
         // Int64
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, long[] array, int offset, int count)
         {
             CheckArray(array, offset, count);
             for (int i = 0; i < count; i++)
@@ -525,13 +525,13 @@ namespace System.Xml
             }
         }
 
-        public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, long[] array, int offset, int count)
         {
             WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
         }
 
         // float
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, float[] array, int offset, int count)
         {
             CheckArray(array, offset, count);
             for (int i = 0; i < count; i++)
@@ -542,13 +542,13 @@ namespace System.Xml
             }
         }
 
-        public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, float[] array, int offset, int count)
         {
             WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
         }
 
         // double
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, double[] array, int offset, int count)
         {
             CheckArray(array, offset, count);
             for (int i = 0; i < count; i++)
@@ -559,13 +559,13 @@ namespace System.Xml
             }
         }
 
-        public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, double[] array, int offset, int count)
         {
             WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
         }
 
         // decimal
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, decimal[] array, int offset, int count)
         {
             CheckArray(array, offset, count);
             for (int i = 0; i < count; i++)
@@ -576,13 +576,13 @@ namespace System.Xml
             }
         }
 
-        public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, decimal[] array, int offset, int count)
         {
             WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
         }
 
         // DateTime
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, DateTime[] array, int offset, int count)
         {
             CheckArray(array, offset, count);
             for (int i = 0; i < count; i++)
@@ -593,13 +593,13 @@ namespace System.Xml
             }
         }
 
-        public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, DateTime[] array, int offset, int count)
         {
             WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
         }
 
         // Guid
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, Guid[] array, int offset, int count)
         {
             CheckArray(array, offset, count);
             for (int i = 0; i < count; i++)
@@ -610,13 +610,13 @@ namespace System.Xml
             }
         }
 
-        public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, Guid[] array, int offset, int count)
         {
             WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
         }
 
         // TimeSpan
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, TimeSpan[] array, int offset, int count)
         {
             CheckArray(array, offset, count);
             for (int i = 0; i < count; i++)
@@ -627,7 +627,7 @@ namespace System.Xml
             }
         }
 
-        public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
+        public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, TimeSpan[] array, int offset, int count)
         {
             WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
         }
@@ -664,7 +664,7 @@ namespace System.Xml
                 _writer.Flush();
             }
 
-            public override string LookupPrefix(string namespaceUri)
+            public override string? LookupPrefix(string namespaceUri)
             {
                 return _writer.LookupPrefix(namespaceUri);
             }
@@ -684,7 +684,7 @@ namespace System.Xml
                 _writer.WriteBinHex(buffer, index, count);
             }
 
-            public override void WriteCData(string text)
+            public override void WriteCData(string? text)
             {
                 _writer.WriteCData(text);
             }
@@ -699,12 +699,12 @@ namespace System.Xml
                 _writer.WriteChars(buffer, index, count);
             }
 
-            public override void WriteComment(string text)
+            public override void WriteComment(string? text)
             {
                 _writer.WriteComment(text);
             }
 
-            public override void WriteDocType(string name, string pubid, string sysid, string subset)
+            public override void WriteDocType(string name, string? pubid, string? sysid, string? subset)
             {
                 _writer.WriteDocType(name, pubid, sysid, subset);
             }
@@ -750,12 +750,12 @@ namespace System.Xml
                 _writer.WriteNode(reader, defattr);
             }
 
-            public override void WriteProcessingInstruction(string name, string text)
+            public override void WriteProcessingInstruction(string name, string? text)
             {
                 _writer.WriteProcessingInstruction(name, text);
             }
 
-            public override void WriteQualifiedName(string localName, string namespaceUri)
+            public override void WriteQualifiedName(string localName, string? namespaceUri)
             {
                 _writer.WriteQualifiedName(localName, namespaceUri);
             }
@@ -770,7 +770,7 @@ namespace System.Xml
                 _writer.WriteRaw(data);
             }
 
-            public override void WriteStartAttribute(string prefix, string localName, string namespaceUri)
+            public override void WriteStartAttribute(string? prefix, string localName, string? namespaceUri)
             {
                 _writer.WriteStartAttribute(prefix, localName, namespaceUri);
                 _prefix++;
@@ -786,7 +786,7 @@ namespace System.Xml
                 _writer.WriteStartDocument(standalone);
             }
 
-            public override void WriteStartElement(string prefix, string localName, string namespaceUri)
+            public override void WriteStartElement(string? prefix, string localName, string? namespaceUri)
             {
                 _writer.WriteStartElement(prefix, localName, namespaceUri);
                 _depth++;
@@ -801,7 +801,7 @@ namespace System.Xml
                 }
             }
 
-            public override void WriteString(string text)
+            public override void WriteString(string? text)
             {
                 _writer.WriteString(text);
             }
@@ -811,7 +811,7 @@ namespace System.Xml
                 _writer.WriteSurrogateCharEntity(lowChar, highChar);
             }
 
-            public override void WriteWhitespace(string whitespace)
+            public override void WriteWhitespace(string? whitespace)
             {
                 _writer.WriteWhitespace(whitespace);
             }
@@ -821,7 +821,7 @@ namespace System.Xml
                 _writer.WriteValue(value);
             }
 
-            public override void WriteValue(string value)
+            public override void WriteValue(string? value)
             {
                 _writer.WriteValue(value);
             }
@@ -851,7 +851,7 @@ namespace System.Xml
                 _writer.WriteValue(value);
             }
 
-            public override void WriteXmlnsAttribute(string prefix, string namespaceUri)
+            public override void WriteXmlnsAttribute(string? prefix, string namespaceUri)
             {
                 if (namespaceUri == null)
                     throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
@@ -874,7 +874,7 @@ namespace System.Xml
                 WriteAttributeString("xmlns", prefix, null, namespaceUri);
             }
 
-            public override string XmlLang
+            public override string? XmlLang
             {
                 get
                 {
index b16dede..3d6cc5c 100644 (file)
@@ -3,30 +3,35 @@
 
 using System.Runtime.Serialization;
 using System.Globalization;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
     internal static class XmlExceptionHelper
     {
+        [DoesNotReturn]
         private static void ThrowXmlException(XmlDictionaryReader reader, string res)
         {
             ThrowXmlException(reader, res, null);
         }
 
-        public static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1)
+        [DoesNotReturn]
+        public static void ThrowXmlException(XmlDictionaryReader reader, string res, string? arg1)
         {
             ThrowXmlException(reader, res, arg1, null);
         }
 
-        private static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1, string arg2)
+        [DoesNotReturn]
+        private static void ThrowXmlException(XmlDictionaryReader reader, string res, string? arg1, string? arg2)
         {
             ThrowXmlException(reader, res, arg1, arg2, null);
         }
 
-        private static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1, string arg2, string arg3)
+        [DoesNotReturn]
+        private static void ThrowXmlException(XmlDictionaryReader reader, string res, string? arg1, string? arg2, string? arg3)
         {
             string s = SR.Format(res, arg1, arg2, arg3);
-            IXmlLineInfo lineInfo = reader as IXmlLineInfo;
+            IXmlLineInfo? lineInfo = reader as IXmlLineInfo;
             if (lineInfo != null && lineInfo.HasLineInfo())
             {
                 s += " " + SR.Format(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition);
@@ -35,10 +40,11 @@ namespace System.Xml
             throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(s));
         }
 
+        [DoesNotReturn]
         public static void ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
         {
             string s = exception.Message;
-            IXmlLineInfo lineInfo = reader as IXmlLineInfo;
+            IXmlLineInfo? lineInfo = reader as IXmlLineInfo;
             if (lineInfo != null && lineInfo.HasLineInfo())
             {
                 s += " " + SR.Format(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition);
@@ -76,121 +82,145 @@ namespace System.Xml
             return SR.Format(SR.XmlFoundNodeType, reader.NodeType);
         }
 
+        [DoesNotReturn]
         public static void ThrowStartElementExpected(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlStartElementExpected, GetWhatWasFound(reader));
         }
 
+        [DoesNotReturn]
         public static void ThrowStartElementExpected(XmlDictionaryReader reader, string name)
         {
             ThrowXmlException(reader, SR.XmlStartElementNameExpected, name, GetWhatWasFound(reader));
         }
 
+        [DoesNotReturn]
         public static void ThrowStartElementExpected(XmlDictionaryReader reader, string localName, string ns)
         {
             ThrowXmlException(reader, SR.XmlStartElementLocalNameNsExpected, localName, ns, GetWhatWasFound(reader));
         }
 
+        [DoesNotReturn]
         public static void ThrowStartElementExpected(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns)
         {
             ThrowStartElementExpected(reader, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(ns));
         }
 
+        [DoesNotReturn]
         public static void ThrowFullStartElementExpected(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlFullStartElementExpected, GetWhatWasFound(reader));
         }
 
+        [DoesNotReturn]
         public static void ThrowFullStartElementExpected(XmlDictionaryReader reader, string name)
         {
             ThrowXmlException(reader, SR.XmlFullStartElementNameExpected, name, GetWhatWasFound(reader));
         }
 
+        [DoesNotReturn]
         public static void ThrowFullStartElementExpected(XmlDictionaryReader reader, string localName, string ns)
         {
             ThrowXmlException(reader, SR.XmlFullStartElementLocalNameNsExpected, localName, ns, GetWhatWasFound(reader));
         }
 
+        [DoesNotReturn]
         public static void ThrowFullStartElementExpected(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns)
         {
             ThrowFullStartElementExpected(reader, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(ns));
         }
 
+        [DoesNotReturn]
         public static void ThrowEndElementExpected(XmlDictionaryReader reader, string localName, string ns)
         {
             ThrowXmlException(reader, SR.XmlEndElementExpected, localName, ns, GetWhatWasFound(reader));
         }
 
+        [DoesNotReturn]
         public static void ThrowMaxArrayLengthExceeded(XmlDictionaryReader reader, int maxArrayLength)
         {
             ThrowXmlException(reader, SR.XmlMaxArrayLengthExceeded, maxArrayLength.ToString(NumberFormatInfo.CurrentInfo));
         }
 
+        [DoesNotReturn]
         public static void ThrowMaxBytesPerReadExceeded(XmlDictionaryReader reader, int maxBytesPerRead)
         {
             ThrowXmlException(reader, SR.XmlMaxBytesPerReadExceeded, maxBytesPerRead.ToString(NumberFormatInfo.CurrentInfo));
         }
 
+        [DoesNotReturn]
         public static void ThrowMaxDepthExceeded(XmlDictionaryReader reader, int maxDepth)
         {
             ThrowXmlException(reader, SR.XmlMaxDepthExceeded, maxDepth.ToString());
         }
 
+        [DoesNotReturn]
         public static void ThrowMaxStringContentLengthExceeded(XmlDictionaryReader reader, int maxStringContentLength)
         {
             ThrowXmlException(reader, SR.XmlMaxStringContentLengthExceeded, maxStringContentLength.ToString(NumberFormatInfo.CurrentInfo));
         }
 
+        [DoesNotReturn]
         public static void ThrowBase64DataExpected(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlBase64DataExpected, GetWhatWasFound(reader));
         }
 
+        [DoesNotReturn]
         public static void ThrowUndefinedPrefix(XmlDictionaryReader reader, string prefix)
         {
             ThrowXmlException(reader, SR.XmlUndefinedPrefix, prefix);
         }
 
+        [DoesNotReturn]
         public static void ThrowProcessingInstructionNotSupported(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlProcessingInstructionNotSupported);
         }
 
+        [DoesNotReturn]
         public static void ThrowInvalidXml(XmlDictionaryReader reader, byte b)
         {
             ThrowXmlException(reader, SR.XmlInvalidXmlByte, b.ToString("X2", CultureInfo.InvariantCulture));
         }
 
+        [DoesNotReturn]
         public static void ThrowUnexpectedEndOfFile(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlUnexpectedEndOfFile, ((XmlBaseReader)reader).GetOpenElements());
         }
 
+        [DoesNotReturn]
         public static void ThrowUnexpectedEndElement(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlUnexpectedEndElement);
         }
 
+        [DoesNotReturn]
         public static void ThrowTokenExpected(XmlDictionaryReader reader, string expected, char found)
         {
             ThrowXmlException(reader, SR.XmlTokenExpected, expected, found.ToString());
         }
 
+        [DoesNotReturn]
         public static void ThrowTokenExpected(XmlDictionaryReader reader, string expected, string found)
         {
             ThrowXmlException(reader, SR.XmlTokenExpected, expected, found);
         }
 
+        [DoesNotReturn]
         public static void ThrowInvalidCharRef(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlInvalidCharRef);
         }
 
+        [DoesNotReturn]
         public static void ThrowTagMismatch(XmlDictionaryReader reader, string expectedPrefix, string expectedLocalName, string foundPrefix, string foundLocalName)
         {
             ThrowXmlException(reader, SR.XmlTagMismatch, GetName(expectedPrefix, expectedLocalName), GetName(foundPrefix, foundLocalName));
         }
 
+        [DoesNotReturn]
         public static void ThrowDuplicateXmlnsAttribute(XmlDictionaryReader reader, string localName, string ns)
         {
             string name;
@@ -201,51 +231,61 @@ namespace System.Xml
             ThrowXmlException(reader, SR.XmlDuplicateAttribute, name, name, ns);
         }
 
+        [DoesNotReturn]
         public static void ThrowDuplicateAttribute(XmlDictionaryReader reader, string prefix1, string prefix2, string localName, string ns)
         {
             ThrowXmlException(reader, SR.XmlDuplicateAttribute, GetName(prefix1, localName), GetName(prefix2, localName), ns);
         }
 
+        [DoesNotReturn]
         public static void ThrowInvalidBinaryFormat(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlInvalidFormat);
         }
 
+        [DoesNotReturn]
         public static void ThrowInvalidRootData(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlInvalidRootData);
         }
 
+        [DoesNotReturn]
         public static void ThrowMultipleRootElements(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlMultipleRootElements);
         }
 
+        [DoesNotReturn]
         public static void ThrowDeclarationNotFirst(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlDeclNotFirst);
         }
 
+        [DoesNotReturn]
         public static void ThrowConversionOverflow(XmlDictionaryReader reader, string value, string type)
         {
             ThrowXmlException(reader, SR.XmlConversionOverflow, value, type);
         }
 
+        [DoesNotReturn]
         public static void ThrowXmlDictionaryStringIDOutOfRange(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlDictionaryStringIDRange, XmlDictionaryString.MinKey.ToString(NumberFormatInfo.CurrentInfo), XmlDictionaryString.MaxKey.ToString(NumberFormatInfo.CurrentInfo));
         }
 
+        [DoesNotReturn]
         public static void ThrowXmlDictionaryStringIDUndefinedStatic(XmlDictionaryReader reader, int key)
         {
             ThrowXmlException(reader, SR.XmlDictionaryStringIDUndefinedStatic, key.ToString(NumberFormatInfo.CurrentInfo));
         }
 
+        [DoesNotReturn]
         public static void ThrowXmlDictionaryStringIDUndefinedSession(XmlDictionaryReader reader, int key)
         {
             ThrowXmlException(reader, SR.XmlDictionaryStringIDUndefinedSession, key.ToString(NumberFormatInfo.CurrentInfo));
         }
 
+        [DoesNotReturn]
         public static void ThrowEmptyNamespace(XmlDictionaryReader reader)
         {
             ThrowXmlException(reader, SR.XmlEmptyNamespaceRequiresNullPrefix);
index 0953ef1..8cdf045 100644 (file)
@@ -14,7 +14,7 @@ namespace System.Xml
 {
     internal abstract class XmlNodeWriter
     {
-        private static XmlNodeWriter s_nullNodeWriter;
+        private static XmlNodeWriter? s_nullNodeWriter;
 
         public static XmlNodeWriter Null
         {
@@ -35,8 +35,8 @@ namespace System.Xml
         public abstract void WriteDeclaration();
         public abstract void WriteComment(string text);
         public abstract void WriteCData(string text);
-        public abstract void WriteStartElement(string prefix, string localName);
-        public virtual Task WriteStartElementAsync(string prefix, string localName)
+        public abstract void WriteStartElement(string? prefix, string localName);
+        public virtual Task WriteStartElementAsync(string? prefix, string localName)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(NotImplemented.ByDesign);
         }
@@ -44,14 +44,14 @@ namespace System.Xml
         {
             WriteStartElement(Encoding.UTF8.GetString(prefixBuffer, prefixOffset, prefixLength), Encoding.UTF8.GetString(localNameBuffer, localNameOffset, localNameLength));
         }
-        public abstract void WriteStartElement(string prefix, XmlDictionaryString localName);
+        public abstract void WriteStartElement(string? prefix, XmlDictionaryString localName);
         public abstract void WriteEndStartElement(bool isEmpty);
         public virtual Task WriteEndStartElementAsync(bool isEmpty)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(NotImplemented.ByDesign);
         }
-        public abstract void WriteEndElement(string prefix, string localName);
-        public virtual Task WriteEndElementAsync(string prefix, string localName)
+        public abstract void WriteEndElement(string? prefix, string localName);
+        public virtual Task WriteEndElementAsync(string? prefix, string localName)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(NotImplemented.ByDesign);
         }
@@ -59,12 +59,12 @@ namespace System.Xml
         {
             WriteEndElement(Encoding.UTF8.GetString(prefixBuffer, prefixOffset, prefixLength), Encoding.UTF8.GetString(localNameBuffer, localNameOffset, localNameLength));
         }
-        public abstract void WriteXmlnsAttribute(string prefix, string ns);
+        public abstract void WriteXmlnsAttribute(string? prefix, string ns);
         public virtual void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength)
         {
             WriteXmlnsAttribute(Encoding.UTF8.GetString(prefixBuffer, prefixOffset, prefixLength), Encoding.UTF8.GetString(nsBuffer, nsOffset, nsLength));
         }
-        public abstract void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns);
+        public abstract void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns);
         public abstract void WriteStartAttribute(string prefix, string localName);
         public virtual void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength)
         {
@@ -113,15 +113,15 @@ namespace System.Xml
             public override void WriteDeclaration() { }
             public override void WriteComment(string text) { }
             public override void WriteCData(string text) { }
-            public override void WriteStartElement(string prefix, string localName) { }
+            public override void WriteStartElement(string? prefix, string localName) { }
             public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { }
-            public override void WriteStartElement(string prefix, XmlDictionaryString localName) { }
+            public override void WriteStartElement(string? prefix, XmlDictionaryString localName) { }
             public override void WriteEndStartElement(bool isEmpty) { }
-            public override void WriteEndElement(string prefix, string localName) { }
+            public override void WriteEndElement(string? prefix, string localName) { }
             public override void WriteEndElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { }
-            public override void WriteXmlnsAttribute(string prefix, string ns) { }
+            public override void WriteXmlnsAttribute(string? prefix, string ns) { }
             public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { }
-            public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { }
+            public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns) { }
             public override void WriteStartAttribute(string prefix, string localName) { }
             public override void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { }
             public override void WriteStartAttribute(string prefix, XmlDictionaryString localName) { }
index d6f05b6..fb539d2 100644 (file)
@@ -1,6 +1,7 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System.Diagnostics;
 using System.IO;
 using System.Text;
 
@@ -8,10 +9,10 @@ namespace System.Xml
 {
     internal class XmlSigningNodeWriter : XmlNodeWriter
     {
-        private XmlNodeWriter _writer;
-        private XmlCanonicalWriter _signingWriter;
-        private byte[] _chars;
-        private byte[] _base64Chars;
+        private XmlNodeWriter _writer = null!; // initialized by SetOutput
+        private XmlCanonicalWriter _signingWriter = null!; // initialized by SetOutput
+        private byte[] _chars = null!; // initialized by SetOutput
+        private byte[]? _base64Chars;
         private readonly bool _text;
 
         public XmlSigningNodeWriter(bool text)
@@ -19,7 +20,7 @@ namespace System.Xml
             _text = text;
         }
 
-        public void SetOutput(XmlNodeWriter writer, Stream stream, bool includeComments, string[] inclusivePrefixes)
+        public void SetOutput(XmlNodeWriter writer, Stream stream, bool includeComments, string[]? inclusivePrefixes)
         {
             _writer = writer;
             if (_signingWriter == null)
@@ -79,8 +80,9 @@ namespace System.Xml
             _signingWriter.WriteEscapedText(text);
         }
 
-        public override void WriteStartElement(string prefix, string localName)
+        public override void WriteStartElement(string? prefix, string localName)
         {
+            Debug.Assert(prefix != null);
             _writer.WriteStartElement(prefix, localName);
             _signingWriter.WriteStartElement(prefix, localName);
         }
@@ -92,8 +94,9 @@ namespace System.Xml
             _signingWriter.WriteStartElement(prefixBuffer, prefixOffset, prefixLength, localNameBuffer, localNameOffset, localNameLength);
         }
 
-        public override void WriteStartElement(string prefix, XmlDictionaryString localName)
+        public override void WriteStartElement(string? prefix, XmlDictionaryString localName)
         {
+            Debug.Assert(prefix != null);
             _writer.WriteStartElement(prefix, localName);
             _signingWriter.WriteStartElement(prefix, localName.Value);
         }
@@ -104,14 +107,16 @@ namespace System.Xml
             _signingWriter.WriteEndStartElement(isEmpty);
         }
 
-        public override void WriteEndElement(string prefix, string localName)
+        public override void WriteEndElement(string? prefix, string localName)
         {
+            Debug.Assert(prefix != null);
             _writer.WriteEndElement(prefix, localName);
             _signingWriter.WriteEndElement(prefix, localName);
         }
 
-        public override void WriteXmlnsAttribute(string prefix, string ns)
+        public override void WriteXmlnsAttribute(string? prefix, string ns)
         {
+            Debug.Assert(prefix != null);
             _writer.WriteXmlnsAttribute(prefix, ns);
             _signingWriter.WriteXmlnsAttribute(prefix, ns);
         }
@@ -123,8 +128,9 @@ namespace System.Xml
             _signingWriter.WriteXmlnsAttribute(prefixBuffer, prefixOffset, prefixLength, nsBuffer, nsOffset, nsLength);
         }
 
-        public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
+        public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns)
         {
+            Debug.Assert(prefix != null);
             _writer.WriteXmlnsAttribute(prefix, ns);
             _signingWriter.WriteXmlnsAttribute(prefix, ns.Value);
         }
index 39f47f5..6075d0a 100644 (file)
@@ -10,13 +10,13 @@ namespace System.Xml
 {
     internal abstract class XmlStreamNodeWriter : XmlNodeWriter
     {
-        private Stream _stream;
+        private Stream _stream = null!; // initialized by SetOutput
         private readonly byte[] _buffer;
         private int _offset;
         private bool _ownsStream;
         private const int bufferLength = 512;
         private const int maxBytesPerChar = 3;
-        private Encoding _encoding;
+        private Encoding? _encoding;
         private static readonly UTF8Encoding s_UTF8Encoding = new UTF8Encoding(false, true);
 
         protected XmlStreamNodeWriter()
@@ -24,7 +24,7 @@ namespace System.Xml
             _buffer = new byte[bufferLength];
         }
 
-        protected void SetOutput(Stream stream, bool ownsStream, Encoding encoding)
+        protected void SetOutput(Stream stream, bool ownsStream, Encoding? encoding)
         {
             _stream = stream;
             _ownsStream = ownsStream;
@@ -462,7 +462,7 @@ namespace System.Xml
                 {
                     _stream.Dispose();
                 }
-                _stream = null;
+                _stream = null!;
             }
         }
     }
index b851af7..7d300f1 100644 (file)
@@ -17,8 +17,8 @@ namespace System.Xml
 {
     public interface IXmlTextReaderInitializer
     {
-        void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose);
-        void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose);
+        void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose);
+        void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose);
     }
 
     internal class XmlUTF8TextReader : XmlBaseReader, IXmlLineInfo, IXmlTextReaderInitializer
@@ -27,8 +27,8 @@ namespace System.Xml
 
         private readonly PrefixHandle _prefix;
         private readonly StringHandle _localName;
-        private int[] _rowOffsets;
-        private OnXmlDictionaryReaderClose _onClose;
+        private int[]? _rowOffsets;
+        private OnXmlDictionaryReaderClose? _onClose;
         private bool _buffered;
         private int _maxBytesPerRead;
         private static readonly byte[] s_charType = new byte[256]
@@ -553,7 +553,7 @@ namespace System.Xml
             _localName = new StringHandle(BufferReader);
         }
 
-        public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
+        public void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose)
         {
             if (buffer == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer)));
@@ -567,11 +567,11 @@ namespace System.Xml
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
             MoveToInitial(quotas, onClose);
             ArraySegment<byte> seg = EncodingStreamWrapper.ProcessBuffer(buffer, offset, count, encoding);
-            BufferReader.SetBuffer(seg.Array, seg.Offset, seg.Count, null, null);
+            BufferReader.SetBuffer(seg.Array!, seg.Offset, seg.Count, null, null);
             _buffered = true;
         }
 
-        public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
+        public void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose)
         {
             if (stream == null)
                 throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream));
@@ -581,7 +581,7 @@ namespace System.Xml
             _buffered = false;
         }
 
-        private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
+        private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose)
         {
             MoveToInitial(quotas);
             _maxBytesPerRead = quotas.MaxBytesPerRead;
@@ -592,7 +592,7 @@ namespace System.Xml
         {
             _rowOffsets = null;
             base.Close();
-            OnXmlDictionaryReaderClose onClose = _onClose;
+            OnXmlDictionaryReaderClose? onClose = _onClose;
             _onClose = null;
             if (onClose != null)
             {
index 5597757..22e4d66 100644 (file)
@@ -14,7 +14,7 @@ namespace System.Xml
 
     internal class XmlUTF8TextWriter : XmlBaseWriter, IXmlTextWriterInitializer
     {
-        private XmlUTF8NodeWriter _writer;
+        private XmlUTF8NodeWriter? _writer;
 
         public void SetOutput(Stream stream, Encoding encoding, bool ownsStream)
         {
@@ -43,14 +43,14 @@ namespace System.Xml
 
     internal class XmlUTF8NodeWriter : XmlStreamNodeWriter
     {
-        private byte[] _entityChars;
+        private byte[]? _entityChars;
         private readonly bool[] _isEscapedAttributeChar;
         private readonly bool[] _isEscapedElementChar;
         private bool _inAttribute;
         private const int bufferLength = 512;
         private const int maxEntityLength = 32;
-        private Encoding _encoding;
-        private char[] _chars;
+        private Encoding? _encoding;
+        private char[]? _chars;
 
         private static readonly byte[] s_startDecl =
         {
@@ -101,9 +101,9 @@ namespace System.Xml
             _inAttribute = false;
         }
 
-        public new void SetOutput(Stream stream, bool ownsStream, Encoding encoding)
+        public new void SetOutput(Stream stream, bool ownsStream, Encoding? encoding)
         {
-            Encoding utf8Encoding = null;
+            Encoding? utf8Encoding = null;
             if (encoding != null && encoding.CodePage == Encoding.UTF8.CodePage)
             {
                 utf8Encoding = encoding;
@@ -203,10 +203,10 @@ namespace System.Xml
             WriteEndComment();
         }
 
-        public override void WriteStartElement(string prefix, string localName)
+        public override void WriteStartElement(string? prefix, string localName)
         {
             WriteByte('<');
-            if (prefix.Length != 0)
+            if (!string.IsNullOrEmpty(prefix))
             {
                 WritePrefix(prefix);
                 WriteByte(':');
@@ -214,10 +214,10 @@ namespace System.Xml
             WriteLocalName(localName);
         }
 
-        public override async Task WriteStartElementAsync(string prefix, string localName)
+        public override async Task WriteStartElementAsync(string? prefix, string localName)
         {
             await WriteByteAsync('<').ConfigureAwait(false);
-            if (prefix.Length != 0)
+            if (!string.IsNullOrEmpty(prefix))
             {
                 // This method calls into unsafe method which cannot run asyncly.
                 WritePrefix(prefix);
@@ -228,7 +228,7 @@ namespace System.Xml
             WriteLocalName(localName);
         }
 
-        public override void WriteStartElement(string prefix, XmlDictionaryString localName)
+        public override void WriteStartElement(string? prefix, XmlDictionaryString localName)
         {
             WriteStartElement(prefix, localName.Value);
         }
@@ -268,10 +268,10 @@ namespace System.Xml
             }
         }
 
-        public override void WriteEndElement(string prefix, string localName)
+        public override void WriteEndElement(string? prefix, string localName)
         {
             WriteBytes('<', '/');
-            if (prefix.Length != 0)
+            if (!string.IsNullOrEmpty(prefix))
             {
                 WritePrefix(prefix);
                 WriteByte(':');
@@ -280,10 +280,10 @@ namespace System.Xml
             WriteByte('>');
         }
 
-        public override async Task WriteEndElementAsync(string prefix, string localName)
+        public override async Task WriteEndElementAsync(string? prefix, string localName)
         {
             await WriteBytesAsync('<', '/').ConfigureAwait(false);
-            if (prefix.Length != 0)
+            if (!string.IsNullOrEmpty(prefix))
             {
                 WritePrefix(prefix);
                 await WriteByteAsync(':').ConfigureAwait(false);
@@ -318,10 +318,10 @@ namespace System.Xml
             _inAttribute = true;
         }
 
-        public override void WriteXmlnsAttribute(string prefix, string ns)
+        public override void WriteXmlnsAttribute(string? prefix, string ns)
         {
             WriteStartXmlnsAttribute();
-            if (prefix.Length != 0)
+            if (!string.IsNullOrEmpty(prefix))
             {
                 WriteByte(':');
                 WritePrefix(prefix);
@@ -331,7 +331,7 @@ namespace System.Xml
             WriteEndAttribute();
         }
 
-        public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
+        public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns)
         {
             WriteXmlnsAttribute(prefix, ns.Value);
         }
index 0cd5533..e9dee40 100644 (file)
@@ -26,13 +26,13 @@ namespace System.Runtime.Serialization.Json
     public sealed partial class DataContractJsonSerializer : System.Runtime.Serialization.XmlObjectSerializer
     {
         public DataContractJsonSerializer(System.Type type) { }
-        public DataContractJsonSerializer(System.Type type, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
-        public DataContractJsonSerializer(System.Type type, System.Runtime.Serialization.Json.DataContractJsonSerializerSettings settings) { }
-        public DataContractJsonSerializer(System.Type type, string rootName) { }
-        public DataContractJsonSerializer(System.Type type, string rootName, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
-        public DataContractJsonSerializer(System.Type type, System.Xml.XmlDictionaryString rootName) { }
-        public DataContractJsonSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
-        public System.Runtime.Serialization.DateTimeFormat DateTimeFormat { get { throw null; } }
+        public DataContractJsonSerializer(System.Type type, System.Collections.Generic.IEnumerable<System.Type>? knownTypes) { }
+        public DataContractJsonSerializer(System.Type type, System.Runtime.Serialization.Json.DataContractJsonSerializerSettings? settings) { }
+        public DataContractJsonSerializer(System.Type type, string? rootName) { }
+        public DataContractJsonSerializer(System.Type type, string? rootName, System.Collections.Generic.IEnumerable<System.Type>? knownTypes) { }
+        public DataContractJsonSerializer(System.Type type, System.Xml.XmlDictionaryString? rootName) { }
+        public DataContractJsonSerializer(System.Type type, System.Xml.XmlDictionaryString? rootName, System.Collections.Generic.IEnumerable<System.Type>? knownTypes) { }
+        public System.Runtime.Serialization.DateTimeFormat? DateTimeFormat { get { throw null; } }
         public System.Runtime.Serialization.EmitTypeInformation EmitTypeInformation { get { throw null; } }
         public bool IgnoreExtensionDataObject { get { throw null; } }
         public System.Collections.ObjectModel.ReadOnlyCollection<System.Type> KnownTypes { get { throw null; } }
@@ -41,37 +41,37 @@ namespace System.Runtime.Serialization.Json
         public bool UseSimpleDictionaryFormat { get { throw null; } }
         public override bool IsStartObject(System.Xml.XmlDictionaryReader reader) { throw null; }
         public override bool IsStartObject(System.Xml.XmlReader reader) { throw null; }
-        public override object ReadObject(System.IO.Stream stream) { throw null; }
-        public override object ReadObject(System.Xml.XmlDictionaryReader reader) { throw null; }
-        public override object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName) { throw null; }
-        public override object ReadObject(System.Xml.XmlReader reader) { throw null; }
-        public override object ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; }
+        public override object? ReadObject(System.IO.Stream stream) { throw null; }
+        public override object? ReadObject(System.Xml.XmlDictionaryReader reader) { throw null; }
+        public override object? ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName) { throw null; }
+        public override object? ReadObject(System.Xml.XmlReader reader) { throw null; }
+        public override object? ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; }
         public override void WriteEndObject(System.Xml.XmlDictionaryWriter writer) { }
         public override void WriteEndObject(System.Xml.XmlWriter writer) { }
-        public override void WriteObject(System.IO.Stream stream, object graph) { }
-        public override void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph) { }
-        public override void WriteObject(System.Xml.XmlWriter writer, object graph) { }
-        public override void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph) { }
-        public override void WriteObjectContent(System.Xml.XmlWriter writer, object graph) { }
-        public override void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph) { }
-        public override void WriteStartObject(System.Xml.XmlWriter writer, object graph) { }
+        public override void WriteObject(System.IO.Stream stream, object? graph) { }
+        public override void WriteObject(System.Xml.XmlDictionaryWriter writer, object? graph) { }
+        public override void WriteObject(System.Xml.XmlWriter writer, object? graph) { }
+        public override void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object? graph) { }
+        public override void WriteObjectContent(System.Xml.XmlWriter writer, object? graph) { }
+        public override void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object? graph) { }
+        public override void WriteStartObject(System.Xml.XmlWriter writer, object? graph) { }
     }
     public partial class DataContractJsonSerializerSettings
     {
         public DataContractJsonSerializerSettings() { }
-        public System.Runtime.Serialization.DateTimeFormat DateTimeFormat { get { throw null; } set { } }
+        public System.Runtime.Serialization.DateTimeFormat? DateTimeFormat { get { throw null; } set { } }
         public System.Runtime.Serialization.EmitTypeInformation EmitTypeInformation { get { throw null; } set { } }
         public bool IgnoreExtensionDataObject { get { throw null; } set { } }
-        public System.Collections.Generic.IEnumerable<System.Type> KnownTypes { get { throw null; } set { } }
+        public System.Collections.Generic.IEnumerable<System.Type>? KnownTypes { get { throw null; } set { } }
         public int MaxItemsInObjectGraph { get { throw null; } set { } }
-        public string RootName { get { throw null; } set { } }
+        public string? RootName { get { throw null; } set { } }
         public bool SerializeReadOnlyTypes { get { throw null; } set { } }
         public bool UseSimpleDictionaryFormat { get { throw null; } set { } }
     }
     public partial interface IXmlJsonReaderInitializer
     {
-        void SetInput(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose);
-        void SetInput(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose);
+        void SetInput(byte[] buffer, int offset, int count, System.Text.Encoding? encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose? onClose);
+        void SetInput(System.IO.Stream stream, System.Text.Encoding? encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose? onClose);
     }
     public partial interface IXmlJsonWriterInitializer
     {
@@ -79,15 +79,15 @@ namespace System.Runtime.Serialization.Json
     }
     public static partial class JsonReaderWriterFactory
     {
-        public static System.Xml.XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, int count, System.Text.Encoding? encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose? onClose) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, int count, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateJsonReader(byte[] buffer, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateJsonReader(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateJsonReader(System.IO.Stream stream, System.Text.Encoding? encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose? onClose) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateJsonReader(System.IO.Stream stream, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
         public static System.Xml.XmlDictionaryWriter CreateJsonWriter(System.IO.Stream stream) { throw null; }
         public static System.Xml.XmlDictionaryWriter CreateJsonWriter(System.IO.Stream stream, System.Text.Encoding encoding) { throw null; }
         public static System.Xml.XmlDictionaryWriter CreateJsonWriter(System.IO.Stream stream, System.Text.Encoding encoding, bool ownsStream) { throw null; }
         public static System.Xml.XmlDictionaryWriter CreateJsonWriter(System.IO.Stream stream, System.Text.Encoding encoding, bool ownsStream, bool indent) { throw null; }
-        public static System.Xml.XmlDictionaryWriter CreateJsonWriter(System.IO.Stream stream, System.Text.Encoding encoding, bool ownsStream, bool indent, string indentChars) { throw null; }
+        public static System.Xml.XmlDictionaryWriter CreateJsonWriter(System.IO.Stream stream, System.Text.Encoding encoding, bool ownsStream, bool indent, string? indentChars) { throw null; }
     }
 }
index fd7caac..a25d7b6 100644 (file)
@@ -1,6 +1,7 @@
 <Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="System.Runtime.Serialization.Json.cs" />
index 59304bf..9cdaf74 100644 (file)
@@ -2,6 +2,7 @@
   <PropertyGroup>
     <IsPartialFacadeAssembly>true</IsPartialFacadeAssembly>
     <TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <ProjectReference Include="$(LibrariesProjectRoot)System.Private.DataContractSerialization\src\System.Private.DataContractSerialization.csproj" />
index 8748a6a..00c9821 100644 (file)
@@ -9,19 +9,19 @@ namespace System.Runtime.Serialization
     public abstract partial class DataContractResolver
     {
         protected DataContractResolver() { }
-        public abstract System.Type ResolveName(string typeName, string typeNamespace, System.Type declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver);
-        public abstract bool TryResolveType(System.Type type, System.Type declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver, out System.Xml.XmlDictionaryString typeName, out System.Xml.XmlDictionaryString typeNamespace);
+        public abstract System.Type? ResolveName(string typeName, string? typeNamespace, System.Type? declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver);
+        public abstract bool TryResolveType(System.Type type, System.Type? declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver, out System.Xml.XmlDictionaryString? typeName, out System.Xml.XmlDictionaryString? typeNamespace);
     }
     public sealed partial class DataContractSerializer : System.Runtime.Serialization.XmlObjectSerializer
     {
         public DataContractSerializer(System.Type type) { }
-        public DataContractSerializer(System.Type type, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
-        public DataContractSerializer(System.Type type, System.Runtime.Serialization.DataContractSerializerSettings settings) { }
+        public DataContractSerializer(System.Type type, System.Collections.Generic.IEnumerable<System.Type>? knownTypes) { }
+        public DataContractSerializer(System.Type type, System.Runtime.Serialization.DataContractSerializerSettings? settings) { }
         public DataContractSerializer(System.Type type, string rootName, string rootNamespace) { }
-        public DataContractSerializer(System.Type type, string rootName, string rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
+        public DataContractSerializer(System.Type type, string rootName, string rootNamespace, System.Collections.Generic.IEnumerable<System.Type>? knownTypes) { }
         public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace) { }
-        public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
-        public System.Runtime.Serialization.DataContractResolver DataContractResolver { get { throw null; } }
+        public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace, System.Collections.Generic.IEnumerable<System.Type>? knownTypes) { }
+        public System.Runtime.Serialization.DataContractResolver? DataContractResolver { get { throw null; } }
         public bool IgnoreExtensionDataObject { get { throw null; } }
         public System.Collections.ObjectModel.ReadOnlyCollection<System.Type> KnownTypes { get { throw null; } }
         public int MaxItemsInObjectGraph { get { throw null; } }
@@ -29,34 +29,34 @@ namespace System.Runtime.Serialization
         public bool SerializeReadOnlyTypes { get { throw null; } }
         public override bool IsStartObject(System.Xml.XmlDictionaryReader reader) { throw null; }
         public override bool IsStartObject(System.Xml.XmlReader reader) { throw null; }
-        public override object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName) { throw null; }
-        public object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName, System.Runtime.Serialization.DataContractResolver dataContractResolver) { throw null; }
-        public override object ReadObject(System.Xml.XmlReader reader) { throw null; }
-        public override object ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; }
+        public override object? ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName) { throw null; }
+        public object? ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName, System.Runtime.Serialization.DataContractResolver? dataContractResolver) { throw null; }
+        public override object? ReadObject(System.Xml.XmlReader reader) { throw null; }
+        public override object? ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; }
         public override void WriteEndObject(System.Xml.XmlDictionaryWriter writer) { }
         public override void WriteEndObject(System.Xml.XmlWriter writer) { }
-        public void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph, System.Runtime.Serialization.DataContractResolver dataContractResolver) { }
-        public override void WriteObject(System.Xml.XmlWriter writer, object graph) { }
-        public override void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph) { }
-        public override void WriteObjectContent(System.Xml.XmlWriter writer, object graph) { }
-        public override void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph) { }
-        public override void WriteStartObject(System.Xml.XmlWriter writer, object graph) { }
+        public void WriteObject(System.Xml.XmlDictionaryWriter writer, object? graph, System.Runtime.Serialization.DataContractResolver? dataContractResolver) { }
+        public override void WriteObject(System.Xml.XmlWriter writer, object? graph) { }
+        public override void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object? graph) { }
+        public override void WriteObjectContent(System.Xml.XmlWriter writer, object? graph) { }
+        public override void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object? graph) { }
+        public override void WriteStartObject(System.Xml.XmlWriter writer, object? graph) { }
     }
     public static partial class DataContractSerializerExtensions
     {
-        public static System.Runtime.Serialization.ISerializationSurrogateProvider GetSerializationSurrogateProvider(this System.Runtime.Serialization.DataContractSerializer serializer) { throw null; }
-        public static void SetSerializationSurrogateProvider(this System.Runtime.Serialization.DataContractSerializer serializer, System.Runtime.Serialization.ISerializationSurrogateProvider provider) { }
+        public static System.Runtime.Serialization.ISerializationSurrogateProvider? GetSerializationSurrogateProvider(this System.Runtime.Serialization.DataContractSerializer serializer) { throw null; }
+        public static void SetSerializationSurrogateProvider(this System.Runtime.Serialization.DataContractSerializer serializer, System.Runtime.Serialization.ISerializationSurrogateProvider? provider) { }
     }
     public partial class DataContractSerializerSettings
     {
         public DataContractSerializerSettings() { }
-        public System.Runtime.Serialization.DataContractResolver DataContractResolver { get { throw null; } set { } }
+        public System.Runtime.Serialization.DataContractResolver? DataContractResolver { get { throw null; } set { } }
         public bool IgnoreExtensionDataObject { get { throw null; } set { } }
-        public System.Collections.Generic.IEnumerable<System.Type> KnownTypes { get { throw null; } set { } }
+        public System.Collections.Generic.IEnumerable<System.Type>? KnownTypes { get { throw null; } set { } }
         public int MaxItemsInObjectGraph { get { throw null; } set { } }
         public bool PreserveObjectReferences { get { throw null; } set { } }
-        public System.Xml.XmlDictionaryString RootName { get { throw null; } set { } }
-        public System.Xml.XmlDictionaryString RootNamespace { get { throw null; } set { } }
+        public System.Xml.XmlDictionaryString? RootName { get { throw null; } set { } }
+        public System.Xml.XmlDictionaryString? RootNamespace { get { throw null; } set { } }
         public bool SerializeReadOnlyTypes { get { throw null; } set { } }
     }
     public partial class ExportOptions
@@ -70,44 +70,44 @@ namespace System.Runtime.Serialization
     }
     public partial interface IExtensibleDataObject
     {
-        System.Runtime.Serialization.ExtensionDataObject ExtensionData { get; set; }
+        System.Runtime.Serialization.ExtensionDataObject? ExtensionData { get; set; }
     }
     public abstract partial class XmlObjectSerializer
     {
         protected XmlObjectSerializer() { }
         public abstract bool IsStartObject(System.Xml.XmlDictionaryReader reader);
         public virtual bool IsStartObject(System.Xml.XmlReader reader) { throw null; }
-        public virtual object ReadObject(System.IO.Stream stream) { throw null; }
-        public virtual object ReadObject(System.Xml.XmlDictionaryReader reader) { throw null; }
-        public abstract object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName);
-        public virtual object ReadObject(System.Xml.XmlReader reader) { throw null; }
-        public virtual object ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; }
+        public virtual object? ReadObject(System.IO.Stream stream) { throw null; }
+        public virtual object? ReadObject(System.Xml.XmlDictionaryReader reader) { throw null; }
+        public abstract object? ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName);
+        public virtual object? ReadObject(System.Xml.XmlReader reader) { throw null; }
+        public virtual object? ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; }
         public abstract void WriteEndObject(System.Xml.XmlDictionaryWriter writer);
         public virtual void WriteEndObject(System.Xml.XmlWriter writer) { }
-        public virtual void WriteObject(System.IO.Stream stream, object graph) { }
-        public virtual void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph) { }
-        public virtual void WriteObject(System.Xml.XmlWriter writer, object graph) { }
-        public abstract void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph);
-        public virtual void WriteObjectContent(System.Xml.XmlWriter writer, object graph) { }
-        public abstract void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph);
-        public virtual void WriteStartObject(System.Xml.XmlWriter writer, object graph) { }
+        public virtual void WriteObject(System.IO.Stream stream, object? graph) { }
+        public virtual void WriteObject(System.Xml.XmlDictionaryWriter writer, object? graph) { }
+        public virtual void WriteObject(System.Xml.XmlWriter writer, object? graph) { }
+        public abstract void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object? graph);
+        public virtual void WriteObjectContent(System.Xml.XmlWriter writer, object? graph) { }
+        public abstract void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object? graph);
+        public virtual void WriteStartObject(System.Xml.XmlWriter writer, object? graph) { }
     }
     public static partial class XmlSerializableServices
     {
         public static void AddDefaultSchema(System.Xml.Schema.XmlSchemaSet schemas, System.Xml.XmlQualifiedName typeQName) { }
         public static System.Xml.XmlNode[] ReadNodes(System.Xml.XmlReader xmlReader) { throw null; }
-        public static void WriteNodes(System.Xml.XmlWriter xmlWriter, System.Xml.XmlNode[] nodes) { }
+        public static void WriteNodes(System.Xml.XmlWriter xmlWriter, System.Xml.XmlNode?[]? nodes) { }
     }
     public static partial class XPathQueryGenerator
     {
-        public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, System.Text.StringBuilder rootElementXpath, out System.Xml.XmlNamespaceManager namespaces) { throw null; }
+        public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, System.Text.StringBuilder? rootElementXpath, out System.Xml.XmlNamespaceManager namespaces) { throw null; }
         public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, out System.Xml.XmlNamespaceManager namespaces) { throw null; }
     }
     public partial class XsdDataContractExporter
     {
         public XsdDataContractExporter() { }
-        public XsdDataContractExporter(System.Xml.Schema.XmlSchemaSet schemas) { }
-        public System.Runtime.Serialization.ExportOptions Options { get { throw null; } set { } }
+        public XsdDataContractExporter(System.Xml.Schema.XmlSchemaSet? schemas) { }
+        public System.Runtime.Serialization.ExportOptions? Options { get { throw null; } set { } }
         public System.Xml.Schema.XmlSchemaSet Schemas { get { throw null; } }
         public bool CanExport(System.Collections.Generic.ICollection<System.Reflection.Assembly> assemblies) { throw null; }
         public bool CanExport(System.Collections.Generic.ICollection<System.Type> types) { throw null; }
@@ -115,8 +115,8 @@ namespace System.Runtime.Serialization
         public void Export(System.Collections.Generic.ICollection<System.Reflection.Assembly> assemblies) { }
         public void Export(System.Collections.Generic.ICollection<System.Type> types) { }
         public void Export(System.Type type) { }
-        public System.Xml.XmlQualifiedName GetRootElementName(System.Type type) { throw null; }
-        public System.Xml.Schema.XmlSchemaType GetSchemaType(System.Type type) { throw null; }
+        public System.Xml.XmlQualifiedName? GetRootElementName(System.Type type) { throw null; }
+        public System.Xml.Schema.XmlSchemaType? GetSchemaType(System.Type type) { throw null; }
         public System.Xml.XmlQualifiedName GetSchemaTypeName(System.Type type) { throw null; }
     }
 }
@@ -136,23 +136,23 @@ namespace System.Xml
     }
     public partial interface IXmlBinaryReaderInitializer
     {
-        void SetInput(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose);
-        void SetInput(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose);
+        void SetInput(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary? dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession? session, System.Xml.OnXmlDictionaryReaderClose? onClose);
+        void SetInput(System.IO.Stream stream, System.Xml.IXmlDictionary? dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession? session, System.Xml.OnXmlDictionaryReaderClose? onClose);
     }
     public partial interface IXmlBinaryWriterInitializer
     {
-        void SetOutput(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session, bool ownsStream);
+        void SetOutput(System.IO.Stream stream, System.Xml.IXmlDictionary? dictionary, System.Xml.XmlBinaryWriterSession? session, bool ownsStream);
     }
     public partial interface IXmlDictionary
     {
-        bool TryLookup(int key, out System.Xml.XmlDictionaryString result);
-        bool TryLookup(string value, out System.Xml.XmlDictionaryString result);
-        bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result);
+        bool TryLookup(int key, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? result);
+        bool TryLookup(string value, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? result);
+        bool TryLookup(System.Xml.XmlDictionaryString value, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? result);
     }
     public partial interface IXmlTextReaderInitializer
     {
-        void SetInput(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose);
-        void SetInput(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose);
+        void SetInput(byte[] buffer, int offset, int count, System.Text.Encoding? encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose? onClose);
+        void SetInput(System.IO.Stream stream, System.Text.Encoding? encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose? onClose);
     }
     public partial interface IXmlTextWriterInitializer
     {
@@ -169,10 +169,10 @@ namespace System.Xml
         public UniqueId(string value) { }
         public int CharArrayLength { get { throw null; } }
         public bool IsGuid { get { throw null; } }
-        public override bool Equals(object obj) { throw null; }
+        public override bool Equals(object? obj) { throw null; }
         public override int GetHashCode() { throw null; }
-        public static bool operator ==(System.Xml.UniqueId id1, System.Xml.UniqueId id2) { throw null; }
-        public static bool operator !=(System.Xml.UniqueId id1, System.Xml.UniqueId id2) { throw null; }
+        public static bool operator ==(System.Xml.UniqueId? id1, System.Xml.UniqueId? id2) { throw null; }
+        public static bool operator !=(System.Xml.UniqueId? id1, System.Xml.UniqueId? id2) { throw null; }
         public int ToCharArray(char[] chars, int offset) { throw null; }
         public override string ToString() { throw null; }
         public bool TryGetGuid(byte[] buffer, int offset) { throw null; }
@@ -183,9 +183,9 @@ namespace System.Xml
         public XmlBinaryReaderSession() { }
         public System.Xml.XmlDictionaryString Add(int id, string value) { throw null; }
         public void Clear() { }
-        public bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { throw null; }
-        public bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { throw null; }
-        public bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { throw null; }
+        public bool TryLookup(int key, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? result) { throw null; }
+        public bool TryLookup(string value, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? result) { throw null; }
+        public bool TryLookup(System.Xml.XmlDictionaryString value, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? result) { throw null; }
     }
     public partial class XmlBinaryWriterSession
     {
@@ -199,40 +199,40 @@ namespace System.Xml
         public XmlDictionary(int capacity) { }
         public static System.Xml.IXmlDictionary Empty { get { throw null; } }
         public virtual System.Xml.XmlDictionaryString Add(string value) { throw null; }
-        public virtual bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { throw null; }
-        public virtual bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { throw null; }
-        public virtual bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { throw null; }
+        public virtual bool TryLookup(int key, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? result) { throw null; }
+        public virtual bool TryLookup(string value, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? result) { throw null; }
+        public virtual bool TryLookup(System.Xml.XmlDictionaryString value, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? result) { throw null; }
     }
     public abstract partial class XmlDictionaryReader : System.Xml.XmlReader
     {
         protected XmlDictionaryReader() { }
         public virtual bool CanCanonicalize { get { throw null; } }
         public virtual System.Xml.XmlDictionaryReaderQuotas Quotas { get { throw null; } }
-        public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary? dictionary, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary? dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession? session) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary? dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession? session, System.Xml.OnXmlDictionaryReaderClose? onClose) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary? dictionary, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary? dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession? session) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary? dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession? session, System.Xml.OnXmlDictionaryReaderClose? onClose) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateDictionaryReader(System.Xml.XmlReader reader) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas, int maxBufferSize, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, string? contentType, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, string? contentType, System.Xml.XmlDictionaryReaderQuotas quotas, int maxBufferSize, System.Xml.OnXmlDictionaryReaderClose? onClose) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas, int maxBufferSize, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, string? contentType, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, string? contentType, System.Xml.XmlDictionaryReaderQuotas quotas, int maxBufferSize, System.Xml.OnXmlDictionaryReaderClose? onClose) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, System.Text.Encoding? encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose? onClose) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
-        public static System.Xml.XmlDictionaryReader CreateTextReader(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
+        public static System.Xml.XmlDictionaryReader CreateTextReader(System.IO.Stream stream, System.Text.Encoding? encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose? onClose) { throw null; }
         public static System.Xml.XmlDictionaryReader CreateTextReader(System.IO.Stream stream, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
         public virtual void EndCanonicalization() { }
-        public virtual string GetAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
+        public virtual string? GetAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
         public virtual void GetNonAtomizedNames(out string localName, out string namespaceUri) { throw null; }
         public virtual int IndexOfLocalName(string[] localNames, string namespaceUri) { throw null; }
         public virtual int IndexOfLocalName(System.Xml.XmlDictionaryString[] localNames, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
@@ -240,7 +240,7 @@ namespace System.Xml
         public virtual bool IsLocalName(System.Xml.XmlDictionaryString localName) { throw null; }
         public virtual bool IsNamespaceUri(string namespaceUri) { throw null; }
         public virtual bool IsNamespaceUri(System.Xml.XmlDictionaryString namespaceUri) { throw null; }
-        public virtual bool IsStartArray(out System.Type type) { throw null; }
+        public virtual bool IsStartArray([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Type? type) { throw null; }
         public virtual bool IsStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
         protected bool IsTextNode(System.Xml.XmlNodeType nodeType) { throw null; }
         public virtual void MoveToStartElement() { }
@@ -269,7 +269,7 @@ namespace System.Xml
         public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.TimeSpan[] array, int offset, int count) { throw null; }
         public virtual bool[] ReadBooleanArray(string localName, string namespaceUri) { throw null; }
         public virtual bool[] ReadBooleanArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
-        public override object ReadContentAs(System.Type type, System.Xml.IXmlNamespaceResolver namespaceResolver) { throw null; }
+        public override object ReadContentAs(System.Type type, System.Xml.IXmlNamespaceResolver? namespaceResolver) { throw null; }
         public virtual byte[] ReadContentAsBase64() { throw null; }
         public virtual byte[] ReadContentAsBinHex() { throw null; }
         protected byte[] ReadContentAsBinHex(int maxByteArrayContentLength) { throw null; }
@@ -323,12 +323,12 @@ namespace System.Xml
         public virtual System.TimeSpan[] ReadTimeSpanArray(string localName, string namespaceUri) { throw null; }
         public virtual System.TimeSpan[] ReadTimeSpanArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
         public virtual int ReadValueAsBase64(byte[] buffer, int offset, int count) { throw null; }
-        public virtual void StartCanonicalization(System.IO.Stream stream, bool includeComments, string[] inclusivePrefixes) { }
+        public virtual void StartCanonicalization(System.IO.Stream stream, bool includeComments, string[]? inclusivePrefixes) { }
         public virtual bool TryGetArrayLength(out int count) { throw null; }
         public virtual bool TryGetBase64ContentLength(out int length) { throw null; }
-        public virtual bool TryGetLocalNameAsDictionaryString(out System.Xml.XmlDictionaryString localName) { throw null; }
-        public virtual bool TryGetNamespaceUriAsDictionaryString(out System.Xml.XmlDictionaryString namespaceUri) { throw null; }
-        public virtual bool TryGetValueAsDictionaryString(out System.Xml.XmlDictionaryString value) { throw null; }
+        public virtual bool TryGetLocalNameAsDictionaryString([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? localName) { throw null; }
+        public virtual bool TryGetNamespaceUriAsDictionaryString([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? namespaceUri) { throw null; }
+        public virtual bool TryGetValueAsDictionaryString([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Xml.XmlDictionaryString? value) { throw null; }
     }
     public sealed partial class XmlDictionaryReaderQuotas
     {
@@ -370,60 +370,60 @@ namespace System.Xml
         protected XmlDictionaryWriter() { }
         public virtual bool CanCanonicalize { get { throw null; } }
         public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream) { throw null; }
-        public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary) { throw null; }
-        public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session) { throw null; }
-        public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session, bool ownsStream) { throw null; }
+        public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary? dictionary) { throw null; }
+        public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary? dictionary, System.Xml.XmlBinaryWriterSession? session) { throw null; }
+        public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary? dictionary, System.Xml.XmlBinaryWriterSession? session, bool ownsStream) { throw null; }
         public static System.Xml.XmlDictionaryWriter CreateDictionaryWriter(System.Xml.XmlWriter writer) { throw null; }
         public static System.Xml.XmlDictionaryWriter CreateMtomWriter(System.IO.Stream stream, System.Text.Encoding encoding, int maxSizeInBytes, string startInfo) { throw null; }
-        public static System.Xml.XmlDictionaryWriter CreateMtomWriter(System.IO.Stream stream, System.Text.Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream) { throw null; }
+        public static System.Xml.XmlDictionaryWriter CreateMtomWriter(System.IO.Stream stream, System.Text.Encoding encoding, int maxSizeInBytes, string startInfo, string? boundary, string? startUri, bool writeMessageHeaders, bool ownsStream) { throw null; }
         public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream) { throw null; }
         public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream, System.Text.Encoding encoding) { throw null; }
         public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream, System.Text.Encoding encoding, bool ownsStream) { throw null; }
         public virtual void EndCanonicalization() { }
-        public virtual void StartCanonicalization(System.IO.Stream stream, bool includeComments, string[] inclusivePrefixes) { }
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.DateTime[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.Guid[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.TimeSpan[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.DateTime[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, double[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.Guid[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, short[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, int[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, long[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, float[] array, int offset, int count) { }
-        public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.TimeSpan[] array, int offset, int count) { }
-        public void WriteAttributeString(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
-        public void WriteAttributeString(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
+        public virtual void StartCanonicalization(System.IO.Stream stream, bool includeComments, string[]? inclusivePrefixes) { }
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, bool[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, System.DateTime[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, decimal[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, double[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, System.Guid[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, short[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, int[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, long[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, float[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, System.TimeSpan[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, bool[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, System.DateTime[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, decimal[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, double[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, System.Guid[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, short[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, int[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, long[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, float[] array, int offset, int count) { }
+        public virtual void WriteArray(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, System.TimeSpan[] array, int offset, int count) { }
+        public void WriteAttributeString(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, string? value) { }
+        public void WriteAttributeString(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, string? value) { }
         public override System.Threading.Tasks.Task WriteBase64Async(byte[] buffer, int index, int count) { throw null; }
-        public void WriteElementString(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
-        public void WriteElementString(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
+        public void WriteElementString(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, string? value) { }
+        public void WriteElementString(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri, string? value) { }
         public virtual void WriteNode(System.Xml.XmlDictionaryReader reader, bool defattr) { }
         public override void WriteNode(System.Xml.XmlReader reader, bool defattr) { }
-        public virtual void WriteQualifiedName(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
-        public virtual void WriteStartAttribute(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
-        public void WriteStartAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
-        public virtual void WriteStartElement(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
-        public void WriteStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
-        public virtual void WriteString(System.Xml.XmlDictionaryString value) { }
+        public virtual void WriteQualifiedName(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri) { }
+        public virtual void WriteStartAttribute(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri) { }
+        public void WriteStartAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri) { }
+        public virtual void WriteStartElement(string? prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri) { }
+        public void WriteStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? namespaceUri) { }
+        public virtual void WriteString(System.Xml.XmlDictionaryString? value) { }
         protected virtual void WriteTextNode(System.Xml.XmlDictionaryReader reader, bool isAttribute) { }
         public virtual void WriteValue(System.Guid value) { }
         public virtual void WriteValue(System.TimeSpan value) { }
         public virtual void WriteValue(System.Xml.IStreamProvider value) { }
         public virtual void WriteValue(System.Xml.UniqueId value) { }
-        public virtual void WriteValue(System.Xml.XmlDictionaryString value) { }
+        public virtual void WriteValue(System.Xml.XmlDictionaryString? value) { }
         public virtual System.Threading.Tasks.Task WriteValueAsync(System.Xml.IStreamProvider value) { throw null; }
-        public virtual void WriteXmlAttribute(string localName, string value) { }
-        public virtual void WriteXmlAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString value) { }
-        public virtual void WriteXmlnsAttribute(string prefix, string namespaceUri) { }
-        public virtual void WriteXmlnsAttribute(string prefix, System.Xml.XmlDictionaryString namespaceUri) { }
+        public virtual void WriteXmlAttribute(string localName, string? value) { }
+        public virtual void WriteXmlAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString? value) { }
+        public virtual void WriteXmlnsAttribute(string? prefix, string namespaceUri) { }
+        public virtual void WriteXmlnsAttribute(string? prefix, System.Xml.XmlDictionaryString namespaceUri) { }
     }
 }
index 779404e..4e128a3 100644 (file)
@@ -1,6 +1,7 @@
 <Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="System.Runtime.Serialization.Xml.cs" />
index 4c21181..dfb110c 100644 (file)
@@ -2,6 +2,7 @@
   <PropertyGroup>
     <IsPartialFacadeAssembly>true</IsPartialFacadeAssembly>
     <TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <ProjectReference Include="$(LibrariesProjectRoot)System.Private.DataContractSerialization\src\System.Private.DataContractSerialization.csproj" />