Annotate System.Runtime.Serialization.Formatters for nullable (dotnet/corefx#42188)
authorbuyaa-n <bunamnan@microsoft.com>
Wed, 6 Nov 2019 02:01:44 +0000 (18:01 -0800)
committerSantiago Fernandez Madero <safern@microsoft.com>
Wed, 6 Nov 2019 02:01:44 +0000 (18:01 -0800)
* Annotate System.Runtime.Serialization.Formatters for nullable

* Some update

* Some more update

* Applying feedback

* Reverting back some changes

* Little typo

Commit migrated from https://github.com/dotnet/corefx/commit/14424c1980f1ed7d8b5c56010675c8de7dbd7450

38 files changed:
src/libraries/System.Runtime.Serialization.Formatters/ref/System.Runtime.Serialization.Formatters.cs
src/libraries/System.Runtime.Serialization.Formatters/ref/System.Runtime.Serialization.Formatters.csproj
src/libraries/System.Runtime.Serialization.Formatters/src/System.Runtime.Serialization.Formatters.csproj
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/DeserializationEventHandler.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatter.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterConverter.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterServices.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryArray.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryAssembly.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryAssemblyInfo.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectString.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWithMap.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWithMapTyped.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryTypeConverter.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryUtilClasses.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/Converter.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/MemberPrimitiveTyped.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/MemberPrimitiveUntyped.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectMap.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectProgress.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/IFieldInfo.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/IFormatter.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ISerializationSurrogate.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ISurrogateSelector.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/MemberHolder.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationBinder.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationEventsCache.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationFieldInfo.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationObjectManager.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SurrogateSelector.cs
src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ValueTypeFixupInfo.cs

index 2862e7b..35bd604 100644 (file)
@@ -13,12 +13,12 @@ namespace System.Runtime.Serialization
         protected System.Runtime.Serialization.ObjectIDGenerator m_idGenerator;
         protected System.Collections.Queue m_objectQueue;
         protected Formatter() { }
-        public abstract System.Runtime.Serialization.SerializationBinder Binder { get; set; }
+        public abstract System.Runtime.Serialization.SerializationBinder? Binder { get; set; }
         public abstract System.Runtime.Serialization.StreamingContext Context { get; set; }
-        public abstract System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get; set; }
+        public abstract System.Runtime.Serialization.ISurrogateSelector? SurrogateSelector { get; set; }
         public abstract object Deserialize(System.IO.Stream serializationStream);
-        protected virtual object GetNext(out long objID) { throw null; }
-        protected virtual long Schedule(object obj) { throw null; }
+        protected virtual object? GetNext(out long objID) { throw null; }
+        protected virtual long Schedule(object? obj) { throw null; }
         public abstract void Serialize(System.IO.Stream serializationStream, object graph);
         protected abstract void WriteArray(object obj, string name, System.Type memberType);
         protected abstract void WriteBoolean(bool val, string name);
@@ -30,8 +30,8 @@ namespace System.Runtime.Serialization
         protected abstract void WriteInt16(short val, string name);
         protected abstract void WriteInt32(int val, string name);
         protected abstract void WriteInt64(long val, string name);
-        protected virtual void WriteMember(string memberName, object data) { }
-        protected abstract void WriteObjectRef(object obj, string name, System.Type memberType);
+        protected virtual void WriteMember(string memberName, object? data) { }
+        protected abstract void WriteObjectRef(object? obj, string name, System.Type memberType);
         [System.CLSCompliantAttribute(false)]
         protected abstract void WriteSByte(sbyte val, string name);
         protected abstract void WriteSingle(float val, string name);
@@ -61,7 +61,7 @@ namespace System.Runtime.Serialization
         [System.CLSCompliantAttribute(false)]
         public sbyte ToSByte(object value) { throw null; }
         public float ToSingle(object value) { throw null; }
-        public string ToString(object value) { throw null; }
+        public string? ToString(object value) { throw null; }
         [System.CLSCompliantAttribute(false)]
         public ushort ToUInt16(object value) { throw null; }
         [System.CLSCompliantAttribute(false)]
@@ -72,33 +72,33 @@ namespace System.Runtime.Serialization
     public static partial class FormatterServices
     {
         public static void CheckTypeSecurity(System.Type t, System.Runtime.Serialization.Formatters.TypeFilterLevel securityLevel) { }
-        public static object[] GetObjectData(object obj, System.Reflection.MemberInfo[] members) { throw null; }
+        public static object?[] GetObjectData(object obj, System.Reflection.MemberInfo[] members) { throw null; }
         public static object GetSafeUninitializedObject(System.Type type) { throw null; }
         public static System.Reflection.MemberInfo[] GetSerializableMembers(System.Type type) { throw null; }
         public static System.Reflection.MemberInfo[] GetSerializableMembers(System.Type type, System.Runtime.Serialization.StreamingContext context) { throw null; }
         public static System.Runtime.Serialization.ISerializationSurrogate GetSurrogateForCyclicalReference(System.Runtime.Serialization.ISerializationSurrogate innerSurrogate) { throw null; }
-        public static System.Type GetTypeFromAssembly(System.Reflection.Assembly assem, string name) { throw null; }
+        public static System.Type? GetTypeFromAssembly(System.Reflection.Assembly assem, string name) { throw null; }
         public static object GetUninitializedObject(System.Type type) { throw null; }
-        public static object PopulateObjectMembers(object obj, System.Reflection.MemberInfo[] members, object[] data) { throw null; }
+        public static object PopulateObjectMembers(object obj, System.Reflection.MemberInfo[] members, object?[] data) { throw null; }
     }
     public partial interface IFormatter
     {
-        System.Runtime.Serialization.SerializationBinder Binder { get; set; }
+        System.Runtime.Serialization.SerializationBinder? Binder { get; set; }
         System.Runtime.Serialization.StreamingContext Context { get; set; }
-        System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get; set; }
+        System.Runtime.Serialization.ISurrogateSelector? SurrogateSelector { get; set; }
         object Deserialize(System.IO.Stream serializationStream);
         void Serialize(System.IO.Stream serializationStream, object graph);
     }
     public partial interface ISerializationSurrogate
     {
         void GetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
-        object SetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.ISurrogateSelector selector);
+        object SetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.ISurrogateSelector? selector);
     }
     public partial interface ISurrogateSelector
     {
         void ChainSelector(System.Runtime.Serialization.ISurrogateSelector selector);
-        System.Runtime.Serialization.ISurrogateSelector GetNextSelector();
-        System.Runtime.Serialization.ISerializationSurrogate GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector);
+        System.Runtime.Serialization.ISurrogateSelector? GetNextSelector();
+        System.Runtime.Serialization.ISerializationSurrogate? GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector);
     }
     public partial class ObjectIDGenerator
     {
@@ -108,9 +108,9 @@ namespace System.Runtime.Serialization
     }
     public partial class ObjectManager
     {
-        public ObjectManager(System.Runtime.Serialization.ISurrogateSelector selector, System.Runtime.Serialization.StreamingContext context) { }
+        public ObjectManager(System.Runtime.Serialization.ISurrogateSelector? selector, System.Runtime.Serialization.StreamingContext context) { }
         public virtual void DoFixups() { }
-        public virtual object GetObject(long objectID) { throw null; }
+        public virtual object? GetObject(long objectID) { throw null; }
         public virtual void RaiseDeserializationEvent() { }
         public void RaiseOnDeserializingEvent(object obj) { }
         public virtual void RecordArrayElementFixup(long arrayToBeFixed, int index, long objectRequired) { }
@@ -119,14 +119,14 @@ namespace System.Runtime.Serialization
         public virtual void RecordFixup(long objectToBeFixed, System.Reflection.MemberInfo member, long objectRequired) { }
         public virtual void RegisterObject(object obj, long objectID) { }
         public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info) { }
-        public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info, long idOfContainingObj, System.Reflection.MemberInfo member) { }
-        public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info, long idOfContainingObj, System.Reflection.MemberInfo member, int[] arrayIndex) { }
+        public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo? info, long idOfContainingObj, System.Reflection.MemberInfo? member) { }
+        public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo? info, long idOfContainingObj, System.Reflection.MemberInfo? member, int[]? arrayIndex) { }
     }
     public abstract partial class SerializationBinder
     {
         protected SerializationBinder() { }
-        public virtual void BindToName(System.Type serializedType, out string assemblyName, out string typeName) { throw null; }
-        public abstract System.Type BindToType(string assemblyName, string typeName);
+        public virtual void BindToName(System.Type serializedType, out string? assemblyName, out string? typeName) { throw null; }
+        public abstract System.Type? BindToType(string assemblyName, string typeName);
     }
     public sealed partial class SerializationObjectManager
     {
@@ -139,8 +139,8 @@ namespace System.Runtime.Serialization
         public SurrogateSelector() { }
         public virtual void AddSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.ISerializationSurrogate surrogate) { }
         public virtual void ChainSelector(System.Runtime.Serialization.ISurrogateSelector selector) { }
-        public virtual System.Runtime.Serialization.ISurrogateSelector GetNextSelector() { throw null; }
-        public virtual System.Runtime.Serialization.ISerializationSurrogate GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector) { throw null; }
+        public virtual System.Runtime.Serialization.ISurrogateSelector? GetNextSelector() { throw null; }
+        public virtual System.Runtime.Serialization.ISerializationSurrogate? GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector) { throw null; }
         public virtual void RemoveSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context) { }
     }
 }
@@ -159,8 +159,8 @@ namespace System.Runtime.Serialization.Formatters
     }
     public partial interface IFieldInfo
     {
-        string[] FieldNames { get; set; }
-        System.Type[] FieldTypes { get; set; }
+        string[]? FieldNames { get; set; }
+        System.Type[]? FieldTypes { get; set; }
     }
     public enum TypeFilterLevel
     {
@@ -173,12 +173,12 @@ namespace System.Runtime.Serialization.Formatters.Binary
     public sealed partial class BinaryFormatter : System.Runtime.Serialization.IFormatter
     {
         public BinaryFormatter() { }
-        public BinaryFormatter(System.Runtime.Serialization.ISurrogateSelector selector, System.Runtime.Serialization.StreamingContext context) { }
+        public BinaryFormatter(System.Runtime.Serialization.ISurrogateSelector? selector, System.Runtime.Serialization.StreamingContext context) { }
         public System.Runtime.Serialization.Formatters.FormatterAssemblyStyle AssemblyFormat { get { throw null; } set { } }
-        public System.Runtime.Serialization.SerializationBinder Binder { get { throw null; } set { } }
+        public System.Runtime.Serialization.SerializationBinder? Binder { get { throw null; } set { } }
         public System.Runtime.Serialization.StreamingContext Context { get { throw null; } set { } }
         public System.Runtime.Serialization.Formatters.TypeFilterLevel FilterLevel { get { throw null; } set { } }
-        public System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get { throw null; } set { } }
+        public System.Runtime.Serialization.ISurrogateSelector? SurrogateSelector { get { throw null; } set { } }
         public System.Runtime.Serialization.Formatters.FormatterTypeStyle TypeFormat { get { throw null; } set { } }
         public object Deserialize(System.IO.Stream serializationStream) { throw null; }
         public void Serialize(System.IO.Stream serializationStream, object graph) { }
index 0acfc02..f0f7e05 100644 (file)
@@ -1,6 +1,7 @@
 <Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <Configurations>netcoreapp-Debug;netcoreapp-Release</Configurations>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="System.Runtime.Serialization.Formatters.cs" />
index c730b2b..f4a4d09 100644 (file)
@@ -4,6 +4,7 @@
     <RootNamespace>System.Runtime.Serialization.Formatters</RootNamespace>
     <NoWarn>$(NoWarn);CS1573</NoWarn>
     <Configurations>netcoreapp-Unix-Debug;netcoreapp-Unix-Release;netcoreapp-Windows_NT-Debug;netcoreapp-Windows_NT-Release</Configurations>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="System.Runtime.Serialization.Formatters.TypeForwards.cs" />
index e739ee7..259e5a6 100644 (file)
@@ -4,7 +4,7 @@
 
 namespace System.Runtime.Serialization
 {
-    internal delegate void DeserializationEventHandler(object sender);
+    internal delegate void DeserializationEventHandler(object? sender);
 
     public delegate void SerializationEventHandler(StreamingContext context);
 }
index 74e34d6..1c82d84 100644 (file)
@@ -23,7 +23,7 @@ namespace System.Runtime.Serialization
 
         public abstract object Deserialize(Stream serializationStream);
 
-        protected virtual object GetNext(out long objID)
+        protected virtual object? GetNext(out long objID)
         {
             if (m_objectQueue.Count == 0)
             {
@@ -31,7 +31,7 @@ namespace System.Runtime.Serialization
                 return null;
             }
 
-            object obj = m_objectQueue.Dequeue();
+            object obj = m_objectQueue.Dequeue()!;
 
             bool isNew;
             objID = m_idGenerator.HasId(obj, out isNew);
@@ -43,7 +43,7 @@ namespace System.Runtime.Serialization
             return obj;
         }
 
-        protected virtual long Schedule(object obj)
+        protected virtual long Schedule(object? obj)
         {
             if (obj == null)
             {
@@ -82,9 +82,9 @@ namespace System.Runtime.Serialization
 
         protected abstract void WriteInt64(long val, string name);
 
-        protected abstract void WriteObjectRef(object obj, string name, Type memberType);
+        protected abstract void WriteObjectRef(object? obj, string name, Type memberType);
 
-        protected virtual void WriteMember(string memberName, object data)
+        protected virtual void WriteMember(string memberName, object? data)
         {
             if (data == null)
             {
@@ -182,9 +182,9 @@ namespace System.Runtime.Serialization
 
         protected abstract void WriteValueType(object obj, string name, Type memberType);
 
-        public abstract ISurrogateSelector SurrogateSelector { get; set; }
+        public abstract ISurrogateSelector? SurrogateSelector { get; set; }
 
-        public abstract SerializationBinder Binder { get; set; }
+        public abstract SerializationBinder? Binder { get; set; }
 
         public abstract StreamingContext Context { get; set; }
     }
index b60193b..6723373 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Diagnostics.CodeAnalysis;
 using System.Globalization;
 using System.Runtime.CompilerServices;
 
@@ -109,12 +110,13 @@ namespace System.Runtime.Serialization
             return System.Convert.ToDateTime(value, CultureInfo.InvariantCulture);
         }
 
-        public string ToString(object value)
+        public string? ToString(object value)
         {
             if (value == null) ThrowValueNullException();
             return System.Convert.ToString(value, CultureInfo.InvariantCulture);
         }
 
+        [DoesNotReturn]
         private static void ThrowValueNullException()
         {
             throw new ArgumentNullException("value");
index dbddcd0..2c92cb5 100644 (file)
@@ -36,26 +36,24 @@ namespace System.Runtime.Serialization
             // If this class doesn't extend directly from object, walk its hierarchy and
             // get all of the private and assembly-access fields (e.g. all fields that aren't
             // virtual) and include them in the list of things to be serialized.
-            Type parentType = type.BaseType;
+            Type? parentType = type.BaseType;
             if (parentType != null && parentType != typeof(object))
             {
-                Type[] parentTypes;
-                int parentTypeCount;
-                bool classNamesUnique = GetParentTypes(parentType, out parentTypes, out parentTypeCount);
+                bool classNamesUnique = GetParentTypes(parentType, out Type[]? parentTypes, out int parentTypeCount);
 
                 if (parentTypeCount > 0)
                 {
                     var allMembers = new List<FieldInfo>();
                     for (int i = 0; i < parentTypeCount; i++)
                     {
-                        parentType = parentTypes[i];
+                        parentType = parentTypes![i];
                         if (!parentType.IsSerializable)
                         {
                             throw new SerializationException(SR.Format(SR.Serialization_NonSerType, parentType.FullName, parentType.Module.Assembly.FullName));
                         }
 
                         FieldInfo[] typeFields = parentType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
-                        string typeName = classNamesUnique ? parentType.Name : parentType.FullName;
+                        string typeName = classNamesUnique ? parentType.Name : parentType.FullName!;
                         foreach (FieldInfo field in typeFields)
                         {
                             // Family and Assembly fields will be gathered by the type itself.
@@ -119,7 +117,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        private static bool GetParentTypes(Type parentType, out Type[] parentTypes, out int parentTypeCount)
+        private static bool GetParentTypes(Type parentType, out Type[]? parentTypes, out int parentTypeCount)
         {
             parentTypes = null;
             parentTypeCount = 0;
@@ -128,7 +126,7 @@ namespace System.Runtime.Serialization
             // typeName to prefix the Field names in SerializationFieldInfo
             bool unique = true;
             Type objectType = typeof(object);
-            for (Type t1 = parentType; t1 != objectType; t1 = t1.BaseType)
+            for (Type t1 = parentType; t1 != objectType; t1 = t1.BaseType!)
             {
                 if (t1.IsInterface)
                 {
@@ -138,7 +136,7 @@ namespace System.Runtime.Serialization
                 string t1Name = t1.Name;
                 for (int i = 0; unique && i < parentTypeCount; i++)
                 {
-                    string t2Name = parentTypes[i].Name;
+                    string t2Name = parentTypes![i].Name;
                     if (t2Name.Length == t1Name.Length && t2Name[0] == t1Name[0] && t1Name == t2Name)
                     {
                         unique = false;
@@ -186,12 +184,11 @@ namespace System.Runtime.Serialization
 
         public static object GetSafeUninitializedObject(Type type) => RuntimeHelpers.GetUninitializedObject(type);
 
-        internal static void SerializationSetValue(MemberInfo fi, object target, object value)
+        internal static void SerializationSetValue(MemberInfo fi, object? target, object? value)
         {
             Debug.Assert(fi != null);
 
-            var serField = fi as FieldInfo;
-            if (serField != null)
+            if (fi is FieldInfo serField)
             {
                 serField.SetValue(target, value);
                 return;
@@ -200,7 +197,7 @@ namespace System.Runtime.Serialization
             throw new ArgumentException(SR.Argument_InvalidFieldInfo);
         }
 
-        public static object PopulateObjectMembers(object obj, MemberInfo[] members, object[] data)
+        public static object PopulateObjectMembers(object obj, MemberInfo[] members, object?[] data)
         {
             if (obj == null)
             {
@@ -230,15 +227,14 @@ namespace System.Runtime.Serialization
                 // If we find an empty, it means that the value was never set during deserialization.
                 // This is either a forward reference or a null.  In either case, this may break some of the
                 // invariants mantained by the setter, so we'll do nothing with it for right now.
-                object value = data[i];
+                object? value = data[i];
                 if (value == null)
                 {
                     continue;
                 }
 
                 // If it's a field, set its value.
-                FieldInfo field = member as FieldInfo;
-                if (field != null)
+                if (member is FieldInfo field)
                 {
                     field.SetValue(obj, data[i]);
                     continue;
@@ -251,7 +247,7 @@ namespace System.Runtime.Serialization
             return obj;
         }
 
-        public static object[] GetObjectData(object obj, MemberInfo[] members)
+        public static object?[] GetObjectData(object obj, MemberInfo[] members)
         {
             if (obj == null)
             {
@@ -262,7 +258,7 @@ namespace System.Runtime.Serialization
                 throw new ArgumentNullException(nameof(members));
             }
 
-            object[] data = new object[members.Length];
+            object?[] data = new object[members.Length];
             for (int i = 0; i < members.Length; i++)
             {
                 MemberInfo member = members[i];
@@ -271,7 +267,7 @@ namespace System.Runtime.Serialization
                     throw new ArgumentNullException(nameof(members), SR.Format(SR.ArgumentNull_NullMember, i));
                 }
 
-                FieldInfo field = member as FieldInfo;
+                FieldInfo? field = member as FieldInfo;
                 if (field == null)
                 {
                     throw new SerializationException(SR.Serialization_UnknownMemberInfo);
@@ -291,7 +287,7 @@ namespace System.Runtime.Serialization
             return new SurrogateForCyclicalReference(innerSurrogate);
         }
 
-        public static Type GetTypeFromAssembly(Assembly assem, string name)
+        public static Type? GetTypeFromAssembly(Assembly assem, string name)
         {
             if (assem == null)
             {
@@ -305,7 +301,7 @@ namespace System.Runtime.Serialization
             return Assembly.Load(new AssemblyName(assemblyName));
         }
 
-        internal static Assembly LoadAssemblyFromStringNoThrow(string assemblyName)
+        internal static Assembly? LoadAssemblyFromStringNoThrow(string assemblyName)
         {
             try
             {
@@ -326,7 +322,7 @@ namespace System.Runtime.Serialization
             Type attributedType = type;
             while (attributedType.HasElementType)
             {
-                attributedType = attributedType.GetElementType();
+                attributedType = attributedType.GetElementType()!;
             }
 
             foreach (Attribute first in attributedType.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false))
@@ -336,7 +332,7 @@ namespace System.Runtime.Serialization
             }
 
             hasTypeForwardedFrom = false;
-            return type.Assembly.FullName;
+            return type.Assembly.FullName!;
         }
 
         internal static string GetClrTypeFullName(Type type)
@@ -350,7 +346,7 @@ namespace System.Runtime.Serialization
         {
             int rank = type.GetArrayRank();
             Debug.Assert(rank >= 1);
-            string typeName = GetClrTypeFullName(type.GetElementType());
+            string typeName = GetClrTypeFullName(type.GetElementType()!);
             return rank == 1 ?
                 typeName + "[]" :
                 typeName + "[" + new string(',', rank - 1) + "]";
@@ -360,7 +356,7 @@ namespace System.Runtime.Serialization
         {
             if (!type.IsGenericType)
             {
-                return type.FullName;
+                return type.FullName!;
             }
 
             var builder = new StringBuilder(type.GetGenericTypeDefinition().FullName).Append("[");
@@ -392,7 +388,7 @@ namespace System.Runtime.Serialization
             _innerSurrogate.GetObjectData(obj, info, context);
         }
 
-        public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
+        public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector? selector)
         {
             return _innerSurrogate.SetObjectData(obj, info, context, selector);
         }
index 1d5e39c..f36cfc4 100644 (file)
@@ -2,16 +2,18 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Diagnostics;
+
 namespace System.Runtime.Serialization.Formatters.Binary
 {
     internal sealed class BinaryArray : IStreamable
     {
         internal int _objectId;
         internal int _rank;
-        internal int[] _lengthA;
-        internal int[] _lowerBoundA;
+        internal int[]? _lengthA;
+        internal int[]? _lowerBoundA;
         internal BinaryTypeEnum _binaryTypeEnum;
-        internal object _typeInformation;
+        internal object? _typeInformation;
         internal int _assemId = 0;
         private BinaryHeaderEnum _binaryHeaderEnum;
         internal BinaryArrayTypeEnum _binaryArrayTypeEnum;
@@ -23,7 +25,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _binaryHeaderEnum = binaryHeaderEnum;
         }
 
-        internal void Set(int objectId, int rank, int[] lengthA, int[] lowerBoundA, BinaryTypeEnum binaryTypeEnum, object typeInformation, BinaryArrayTypeEnum binaryArrayTypeEnum, int assemId)
+        internal void Set(int objectId, int rank, int[] lengthA, int[]? lowerBoundA, BinaryTypeEnum binaryTypeEnum, object? typeInformation, BinaryArrayTypeEnum binaryArrayTypeEnum, int assemId)
         {
             _objectId = objectId;
             _binaryArrayTypeEnum = binaryArrayTypeEnum;
@@ -54,13 +56,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         public void Write(BinaryFormatterWriter output)
         {
+            Debug.Assert(_lengthA != null);
             switch (_binaryHeaderEnum)
             {
                 case BinaryHeaderEnum.ArraySinglePrimitive:
                     output.WriteByte((byte)_binaryHeaderEnum);
                     output.WriteInt32(_objectId);
                     output.WriteInt32(_lengthA[0]);
-                    output.WriteByte((byte)((InternalPrimitiveTypeE)_typeInformation));
+                    output.WriteByte((byte)((InternalPrimitiveTypeE)_typeInformation!));
                     break;
                 case BinaryHeaderEnum.ArraySingleString:
                     output.WriteByte((byte)_binaryHeaderEnum);
@@ -85,6 +88,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                         (_binaryArrayTypeEnum == BinaryArrayTypeEnum.JaggedOffset) ||
                         (_binaryArrayTypeEnum == BinaryArrayTypeEnum.RectangularOffset))
                     {
+                        Debug.Assert(_lowerBoundA != null);
                         for (int i = 0; i < _rank; i++)
                         {
                             output.WriteInt32(_lowerBoundA[i]);
index 14b357b..5fd771b 100644 (file)
@@ -2,12 +2,14 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Diagnostics;
+
 namespace System.Runtime.Serialization.Formatters.Binary
 {
     internal sealed class BinaryAssembly : IStreamable
     {
         internal int _assemId;
-        internal string _assemblyString;
+        internal string? _assemblyString;
 
         internal BinaryAssembly() { }
 
@@ -21,6 +23,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         {
             output.WriteByte((byte)BinaryHeaderEnum.Assembly);
             output.WriteInt32(_assemId);
+            Debug.Assert(_assemblyString != null);
             output.WriteString(_assemblyString);
         }
 
index 3a647b3..958c32d 100644 (file)
@@ -9,14 +9,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
     internal sealed class BinaryAssemblyInfo
     {
         internal string _assemblyString;
-        private Assembly _assembly;
+        private Assembly? _assembly;
 
         internal BinaryAssemblyInfo(string assemblyString)
         {
             _assemblyString = assemblyString;
         }
 
-        internal BinaryAssemblyInfo(string assemblyString, Assembly assembly) : this(assemblyString)
+        internal BinaryAssemblyInfo(string assemblyString, Assembly? assembly) : this(assemblyString)
         {
             _assembly = assembly;
         }
index a1a6454..97fa3a6 100644 (file)
@@ -13,26 +13,26 @@ namespace System.Runtime.Serialization.Formatters.Binary
     {
         private static readonly ConcurrentDictionary<Type, TypeInformation> s_typeNameCache = new ConcurrentDictionary<Type, TypeInformation>();
 
-        internal ISurrogateSelector _surrogates;
+        internal ISurrogateSelector? _surrogates;
         internal StreamingContext _context;
-        internal SerializationBinder _binder;
+        internal SerializationBinder? _binder;
         internal FormatterTypeStyle _typeFormat = FormatterTypeStyle.TypesAlways; // For version resiliency, always put out types
         internal FormatterAssemblyStyle _assemblyFormat = FormatterAssemblyStyle.Simple;
         internal TypeFilterLevel _securityLevel = TypeFilterLevel.Full;
-        internal object[] _crossAppDomainArray = null;
+        internal object[]? _crossAppDomainArray = null;
 
         public FormatterTypeStyle TypeFormat { get { return _typeFormat; } set { _typeFormat = value; } }
         public FormatterAssemblyStyle AssemblyFormat { get { return _assemblyFormat; } set { _assemblyFormat = value; } }
         public TypeFilterLevel FilterLevel { get { return _securityLevel; } set { _securityLevel = value; } }
-        public ISurrogateSelector SurrogateSelector { get { return _surrogates; } set { _surrogates = value; } }
-        public SerializationBinder Binder { get { return _binder; } set { _binder = value; } }
+        public ISurrogateSelector? SurrogateSelector { get { return _surrogates; } set { _surrogates = value; } }
+        public SerializationBinder? Binder { get { return _binder; } set { _binder = value; } }
         public StreamingContext Context { get { return _context; } set { _context = value; } }
 
         public BinaryFormatter() : this(null, new StreamingContext(StreamingContextStates.All))
         {
         }
 
-        public BinaryFormatter(ISurrogateSelector selector, StreamingContext context)
+        public BinaryFormatter(ISurrogateSelector? selector, StreamingContext context)
         {
             _surrogates = selector;
             _context = context;
index 85b5e56..34ac7be 100644 (file)
@@ -18,23 +18,23 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private readonly Stream _outputStream;
         private readonly FormatterTypeStyle _formatterTypeStyle;
-        private readonly ObjectWriter _objectWriter = null;
-        private readonly BinaryWriter _dataWriter = null;
+        private readonly ObjectWriter _objectWriter;
+        private readonly BinaryWriter _dataWriter;
 
         private int _consecutiveNullArrayEntryCount = 0;
-        private Dictionary<string, ObjectMapInfo> _objectMapTable;
-
-        private BinaryObject _binaryObject;
-        private BinaryObjectWithMap _binaryObjectWithMap;
-        private BinaryObjectWithMapTyped _binaryObjectWithMapTyped;
-        private BinaryObjectString _binaryObjectString;
-        private BinaryArray _binaryArray;
-        private byte[] _byteBuffer = null;
-        private MemberPrimitiveUnTyped _memberPrimitiveUnTyped;
-        private MemberPrimitiveTyped _memberPrimitiveTyped;
-        private ObjectNull _objectNull;
-        private MemberReference _memberReference;
-        private BinaryAssembly _binaryAssembly;
+        private Dictionary<string, ObjectMapInfo>? _objectMapTable;
+
+        private BinaryObject? _binaryObject;
+        private BinaryObjectWithMap? _binaryObjectWithMap;
+        private BinaryObjectWithMapTyped? _binaryObjectWithMapTyped;
+        private BinaryObjectString? _binaryObjectString;
+        private BinaryArray? _binaryArray;
+        private byte[]? _byteBuffer = null;
+        private MemberPrimitiveUnTyped? _memberPrimitiveUnTyped;
+        private MemberPrimitiveTyped? _memberPrimitiveTyped;
+        private ObjectNull? _objectNull;
+        private MemberReference? _memberReference;
+        private BinaryAssembly? _binaryAssembly;
 
         internal BinaryFormatterWriter(Stream outputStream, ObjectWriter objectWriter, FormatterTypeStyle formatterTypeStyle)
         {
@@ -112,23 +112,24 @@ namespace System.Runtime.Serialization.Formatters.Binary
             record.Write(this);
         }
 
-        internal void WriteObject(NameInfo nameInfo, NameInfo typeNameInfo, int numMembers, string[] memberNames, Type[] memberTypes, WriteObjectInfo[] memberObjectInfos)
+        internal void WriteObject(NameInfo nameInfo, NameInfo? typeNameInfo, int numMembers, string[] memberNames, Type[] memberTypes, WriteObjectInfo[] memberObjectInfos)
         {
             InternalWriteItemNull();
             int assemId;
             int objectId = (int)nameInfo._objectId;
 
-            string objectName = objectId < 0 ?
-                objectName = typeNameInfo.NIname : // Nested Object
-                objectName = nameInfo.NIname; // Non-Nested
+            Debug.Assert(typeNameInfo != null); // Explicitly called with null, asserting for now https://github.com/dotnet/corefx/issues/42393
+            string? objectName = objectId < 0 ?
+                typeNameInfo.NIname : // Nested Object
+                nameInfo.NIname; // Non-Nested
 
             if (_objectMapTable == null)
             {
                 _objectMapTable = new Dictionary<string, ObjectMapInfo>();
             }
 
-            ObjectMapInfo objectMapInfo;
-            if (_objectMapTable.TryGetValue(objectName, out objectMapInfo) &&
+            Debug.Assert(objectName != null);
+            if (_objectMapTable.TryGetValue(objectName, out ObjectMapInfo? objectMapInfo) &&
                 objectMapInfo.IsCompatible(numMembers, memberNames, memberTypes))
             {
                 // Object
@@ -162,11 +163,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
             {
                 // ObjectWithMapTyped
                 var binaryTypeEnumA = new BinaryTypeEnum[numMembers];
-                var typeInformationA = new object[numMembers];
+                var typeInformationA = new object?[numMembers];
                 var assemIdA = new int[numMembers];
                 for (int i = 0; i < numMembers; i++)
                 {
-                    object typeInformation = null;
+                    object? typeInformation = null;
                     binaryTypeEnumA[i] = BinaryTypeConverter.GetBinaryTypeInfo(memberTypes[i], memberObjectInfos[i], null, _objectWriter, out typeInformation, out assemId);
                     typeInformationA[i] = typeInformation;
                     assemIdA[i] = assemId;
@@ -188,7 +189,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
         }
 
-        internal void WriteObjectString(int objectId, string value)
+        internal void WriteObjectString(int objectId, string? value)
         {
             InternalWriteItemNull();
 
@@ -201,14 +202,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _binaryObjectString.Write(this);
         }
 
-        internal void WriteSingleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, Array array)
+        internal void WriteSingleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo? objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, Array array)
         {
             InternalWriteItemNull();
             BinaryArrayTypeEnum binaryArrayTypeEnum;
             var lengthA = new int[1];
             lengthA[0] = length;
-            int[] lowerBoundA = null;
-            object typeInformation = null;
+            int[]? lowerBoundA = null;
+            object? typeInformation = null;
 
             if (lowerBound == 0)
             {
@@ -223,7 +224,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             int assemId;
             BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(
-                arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
+                arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
 
             if (_binaryArray == null)
             {
@@ -254,7 +255,6 @@ namespace System.Runtime.Serialization.Formatters.Binary
         private void WriteArrayAsBytes(Array array, int typeLength)
         {
             InternalWriteItemNull();
-            int byteLength = array.Length * typeLength;
             int arrayOffset = 0;
             if (_byteBuffer == null)
             {
@@ -285,14 +285,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
         }
 
-        internal void WriteJaggedArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound)
+        internal void WriteJaggedArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo? objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound)
         {
             InternalWriteItemNull();
             BinaryArrayTypeEnum binaryArrayTypeEnum;
             var lengthA = new int[1];
             lengthA[0] = length;
-            int[] lowerBoundA = null;
-            object typeInformation = null;
+            int[]? lowerBoundA = null;
+            object? typeInformation = null;
             int assemId = 0;
 
             if (lowerBound == 0)
@@ -306,7 +306,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 lowerBoundA[0] = lowerBound;
             }
 
-            BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
+            BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
 
             if (_binaryArray == null)
             {
@@ -317,14 +317,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _binaryArray.Write(this);
         }
 
-        internal void WriteRectangleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int rank, int[] lengthA, int[] lowerBoundA)
+        internal void WriteRectangleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo? objectInfo, NameInfo arrayElemTypeNameInfo, int rank, int[] lengthA, int[] lowerBoundA)
         {
             InternalWriteItemNull();
 
             BinaryArrayTypeEnum binaryArrayTypeEnum = BinaryArrayTypeEnum.Rectangular;
-            object typeInformation = null;
+            object? typeInformation = null;
             int assemId = 0;
-            BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
+            BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
 
             if (_binaryArray == null)
             {
@@ -344,7 +344,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _binaryArray.Write(this);
         }
 
-        internal void WriteObjectByteArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, byte[] byteA)
+        internal void WriteObjectByteArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo? objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, byte[] byteA)
         {
             InternalWriteItemNull();
             WriteSingleArray(memberNameInfo, arrayNameInfo, objectInfo, arrayElemTypeNameInfo, length, lowerBound, byteA);
@@ -408,7 +408,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             InternalWriteItemNull();
         }
 
-        internal void WriteMemberString(NameInfo memberNameInfo, NameInfo typeNameInfo, string value)
+        internal void WriteMemberString(NameInfo memberNameInfo, NameInfo typeNameInfo, string? value)
         {
             InternalWriteItemNull();
             WriteObjectString((int)typeNameInfo._objectId, value);
@@ -453,7 +453,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             WriteMemberObjectRef(nameInfo, idRef);
         }
 
-        internal void WriteAssembly(Type type, string assemblyString, int assemId, bool isNew)
+        internal void WriteAssembly(Type? type, string assemblyString, int assemId, bool isNew)
         {
             //If the file being tested wasn't built as an assembly, then we're going to get null back
             //for the assembly name.  This is very unfortunate.
@@ -475,7 +475,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Method to write a value onto a stream given its primitive type code
-        internal void WriteValue(InternalPrimitiveTypeE code, object value)
+        internal void WriteValue(InternalPrimitiveTypeE code, object? value)
         {
             switch (code)
             {
@@ -492,8 +492,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 case InternalPrimitiveTypeE.UInt32: WriteUInt32(Convert.ToUInt32(value, CultureInfo.InvariantCulture)); break;
                 case InternalPrimitiveTypeE.UInt64: WriteUInt64(Convert.ToUInt64(value, CultureInfo.InvariantCulture)); break;
                 case InternalPrimitiveTypeE.Decimal: WriteDecimal(Convert.ToDecimal(value, CultureInfo.InvariantCulture)); break;
-                case InternalPrimitiveTypeE.TimeSpan: WriteTimeSpan((TimeSpan)value); break;
-                case InternalPrimitiveTypeE.DateTime: WriteDateTime((DateTime)value); break;
+                case InternalPrimitiveTypeE.TimeSpan: WriteTimeSpan((TimeSpan)value!); break;
+                case InternalPrimitiveTypeE.DateTime: WriteDateTime((DateTime)value!); break;
                 default: throw new SerializationException(SR.Format(SR.Serialization_TypeCode, code.ToString()));
             }
         }
@@ -513,7 +513,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 _memberTypes = memberTypes;
             }
 
-            internal bool IsCompatible(int numMembers, string[] memberNames, Type[] memberTypes)
+            internal bool IsCompatible(int numMembers, string[] memberNames, Type[]? memberTypes)
             {
                 if (_numMembers != numMembers)
                 {
index 45b732b..dd71d5e 100644 (file)
@@ -5,6 +5,7 @@
 using System.Threading;
 using System.Collections.Generic;
 using System.Reflection;
+using System.Diagnostics;
 
 namespace System.Runtime.Serialization.Formatters.Binary
 {
@@ -14,33 +15,34 @@ namespace System.Runtime.Serialization.Formatters.Binary
     internal sealed class WriteObjectInfo
     {
         internal int _objectInfoId;
-        internal object _obj;
-        internal Type _objectType;
+        internal object? _obj;
+        internal Type? _objectType;
 
         internal bool _isSi = false;
         internal bool _isNamed = false;
         internal bool _isArray = false;
 
-        internal SerializationInfo _si = null;
-        internal SerObjectInfoCache _cache = null;
+        internal SerializationInfo? _si = null;
+        internal SerObjectInfoCache _cache = null!; // Initiated before use
 
-        internal object[] _memberData = null;
-        internal ISerializationSurrogate _serializationSurrogate = null;
+        internal object?[]? _memberData = null;
+        internal ISerializationSurrogate? _serializationSurrogate = null;
         internal StreamingContext _context;
-        internal SerObjectInfoInit _serObjectInfoInit = null;
+        internal SerObjectInfoInit? _serObjectInfoInit = null;
 
         // Writing and Parsing information
         internal long _objectId;
         internal long _assemId;
 
         // Binder information
-        private string _binderTypeName;
-        private string _binderAssemblyString;
+        private string? _binderTypeName;
+        private string? _binderAssemblyString;
 
         internal WriteObjectInfo() { }
 
         internal void ObjectEnd()
         {
+            Debug.Assert(_serObjectInfoInit != null);
             PutObjectInfo(_serObjectInfoInit, this);
         }
 
@@ -52,7 +54,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _isNamed = false;
             _isArray = false;
             _si = null;
-            _cache = null;
+            _cache = null!;
             _memberData = null;
 
             // Writing and Parsing information
@@ -64,7 +66,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _binderAssemblyString = null;
         }
 
-        internal static WriteObjectInfo Serialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
+        internal static WriteObjectInfo Serialize(object obj, ISurrogateSelector? surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder? binder)
         {
             WriteObjectInfo woi = GetObjectInfo(serObjectInfoInit);
             woi.InitSerialize(obj, surrogateSelector, context, serObjectInfoInit, converter, objectWriter, binder);
@@ -72,7 +74,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Write constructor
-        internal void InitSerialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
+        internal void InitSerialize(object obj, ISurrogateSelector? surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder? binder)
         {
             _context = context;
             _obj = obj;
@@ -117,7 +119,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
         }
 
-        internal static WriteObjectInfo Serialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder)
+        internal static WriteObjectInfo Serialize(Type objectType, ISurrogateSelector? surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder? binder)
         {
             WriteObjectInfo woi = GetObjectInfo(serObjectInfoInit);
             woi.InitSerialize(objectType, surrogateSelector, context, serObjectInfoInit, converter, binder);
@@ -125,7 +127,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Write Constructor used for array types or null members
-        internal void InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder)
+        internal void InitSerialize(Type objectType, ISurrogateSelector? surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder? binder)
         {
             _objectType = objectType;
             _context = context;
@@ -139,10 +141,9 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             InvokeSerializationBinder(binder);
 
-            ISurrogateSelector surrogateSelectorTemp = null;
             if (surrogateSelector != null)
             {
-                _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp);
+                _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out ISurrogateSelector surrogateSelectorTemp);
             }
 
             if (_serializationSurrogate != null)
@@ -169,8 +170,9 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private void InitSiWrite()
         {
-            SerializationInfoEnumerator siEnum = null;
+            SerializationInfoEnumerator? siEnum = null;
             _isSi = true;
+            Debug.Assert(_si != null);
             siEnum = _si.GetEnumerator();
             int infoLength = 0;
 
@@ -180,7 +182,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             // For ISerializable cache cannot be saved because each object instance can have different values
             // BinaryWriter only puts the map on the wire if the ISerializable map cannot be reused.
-            TypeInformation typeInformation = null;
+            TypeInformation? typeInformation = null;
             string fullTypeName = _si.FullTypeName;
             string assemblyString = _si.AssemblyName;
             bool hasTypeForwardedFrom = false;
@@ -219,14 +221,15 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _isNamed = true;
         }
 
-        private static void CheckTypeForwardedFrom(SerObjectInfoCache cache, Type objectType, string binderAssemblyString)
+        private static void CheckTypeForwardedFrom(SerObjectInfoCache? cache, Type objectType, string? binderAssemblyString)
         {
             // nop
         }
 
         private void InitNoMembers()
         {
-            if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache))
+            Debug.Assert(_serObjectInfoInit != null && _objectType != null);
+            if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache!))
             {
                 _cache = new SerObjectInfoCache(_objectType);
                 _serObjectInfoInit._seenBeforeTable.Add(_objectType, _cache);
@@ -235,7 +238,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private void InitMemberInfo()
         {
-            if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache))
+            Debug.Assert(_serObjectInfoInit != null && _objectType != null);
+            if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache!))
             {
                 _cache = new SerObjectInfoCache(_objectType);
 
@@ -255,7 +259,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             if (_obj != null)
             {
-                _memberData = FormatterServices.GetObjectData(_obj, _cache._memberInfos);
+                _memberData = FormatterServices.GetObjectData(_obj, _cache._memberInfos!);
             }
 
             _isNamed = true;
@@ -265,10 +269,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         internal string GetAssemblyString() => _binderAssemblyString ?? _cache._assemblyString;
 
-        private void InvokeSerializationBinder(SerializationBinder binder) =>
-            binder?.BindToName(_objectType, out _binderAssemblyString, out _binderTypeName);
+        private void InvokeSerializationBinder(SerializationBinder? binder) =>
+            binder?.BindToName(_objectType!, out _binderAssemblyString, out _binderTypeName);
 
-        internal void GetMemberInfo(out string[] outMemberNames, out Type[] outMemberTypes, out object[] outMemberData)
+        internal void GetMemberInfo(out string[]? outMemberNames, out Type[]? outMemberTypes, out object?[]? outMemberData)
         {
             outMemberNames = _cache._memberNames;
             outMemberTypes = _cache._memberTypes;
@@ -286,7 +290,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             if (!serObjectInfoInit._oiPool.IsEmpty())
             {
-                objectInfo = (WriteObjectInfo)serObjectInfoInit._oiPool.Pop();
+                objectInfo = (WriteObjectInfo)serObjectInfoInit._oiPool.Pop()!;
                 objectInfo.InternalInit();
             }
             else
@@ -307,9 +311,9 @@ namespace System.Runtime.Serialization.Formatters.Binary
         internal int _objectInfoId;
         internal static int _readObjectInfoCounter;
 
-        internal Type _objectType;
+        internal Type? _objectType = null;
 
-        internal ObjectManager _objectManager;
+        internal ObjectManager? _objectManager;
 
         internal int _count;
 
@@ -317,20 +321,20 @@ namespace System.Runtime.Serialization.Formatters.Binary
         internal bool _isTyped = false;
         internal bool _isSimpleAssembly = false;
 
-        internal SerObjectInfoCache _cache;
+        internal SerObjectInfoCache? _cache;
 
-        internal string[] _wireMemberNames;
-        internal Type[] _wireMemberTypes;
+        internal string[]? _wireMemberNames;
+        internal Type[]? _wireMemberTypes;
 
         private int _lastPosition = 0;
 
-        internal ISerializationSurrogate _serializationSurrogate = null;
+        internal ISerializationSurrogate? _serializationSurrogate = null;
         internal StreamingContext _context;
 
         // Si Read
-        internal List<Type> _memberTypesList;
-        internal SerObjectInfoInit _serObjectInfoInit = null;
-        internal IFormatterConverter _formatterConverter;
+        internal List<Type>? _memberTypesList;
+        internal SerObjectInfoInit? _serObjectInfoInit = null;
+        internal IFormatterConverter? _formatterConverter = null;
 
         internal ReadObjectInfo() { }
 
@@ -341,14 +345,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _lastPosition = 0;
         }
 
-        internal static ReadObjectInfo Create(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
+        internal static ReadObjectInfo Create(Type objectType, ISurrogateSelector? surrogateSelector, StreamingContext context, ObjectManager? objectManager, SerObjectInfoInit? serObjectInfoInit, IFormatterConverter? converter, bool bSimpleAssembly)
         {
             ReadObjectInfo roi = GetObjectInfo(serObjectInfoInit);
             roi.Init(objectType, surrogateSelector, context, objectManager, serObjectInfoInit, converter, bSimpleAssembly);
             return roi;
         }
 
-        internal void Init(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
+        internal void Init(Type objectType, ISurrogateSelector? surrogateSelector, StreamingContext context, ObjectManager? objectManager, SerObjectInfoInit? serObjectInfoInit, IFormatterConverter? converter, bool bSimpleAssembly)
         {
             _objectType = objectType;
             _objectManager = objectManager;
@@ -360,14 +364,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
             InitReadConstructor(objectType, surrogateSelector, context);
         }
 
-        internal static ReadObjectInfo Create(Type objectType, string[] memberNames, Type[] memberTypes, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
+        internal static ReadObjectInfo Create(Type? objectType, string[] memberNames, Type[]? memberTypes, ISurrogateSelector? surrogateSelector, StreamingContext context, ObjectManager? objectManager, SerObjectInfoInit? serObjectInfoInit, IFormatterConverter? converter, bool bSimpleAssembly)
         {
             ReadObjectInfo roi = GetObjectInfo(serObjectInfoInit);
             roi.Init(objectType, memberNames, memberTypes, surrogateSelector, context, objectManager, serObjectInfoInit, converter, bSimpleAssembly);
             return roi;
         }
 
-        internal void Init(Type objectType, string[] memberNames, Type[] memberTypes, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
+        internal void Init(Type? objectType, string[] memberNames, Type[]? memberTypes, ISurrogateSelector? surrogateSelector, StreamingContext context, ObjectManager? objectManager, SerObjectInfoInit? serObjectInfoInit, IFormatterConverter? converter, bool bSimpleAssembly)
         {
             _objectType = objectType;
             _objectManager = objectManager;
@@ -387,7 +391,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
         }
 
-        private void InitReadConstructor(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context)
+        private void InitReadConstructor(Type objectType, ISurrogateSelector? surrogateSelector, StreamingContext context)
         {
             if (objectType.IsArray)
             {
@@ -395,7 +399,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 return;
             }
 
-            ISurrogateSelector surrogateSelectorTemp = null;
+            ISurrogateSelector? surrogateSelectorTemp = null;
             if (surrogateSelector != null)
             {
                 _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp);
@@ -430,13 +434,13 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private void InitNoMembers()
         {
-            _cache = new SerObjectInfoCache(_objectType);
+            _cache = new SerObjectInfoCache(_objectType!);
         }
 
         private void InitMemberInfo()
         {
-            _cache = new SerObjectInfoCache(_objectType);
-            _cache._memberInfos = FormatterServices.GetSerializableMembers(_objectType, _context);
+            _cache = new SerObjectInfoCache(_objectType!);
+            _cache._memberInfos = FormatterServices.GetSerializableMembers(_objectType!, _context);
             _count = _cache._memberInfos.Length;
             _cache._memberNames = new string[_count];
             _cache._memberTypes = new Type[_count];
@@ -452,7 +456,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Get the memberInfo for a memberName
-        internal MemberInfo GetMemberInfo(string name)
+        internal MemberInfo? GetMemberInfo(string? name)
         {
             if (_cache == null)
             {
@@ -474,7 +478,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Get the ObjectType for a memberName
-        internal Type GetType(string name)
+        internal Type? GetType(string name)
         {
             int position = Position(name);
             if (position == -1)
@@ -482,7 +486,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 return null;
             }
 
-            Type type = _isTyped ? _cache._memberTypes[position] : _memberTypesList[position];
+            Type type = _isTyped ? _cache!._memberTypes![position] : _memberTypesList![position];
             if (type == null)
             {
                 throw new SerializationException(SR.Format(SR.Serialization_ISerializableTypes, _objectType + " " + name));
@@ -492,10 +496,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Adds the value for a memberName
-        internal void AddValue(string name, object value, ref SerializationInfo si, ref object[] memberData)
+        internal void AddValue(string name, object? value, ref SerializationInfo? si, ref object?[]? memberData)
         {
             if (_isSi)
             {
+                Debug.Assert(si != null);
                 si.AddValue(name, value);
             }
             else
@@ -504,24 +509,27 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 int position = Position(name);
                 if (position != -1)
                 {
+                    Debug.Assert(memberData != null);
                     memberData[position] = value;
                 }
             }
         }
 
-        internal void InitDataStore(ref SerializationInfo si, ref object[] memberData)
+        internal void InitDataStore(ref SerializationInfo? si, ref object?[]? memberData)
         {
             if (_isSi)
             {
                 if (si == null)
                 {
-                    si = new SerializationInfo(_objectType, _formatterConverter);
+                    Debug.Assert(_objectType != null);
+                    si = new SerializationInfo(_objectType, _formatterConverter!);
                 }
             }
             else
             {
                 if (memberData == null && _cache != null)
                 {
+                    Debug.Assert(_cache._memberNames != null);
                     memberData = new object[_cache._memberNames.Length];
                 }
             }
@@ -549,28 +557,31 @@ namespace System.Runtime.Serialization.Formatters.Binary
                         throw new SerializationException(SR.Serialization_CorruptedStream);
                     }
 
+                    Debug.Assert(_cache != null && _cache._memberInfos != null);
                     _objectManager.RecordFixup(objectId, _cache._memberInfos[position], idRef);
                 }
             }
         }
 
         // Fills in the values for an object
-        internal void PopulateObjectMembers(object obj, object[] memberData)
+        internal void PopulateObjectMembers(object obj, object?[]? memberData)
         {
             if (!_isSi && memberData != null)
             {
+                Debug.Assert(_cache != null && _cache._memberInfos != null);
                 FormatterServices.PopulateObjectMembers(obj, _cache._memberInfos, memberData);
             }
         }
 
         // Specifies the position in the memberNames array of this name
-        private int Position(string name)
+        private int Position(string? name)
         {
             if (_cache == null)
             {
                 return -1;
             }
 
+            Debug.Assert(_cache._memberNames != null);
             if (_cache._memberNames.Length > 0 && _cache._memberNames[_lastPosition].Equals(name))
             {
                 return _lastPosition;
@@ -597,7 +608,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Return the member Types in order of memberNames
-        internal Type[] GetMemberTypes(string[] inMemberNames, Type objectType)
+        internal Type[]? GetMemberTypes(string[] inMemberNames, Type? objectType)
         {
             if (_isSi)
             {
@@ -609,6 +620,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 return null;
             }
 
+            Debug.Assert(_cache._memberInfos != null);
             if (_cache._memberTypes == null)
             {
                 _cache._memberTypes = new Type[_count];
@@ -652,6 +664,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                         if (!_isSimpleAssembly &&
                             _cache._memberInfos[i].GetCustomAttribute(typeof(OptionalFieldAttribute), inherit: false) == null)
                         {
+                            Debug.Assert(_cache._memberNames != null);
                             throw new SerializationException(SR.Format(SR.Serialization_MissingMember, _cache._memberNames[i], objectType, typeof(OptionalFieldAttribute).FullName));
                         }
                     }
@@ -673,7 +686,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
 
-        private static ReadObjectInfo GetObjectInfo(SerObjectInfoInit serObjectInfoInit)
+        private static ReadObjectInfo GetObjectInfo(SerObjectInfoInit? serObjectInfoInit)
         {
             ReadObjectInfo roi = new ReadObjectInfo();
             roi._objectInfoId = Interlocked.Increment(ref _readObjectInfoCounter);
@@ -694,9 +707,9 @@ namespace System.Runtime.Serialization.Formatters.Binary
         internal readonly string _assemblyString;
         internal readonly bool _hasTypeForwardedFrom;
 
-        internal MemberInfo[] _memberInfos;
-        internal string[] _memberNames;
-        internal Type[] _memberTypes;
+        internal MemberInfo[]? _memberInfos;
+        internal string[]? _memberNames;
+        internal Type[]? _memberTypes;
 
         internal SerObjectInfoCache(string typeName, string assemblyName, bool hasTypeForwardedFrom)
         {
index ce291c4..b775b98 100644 (file)
@@ -6,6 +6,7 @@ using System.Globalization;
 using System.IO;
 using System.Reflection;
 using System.Diagnostics;
+using System.Collections;
 
 namespace System.Runtime.Serialization.Formatters.Binary
 {
@@ -13,27 +14,27 @@ namespace System.Runtime.Serialization.Formatters.Binary
     {
         // System.Serializer information
         internal Stream _stream;
-        internal ISurrogateSelector _surrogates;
+        internal ISurrogateSelector? _surrogates;
         internal StreamingContext _context;
-        internal ObjectManager _objectManager;
+        internal ObjectManager? _objectManager;
         internal InternalFE _formatterEnums;
-        internal SerializationBinder _binder;
+        internal SerializationBinder? _binder;
 
         // Top object and headers
         internal long _topId;
         internal bool _isSimpleAssembly = false;
-        internal object _topObject;
-        internal SerObjectInfoInit _serObjectInfoInit;
-        internal IFormatterConverter _formatterConverter;
+        internal object? _topObject;
+        internal SerObjectInfoInit? _serObjectInfoInit;
+        internal IFormatterConverter? _formatterConverter;
 
         // Stack of Object ParseRecords
-        internal SerStack _stack;
+        internal SerStack? _stack;
 
         // ValueType Fixup Stack
-        private SerStack _valueFixupStack;
+        private SerStack? _valueFixupStack;
 
         // Cross AppDomain
-        internal object[] _crossAppDomainArray; //Set by the BinaryFormatter
+        internal object[]? _crossAppDomainArray; //Set by the BinaryFormatter
 
         //MethodCall and MethodReturn are handled special for perf reasons
         private bool _fullDeserialization;
@@ -44,11 +45,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // a single counter, only value types have a negative value. Need a way to handle older formats.
         private const int ThresholdForValueTypeIds = int.MaxValue;
         private bool _oldFormatDetected = false;
-        private IntSizedArray _valTypeObjectIdTable;
+        private IntSizedArray? _valTypeObjectIdTable;
 
         private readonly NameCache _typeCache = new NameCache();
 
-        internal object TopObject
+        internal object? TopObject
         {
             get { return _topObject; }
             set
@@ -61,7 +62,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
         }
 
-        internal ObjectReader(Stream stream, ISurrogateSelector selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder binder)
+        internal ObjectReader(Stream stream, ISurrogateSelector? selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder? binder)
         {
             if (stream == null)
             {
@@ -101,7 +102,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
                 if (_fullDeserialization)
                 {
-                    _objectManager.DoFixups();
+                    _objectManager!.DoFixups();
                 }
 
                 if (TopObject == null)
@@ -113,6 +114,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 //So refresh it using topID.
                 if (HasSurrogate(TopObject.GetType()) && _topId != 0)//Not yet resolved
                 {
+                    Debug.Assert(_objectManager != null);
                     TopObject = _objectManager.GetObject(_topId);
                 }
 
@@ -123,10 +125,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
                 if (_fullDeserialization)
                 {
-                    _objectManager.RaiseDeserializationEvent(); // This will raise both IDeserialization and [OnDeserialized] events
+                    _objectManager!.RaiseDeserializationEvent(); // This will raise both IDeserialization and [OnDeserialized] events
                 }
 
-                return TopObject;
+                return TopObject!;
             }
         }
         private bool HasSurrogate(Type t)
@@ -156,6 +158,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         internal object CrossAppDomainArray(int index)
         {
+            Debug.Assert(_crossAppDomainArray != null);
             Debug.Assert(index < _crossAppDomainArray.Length, "[System.Runtime.Serialization.Formatters.BinaryObjectReader index out of range for CrossAppDomainArray]");
             return _crossAppDomainArray[index];
         }
@@ -165,7 +168,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             return ReadObjectInfo.Create(objectType, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly);
         }
 
-        internal ReadObjectInfo CreateReadObjectInfo(Type objectType, string[] memberNames, Type[] memberTypes)
+        internal ReadObjectInfo CreateReadObjectInfo(Type? objectType, string[] memberNames, Type[]? memberTypes)
         {
             return ReadObjectInfo.Create(objectType, memberNames, memberTypes, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly);
         }
@@ -210,10 +213,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Parse the SerializedStreamHeader element. This is the first element in the stream if present
-        private void ParseSerializedStreamHeader(ParseRecord pr) => _stack.Push(pr);
+        private void ParseSerializedStreamHeader(ParseRecord pr) => _stack!.Push(pr);
 
         // Parse the SerializedStreamHeader end element. This is the last element in the stream if present
-        private void ParseSerializedStreamHeaderEnd(ParseRecord pr) => _stack.Pop();
+        private void ParseSerializedStreamHeaderEnd(ParseRecord pr) => _stack!.Pop();
 
         // New object encountered in stream
         private void ParseObject(ParseRecord pr)
@@ -230,7 +233,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             if (pr._parseTypeEnum == InternalParseTypeE.Object)
             {
-                _stack.Push(pr); // Nested objects member names are already on stack
+                _stack!.Push(pr); // Nested objects member names are already on stack
             }
 
             if (pr._objectTypeEnum == InternalObjectTypeE.Array)
@@ -260,8 +263,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     }
                     else
                     {
-                        _stack.Pop();
-                        RegisterObject(pr._newObj, pr, (ParseRecord)_stack.Peek());
+                        _stack!.Pop();
+                        RegisterObject(pr._newObj, pr, (ParseRecord?)_stack.Peek());
                         return;
                     }
                 }
@@ -276,6 +279,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 CheckSerializable(pr._dtType);
                 pr._newObj = FormatterServices.GetUninitializedObject(pr._dtType);
 
+                Debug.Assert(_objectManager != null);
                 // Run the OnDeserializing methods
                 _objectManager.RaiseOnDeserializingEvent(pr._newObj);
             }
@@ -299,7 +303,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // End of object encountered in stream
         private void ParseObjectEnd(ParseRecord pr)
         {
-            ParseRecord objectPr = (ParseRecord)_stack.Peek() ?? pr;
+            Debug.Assert(_stack != null);
+            ParseRecord objectPr = (ParseRecord?)_stack.Peek() ?? pr;
 
             if (objectPr._objectPositionEnum == InternalObjectPositionE.Top)
             {
@@ -312,7 +317,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
 
             _stack.Pop();
-            ParseRecord parentPr = (ParseRecord)_stack.Peek();
+            ParseRecord? parentPr = (ParseRecord?)_stack.Peek();
 
             if (objectPr._newObj == null)
             {
@@ -330,6 +335,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 return;
             }
 
+            Debug.Assert(objectPr._objectInfo != null);
             objectPr._objectInfo.PopulateObjectMembers(objectPr._newObj, objectPr._memberData);
 
             // Registration is after object is populated
@@ -340,7 +346,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             if (objectPr._isValueTypeFixup)
             {
-                ValueFixup fixup = (ValueFixup)ValueFixupStack.Pop(); //Value fixup
+                ValueFixup? fixup = (ValueFixup?)ValueFixupStack.Pop(); //Value fixup
+                Debug.Assert(fixup != null && parentPr != null);
                 fixup.Fixup(objectPr, parentPr);  // Value fixup
             }
 
@@ -357,8 +364,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
         {
             long genId = pr._objectId;
 
+            Debug.Assert(_stack != null);
             if (pr._arrayTypeEnum == InternalArrayTypeE.Base64)
             {
+                Debug.Assert(pr._value != null);
                 // ByteArray
                 pr._newObj = pr._value.Length > 0 ?
                     Convert.FromBase64String(pr._value) :
@@ -373,7 +382,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     TopObject = pr._newObj;
                 }
 
-                ParseRecord parentPr = (ParseRecord)_stack.Peek();
+                ParseRecord? parentPr = (ParseRecord?)_stack.Peek();
 
                 // Base64 can be registered at this point because it is populated
                 RegisterObject(pr._newObj, pr, parentPr);
@@ -386,13 +395,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     TopObject = pr._newObj;
                 }
 
-                ParseRecord parentPr = (ParseRecord)_stack.Peek();
+                ParseRecord? parentPr = (ParseRecord?)_stack.Peek();
 
                 // Primitive typed array can be registered at this point because it is populated
                 RegisterObject(pr._newObj, pr, parentPr);
             }
             else if ((pr._arrayTypeEnum == InternalArrayTypeE.Jagged) || (pr._arrayTypeEnum == InternalArrayTypeE.Single))
             {
+                Debug.Assert(pr._lengthA != null);
                 // Multidimensional jagged array or single array
                 bool couldBeValueType = true;
                 if ((pr._lowerBoundA == null) || (pr._lowerBoundA[0] == 0))
@@ -428,13 +438,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 {
                     if (!pr._isLowerBound && (Converter.IsWriteAsByteArray(pr._arrayElementTypeCode)))
                     {
+                        Debug.Assert(pr._newObj != null);
                         pr._primitiveArray = new PrimitiveArray(pr._arrayElementTypeCode, (Array)pr._newObj);
                     }
                     else if (couldBeValueType && pr._arrayElementType != null)
                     {
                         if (!pr._arrayElementType.IsValueType && !pr._isLowerBound)
                         {
-                            pr._objectA = (object[])pr._newObj;
+                            pr._objectA = (object[]?)pr._newObj;
                         }
                     }
                 }
@@ -457,8 +468,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     }
                 }
 
+                Debug.Assert(pr._lengthA != null);
                 if (pr._arrayElementType != null)
                 {
+                    Debug.Assert(pr._lowerBoundA != null);
                     pr._newObj = !pr._isLowerBound ?
                         Array.CreateInstance(pr._arrayElementType, pr._lengthA) :
                         Array.CreateInstance(pr._arrayElementType, pr._lengthA, pr._lowerBoundA);
@@ -483,6 +496,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // Builds a map for each item in an incoming rectangle array. The map specifies where the item is placed in the output Array Object
         private void NextRectangleMap(ParseRecord pr)
         {
+            Debug.Assert(pr._rectangularMap != null && pr._lengthA != null && pr._indexMap != null);
             // For each invocation, calculate the next rectangular array position
             // example
             // indexMap 0 [0,0,0]
@@ -515,8 +529,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // Array object item encountered in stream
         private void ParseArrayMember(ParseRecord pr)
         {
-            ParseRecord objectPr = (ParseRecord)_stack.Peek();
+            Debug.Assert(_stack != null);
+            ParseRecord? objectPr = (ParseRecord?)_stack.Peek();
 
+            Debug.Assert(objectPr != null && objectPr._indexMap != null && objectPr._lowerBoundA != null);
             // Set up for inserting value into correct array position
             if (objectPr._arrayTypeEnum == InternalArrayTypeE.Rectangular)
             {
@@ -526,6 +542,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 }
                 if (objectPr._isLowerBound)
                 {
+                    Debug.Assert(objectPr._rectangularMap != null);
                     for (int i = 0; i < objectPr._rank; i++)
                     {
                         objectPr._indexMap[i] = objectPr._rectangularMap[i] + objectPr._lowerBoundA[i];
@@ -545,8 +562,9 @@ namespace System.Runtime.Serialization.Formatters.Binary
             {
                 // Object Reference
 
+                Debug.Assert(_objectManager != null);
                 // See if object has already been instantiated
-                object refObj = _objectManager.GetObject(pr._idRef);
+                object? refObj = _objectManager.GetObject(pr._idRef);
                 if (refObj == null)
                 {
                     // Object not instantiated
@@ -564,6 +582,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     }
                     else
                     {
+                        Debug.Assert(objectPr._newObj != null);
                         ((Array)objectPr._newObj).SetValue(refObj, objectPr._indexMap); // Object has been instantiated
                     }
                 }
@@ -581,6 +600,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
                 if (objectPr._arrayElementType != null)
                 {
+                    Debug.Assert(objectPr._newObj != null);
                     if ((objectPr._arrayElementType.IsValueType) && (pr._arrayElementTypeCode == InternalPrimitiveTypeE.Invalid))
                     {
                         pr._isValueTypeFixup = true; //Valuefixup
@@ -611,6 +631,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     }
                     else
                     {
+                        Debug.Assert(objectPr._newObj != null);
                         ((Array)objectPr._newObj).SetValue(pr._value, objectPr._indexMap);
                     }
                 }
@@ -622,7 +643,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                         throw new SerializationException(SR.Serialization_ArrayTypeObject);
                     }
 
-                    object var = null;
+                    object? var = null;
 
                     if (ReferenceEquals(pr._dtType, Converter.s_typeofString))
                     {
@@ -631,6 +652,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     }
                     else if (ReferenceEquals(pr._dtTypeCode, InternalPrimitiveTypeE.Invalid))
                     {
+                        Debug.Assert(pr._dtType != null);
                         CheckSerializable(pr._dtType);
                         // Not nested and invalid, so it is an empty object
                         var = FormatterServices.GetUninitializedObject(pr._dtType);
@@ -647,6 +669,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     }
                     else
                     {
+                        Debug.Assert(objectPr._newObj != null);
                         ((Array)objectPr._newObj).SetValue(var, objectPr._indexMap); // Primitive type
                     }
                 }
@@ -655,12 +678,13 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     // Primitive type
                     if (objectPr._primitiveArray != null)
                     {
+                        Debug.Assert(pr._value != null);
                         // Fast path for Soap primitive arrays. Binary was handled in the BinaryParser
                         objectPr._primitiveArray.SetValue(pr._value, objectPr._indexMap[0]);
                     }
                     else
                     {
-                        object var = pr._varValue != null ?
+                        object? var = pr._varValue != null ?
                             pr._varValue :
                             Converter.FromString(pr._value, objectPr._arrayElementTypeCode);
                         if (objectPr._objectA != null)
@@ -669,6 +693,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                         }
                         else
                         {
+                            Debug.Assert(objectPr._newObj != null);
                             ((Array)objectPr._newObj).SetValue(var, objectPr._indexMap); // Primitive type
                         }
                     }
@@ -698,8 +723,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // Object member encountered in stream
         private void ParseMember(ParseRecord pr)
         {
-            ParseRecord objectPr = (ParseRecord)_stack.Peek();
-            string objName = objectPr?._name;
+            Debug.Assert(_stack != null);
+            ParseRecord? objectPr = (ParseRecord?)_stack.Peek();
 
             switch (pr._memberTypeEnum)
             {
@@ -710,6 +735,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     break;
             }
 
+            Debug.Assert(objectPr!= null && objectPr._objectInfo != null && pr._name != null);
             //if ((pr.PRdtType == null) && !objectPr.PRobjectInfo.isSi)
             if (pr._dtType == null && objectPr._objectInfo._isTyped)
             {
@@ -743,8 +769,9 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
             else if (pr._memberValueEnum == InternalMemberValueE.Reference)
             {
+                Debug.Assert(_objectManager != null);
                 // See if object has already been instantiated
-                object refObj = _objectManager.GetObject(pr._idRef);
+                object? refObj = _objectManager.GetObject(pr._idRef);
                 if (refObj == null)
                 {
                     objectPr._objectInfo.AddValue(pr._name, null, ref objectPr._si, ref objectPr._memberData);
@@ -769,6 +796,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     // The member field was an object put the value is Inline either  bin.Base64 or invalid
                     if (pr._arrayTypeEnum == InternalArrayTypeE.Base64)
                     {
+                        Debug.Assert(pr._value != null);
                         objectPr._objectInfo.AddValue(pr._name, Convert.FromBase64String(pr._value), ref objectPr._si, ref objectPr._memberData);
                     }
                     else if (ReferenceEquals(pr._dtType, Converter.s_typeofObject))
@@ -794,7 +822,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 }
                 else
                 {
-                    object var = pr._varValue != null ?
+                    object? var = pr._varValue != null ?
                         pr._varValue :
                         Converter.FromString(pr._value, pr._dtTypeCode);
                     objectPr._objectInfo.AddValue(pr._name, var, ref objectPr._si, ref objectPr._memberData);
@@ -821,7 +849,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     }
                     break;
                 default:
-                    ParseError(pr, (ParseRecord)_stack.Peek());
+                    Debug.Assert(_stack != null);
+                    ParseError(pr, (ParseRecord)_stack.Peek()!);
                     break;
             }
         }
@@ -838,21 +867,21 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
         }
 
-        private void RegisterObject(object obj, ParseRecord pr, ParseRecord objectPr)
+        private void RegisterObject(object obj, ParseRecord pr, ParseRecord? objectPr)
         {
             RegisterObject(obj, pr, objectPr, false);
         }
 
-        private void RegisterObject(object obj, ParseRecord pr, ParseRecord objectPr, bool bIsString)
+        private void RegisterObject(object? obj, ParseRecord pr, ParseRecord? objectPr, bool bIsString)
         {
             if (!pr._isRegistered)
             {
                 pr._isRegistered = true;
 
-                SerializationInfo si = null;
+                SerializationInfo? si = null;
                 long parentId = 0;
-                MemberInfo memberInfo = null;
-                int[] indexMap = null;
+                MemberInfo? memberInfo = null;
+                int[]? indexMap = null;
 
                 if (objectPr != null)
                 {
@@ -871,12 +900,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 // SerializationInfo is always needed for ISerialization
                 si = pr._si;
 
+                Debug.Assert(_objectManager != null);
                 if (bIsString)
                 {
-                    _objectManager.RegisterString((string)obj, pr._objectId, si, parentId, memberInfo);
+                    _objectManager.RegisterString((string?)obj, pr._objectId, si, parentId, memberInfo);
                 }
                 else
                 {
+                    Debug.Assert(obj != null);
                     _objectManager.RegisterObject(obj, pr._objectId, si, parentId, memberInfo, indexMap);
                 }
             }
@@ -916,9 +947,9 @@ namespace System.Runtime.Serialization.Formatters.Binary
             return -1 * objectId;
         }
 
-        internal Type Bind(string assemblyString, string typeString)
+        internal Type? Bind(string assemblyString, string typeString)
         {
-            Type type = null;
+            Type? type = null;
             if (_binder != null)
             {
                 type = _binder.BindToType(assemblyString, typeString);
@@ -932,15 +963,15 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         internal sealed class TypeNAssembly
         {
-            public Type Type;
-            public string AssemblyName;
+            public Type? Type;
+            public string? AssemblyName;
         }
 
-        internal Type FastBindToType(string assemblyName, string typeName)
+        internal Type? FastBindToType(string? assemblyName, string typeName)
         {
-            Type type = null;
+            Type? type = null;
 
-            TypeNAssembly entry = (TypeNAssembly)_typeCache.GetCachedValue(typeName);
+            TypeNAssembly? entry = (TypeNAssembly?)_typeCache.GetCachedValue(typeName);
 
             if (entry == null || entry.AssemblyName != assemblyName)
             {
@@ -950,8 +981,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     return null;
                 }
 
-                Assembly assm = null;
-                AssemblyName assmName = null;
+                Assembly? assm = null;
+                AssemblyName? assmName = null;
 
                 try
                 {
@@ -1005,7 +1036,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             return entry.Type;
         }
 
-        private static Assembly ResolveSimpleAssemblyName(AssemblyName assemblyName)
+        private static Assembly? ResolveSimpleAssemblyName(AssemblyName assemblyName)
         {
             try
             {
@@ -1017,7 +1048,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             {
                 try
                 {
-                    return Assembly.Load(assemblyName.Name);
+                    return Assembly.Load(assemblyName.Name!);
                 }
                 catch { }
             }
@@ -1025,7 +1056,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             return null;
         }
 
-        private static void GetSimplyNamedTypeFromAssembly(Assembly assm, string typeName, ref Type type)
+        private static void GetSimplyNamedTypeFromAssembly(Assembly assm, string typeName, ref Type? type)
         {
             // Catching any exceptions that could be thrown from a failure on assembly load
             // This is necessary, for example, if there are generic parameters that are qualified with a version of the assembly that predates the one available
@@ -1044,13 +1075,13 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
         }
 
-        private string _previousAssemblyString;
-        private string _previousName;
-        private Type _previousType;
+        private string? _previousAssemblyString;
+        private string? _previousName;
+        private Type? _previousType;
 
-        internal Type GetType(BinaryAssemblyInfo assemblyInfo, string name)
+        internal Type? GetType(BinaryAssemblyInfo assemblyInfo, string name)
         {
-            Type objectType = null;
+            Type? objectType;
 
             if (((_previousName != null) && (_previousName.Length == name.Length) && (_previousName.Equals(name))) &&
                 ((_previousAssemblyString != null) && (_previousAssemblyString.Length == assemblyInfo._assemblyString.Length) && (_previousAssemblyString.Equals(assemblyInfo._assemblyString))))
@@ -1101,7 +1132,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 _topLevelAssembly = topLevelAssembly;
             }
 
-            public Type ResolveType(Assembly assembly, string simpleTypeName, bool ignoreCase)
+            public Type? ResolveType(Assembly? assembly, string simpleTypeName, bool ignoreCase)
             {
                 if (assembly == null)
                 {
index ebcfc97..7e3d6ad 100644 (file)
@@ -7,11 +7,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
     internal sealed class BinaryObjectString : IStreamable
     {
         internal int _objectId;
-        internal string _value;
+        internal string? _value;
 
         internal BinaryObjectString() { }
 
-        internal void Set(int objectId, string value)
+        internal void Set(int objectId, string? value)
         {
             _objectId = objectId;
             _value = value;
@@ -21,7 +21,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         {
             output.WriteByte((byte)BinaryHeaderEnum.ObjectString);
             output.WriteInt32(_objectId);
-            output.WriteString(_value);
+            output.WriteString(_value!);
         }
 
         public void Read(BinaryParser input)
index c25e5e8..2f8cd19 100644 (file)
@@ -2,15 +2,17 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Diagnostics;
+
 namespace System.Runtime.Serialization.Formatters.Binary
 {
     internal sealed class BinaryObjectWithMap : IStreamable
     {
         internal BinaryHeaderEnum _binaryHeaderEnum;
         internal int _objectId;
-        internal string _name;
+        internal string? _name;
         internal int _numMembers;
-        internal string[] _memberNames;
+        internal string[]? _memberNames;
         internal int _assemId;
 
         internal BinaryObjectWithMap() { }
@@ -35,6 +37,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         public void Write(BinaryFormatterWriter output)
         {
+            Debug.Assert(_name != null && _memberNames != null);
             output.WriteByte((byte)_binaryHeaderEnum);
             output.WriteInt32(_objectId);
             output.WriteString(_name);
index 3057e15..26484cd 100644 (file)
@@ -2,18 +2,20 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Diagnostics;
+
 namespace System.Runtime.Serialization.Formatters.Binary
 {
     internal sealed class BinaryObjectWithMapTyped : IStreamable
     {
         internal BinaryHeaderEnum _binaryHeaderEnum;
         internal int _objectId;
-        internal string _name;
+        internal string? _name;
         internal int _numMembers;
-        internal string[] _memberNames;
-        internal BinaryTypeEnum[] _binaryTypeEnumA;
-        internal object[] _typeInformationA;
-        internal int[] _memberAssemIds;
+        internal string[]? _memberNames;
+        internal BinaryTypeEnum[]? _binaryTypeEnumA;
+        internal object?[]? _typeInformationA;
+        internal int[]? _memberAssemIds;
         internal int _assemId;
 
         internal BinaryObjectWithMapTyped() { }
@@ -23,7 +25,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _binaryHeaderEnum = binaryHeaderEnum;
         }
 
-        internal void Set(int objectId, string name, int numMembers, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object[] typeInformationA, int[] memberAssemIds, int assemId)
+        internal void Set(int objectId, string name, int numMembers, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object?[] typeInformationA, int[] memberAssemIds, int assemId)
         {
             _objectId = objectId;
             _assemId = assemId;
@@ -42,6 +44,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         public void Write(BinaryFormatterWriter output)
         {
+            Debug.Assert(_name != null && _memberNames != null && _binaryTypeEnumA != null && _typeInformationA != null && _memberAssemIds != null);
             output.WriteByte((byte)_binaryHeaderEnum);
             output.WriteInt32(_objectId);
             output.WriteString(_name);
index 70b23d5..5a99ef9 100644 (file)
@@ -4,40 +4,41 @@
 
 using System.Reflection;
 using System.Collections.Generic;
+using System.Diagnostics;
 
 namespace System.Runtime.Serialization.Formatters.Binary
 {
     internal sealed class ObjectWriter
     {
-        private Queue<object> _objectQueue;
-        private ObjectIDGenerator _idGenerator;
+        private Queue<object>? _objectQueue;
+        private ObjectIDGenerator? _idGenerator;
         private int _currentId;
 
-        private readonly ISurrogateSelector _surrogates;
+        private readonly ISurrogateSelector? _surrogates;
         private readonly StreamingContext _context;
-        private BinaryFormatterWriter _serWriter;
+        private BinaryFormatterWriter? _serWriter;
         private readonly SerializationObjectManager _objectManager;
 
         private long _topId;
-        private readonly string _topName = null;
+        private readonly string? _topName = null;
 
         private readonly InternalFE _formatterEnums;
-        private readonly SerializationBinder _binder;
+        private readonly SerializationBinder? _binder;
 
-        private SerObjectInfoInit _serObjectInfoInit;
+        private SerObjectInfoInit? _serObjectInfoInit;
 
-        private IFormatterConverter _formatterConverter;
+        private IFormatterConverter? _formatterConverter;
 
-        internal object[] _crossAppDomainArray = null;
-        internal List<object> _internalCrossAppDomainArray = null;
+        internal object[]? _crossAppDomainArray = null;
+        internal List<object>? _internalCrossAppDomainArray = null;
 
-        private object _previousObj = null;
+        private object? _previousObj = null;
         private long _previousId = 0;
 
-        private Type _previousType = null;
+        private Type? _previousType = null;
         private InternalPrimitiveTypeE _previousCode = InternalPrimitiveTypeE.Invalid;
 
-        internal ObjectWriter(ISurrogateSelector selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder binder)
+        internal ObjectWriter(ISurrogateSelector? selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder? binder)
         {
             _currentId = 1;
             _surrogates = selector;
@@ -62,8 +63,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             serWriter.WriteBegin();
             long headerId = 0;
-            object obj;
-            long objectId;
+            object? obj;
             bool isNew;
 
             // allocations if methodCall or methodResponse and no graph
@@ -77,9 +77,9 @@ namespace System.Runtime.Serialization.Formatters.Binary
             WriteSerializedStreamHeader(_topId, headerId);
 
             _objectQueue.Enqueue(graph);
-            while ((obj = GetNext(out objectId)) != null)
+            while ((obj = GetNext(out long objectId)) != null)
             {
-                WriteObjectInfo objectInfo = null;
+                WriteObjectInfo? objectInfo = null;
 
                 // GetNext will return either an object or a WriteObjectInfo.
                 // A WriteObjectInfo is returned if this object was member of another object
@@ -112,16 +112,17 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // Writes a given object to the stream.
         private void Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)
         {
-            object obj = objectInfo._obj;
+            object? obj = objectInfo._obj;
             if (obj == null)
             {
                 throw new ArgumentNullException(nameof(objectInfo) + "." + nameof(objectInfo._obj));
             }
-            Type objType = objectInfo._objectType;
+            Type? objType = objectInfo._objectType;
             long objectId = objectInfo._objectId;
 
             if (ReferenceEquals(objType, Converter.s_typeofString))
             {
+                Debug.Assert(_serWriter != null);
                 // Top level String
                 memberNameInfo._objectId = objectId;
                 _serWriter.WriteObjectString((int)objectId, obj.ToString());
@@ -134,11 +135,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 }
                 else
                 {
-                    string[] memberNames;
-                    Type[] memberTypes;
-                    object[] memberData;
-
-                    objectInfo.GetMemberInfo(out memberNames, out memberTypes, out memberData);
+                    objectInfo.GetMemberInfo(out string[]? memberNames, out Type[]? memberTypes, out object?[]? memberData);
 
                     // Only Binary needs to transmit types for ISerializable because the binary formatter transmits the types in URT format.
                     // Soap transmits all types as strings, so it is up to the ISerializable object to convert the string back to its URT type
@@ -150,6 +147,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                         typeNameInfo._isParentTypeOnObject = true;
                     }
 
+                    Debug.Assert(memberNames != null && memberTypes != null && memberData != null);
                     var memberObjectInfos = new WriteObjectInfo[memberNames.Length];
 
                     // Get assembly information
@@ -162,17 +160,18 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     {
                         Type type =
                             memberTypes[i] != null ? memberTypes[i] :
-                            memberData[i] != null ? GetType(memberData[i]) :
+                            memberData[i] != null ? GetType(memberData[i]!) : // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644
                             Converter.s_typeofObject;
 
                         InternalPrimitiveTypeE code = ToCode(type);
                         if ((code == InternalPrimitiveTypeE.Invalid) &&
                             (!ReferenceEquals(type, Converter.s_typeofString)))
                         {
+                            Debug.Assert(_serObjectInfoInit != null && _formatterConverter != null);
                             if (memberData[i] != null)
                             {
                                 memberObjectInfos[i] = WriteObjectInfo.Serialize(
-                                    memberData[i],
+                                    memberData[i]!, // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644
                                     _surrogates,
                                     _context,
                                     _serObjectInfoInit,
@@ -201,16 +200,17 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         // Writes a given object to the stream.
         private void Write(WriteObjectInfo objectInfo,
-                           NameInfo memberNameInfo,
+                           NameInfo? memberNameInfo,
                            NameInfo typeNameInfo,
                            string[] memberNames,
                            Type[] memberTypes,
-                           object[] memberData,
+                           object?[] memberData,
                            WriteObjectInfo[] memberObjectInfos)
         {
             int numItems = memberNames.Length;
-            NameInfo topNameInfo = null;
+            NameInfo? topNameInfo = null;
 
+            Debug.Assert(_serWriter != null);
             if (memberNameInfo != null)
             {
                 memberNameInfo._objectId = objectInfo._objectId;
@@ -231,6 +231,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 }
             }
 
+            Debug.Assert(memberNameInfo != null);
             if (memberNameInfo._isParentTypeOnObject)
             {
                 memberNameInfo._transmitTypeOnObject = true;
@@ -254,8 +255,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
             else if ((objectInfo._objectId == _topId) && (_topName != null))
             {
-                _serWriter.WriteObjectEnd(topNameInfo, typeNameInfo);
-                PutNameInfo(topNameInfo);
+                _serWriter.WriteObjectEnd(topNameInfo!, typeNameInfo);
+                PutNameInfo(topNameInfo!);
             }
             else if (!ReferenceEquals(objectInfo._objectType, Converter.s_typeofString))
             {
@@ -268,8 +269,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
                                       NameInfo typeNameInfo,
                                       string memberName,
                                       Type memberType,
-                                      object memberData,
-                                      WriteObjectInfo memberObjectInfo)
+                                      object? memberData,
+                                      WriteObjectInfo? memberObjectInfo)
         {
             NameInfo newMemberNameInfo = MemberToNameInfo(memberName); // newMemberNameInfo contains the member type
 
@@ -280,7 +281,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             newMemberNameInfo._type = memberType;
 
             // newTypeNameInfo contains the data type
-            NameInfo newTypeNameInfo = null;
+            NameInfo newTypeNameInfo;
             if (memberObjectInfo == null)
             {
                 newTypeNameInfo = TypeToNameInfo(memberType);
@@ -300,12 +301,12 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // Writes the members of an object
         private void WriteMembers(NameInfo memberNameInfo,
                                   NameInfo memberTypeNameInfo,
-                                  object memberData,
+                                  object? memberData,
                                   WriteObjectInfo objectInfo,
                                   NameInfo typeNameInfo,
-                                  WriteObjectInfo memberObjectInfo)
+                                  WriteObjectInfo? memberObjectInfo)
         {
-            Type memberType = memberNameInfo._type;
+            Type? memberType = memberNameInfo._type;
             bool assignUniqueIdToValueType = false;
 
             // Types are transmitted for a member as follows:
@@ -313,7 +314,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             // The member object of type is ISerializable and
             //  Binary - Types always transmitted.
 
-            if (ReferenceEquals(memberType, Converter.s_typeofObject) || Nullable.GetUnderlyingType(memberType) != null)
+            if (ReferenceEquals(memberType, Converter.s_typeofObject) || Nullable.GetUnderlyingType(memberType!) != null)
             {
                 memberTypeNameInfo._transmitTypeOnMember = true;
                 memberNameInfo._transmitTypeOnMember = true;
@@ -331,8 +332,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 return;
             }
 
-            object outObj = memberData;
-            Type outType = null;
+            object outObj = memberData!;
+            Type? outType = null;
 
             // If member type does not equal data type, transmit type on object.
             if (memberTypeNameInfo._primitiveTypeEnum == InternalPrimitiveTypeE.Invalid)
@@ -348,7 +349,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             if (ReferenceEquals(memberType, Converter.s_typeofObject))
             {
                 assignUniqueIdToValueType = true;
-                memberType = GetType(memberData);
+                memberType = GetType(memberData!);
                 if (memberObjectInfo == null)
                 {
                     TypeToNameInfo(memberType, memberTypeNameInfo);
@@ -361,15 +362,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             if (memberObjectInfo != null && memberObjectInfo._isArray)
             {
-                // Array
-                long arrayId = 0;
-                if (outType == null)
-                {
-                    outType = GetType(outObj);
-                }
-
-                // outObj is an array. It can never be a value type..
-                arrayId = Schedule(outObj, false, null, memberObjectInfo);
+                // outObj is an array. It can never be a value type.
+                long arrayId = Schedule(outObj, false, null, memberObjectInfo);
                 if (arrayId > 0)
                 {
                     // Array as object
@@ -378,6 +372,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 }
                 else
                 {
+                    Debug.Assert(_serWriter != null);
                     // Nested Array
                     _serWriter.WriteMemberNested(memberNameInfo);
 
@@ -389,7 +384,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 return;
             }
 
-            if (!WriteKnownValueClass(memberNameInfo, memberTypeNameInfo, memberData))
+            if (!WriteKnownValueClass(memberNameInfo, memberTypeNameInfo, memberData!))
             {
                 if (outType == null)
                 {
@@ -399,6 +394,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 long memberObjectId = Schedule(outObj, assignUniqueIdToValueType, outType, memberObjectInfo);
                 if (memberObjectId < 0)
                 {
+                    Debug.Assert(memberObjectInfo != null);
                     // Nested object
                     memberObjectInfo._objectId = memberObjectId;
                     NameInfo newTypeNameInfo = TypeToNameInfo(memberObjectInfo);
@@ -417,7 +413,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Writes out an array
-        private void WriteArray(WriteObjectInfo objectInfo, NameInfo memberNameInfo, WriteObjectInfo memberObjectInfo)
+        private void WriteArray(WriteObjectInfo objectInfo, NameInfo? memberNameInfo, WriteObjectInfo? memberObjectInfo)
         {
             bool isAllocatedMemberNameInfo = false;
             if (memberNameInfo == null)
@@ -432,15 +428,16 @@ namespace System.Runtime.Serialization.Formatters.Binary
             memberNameInfo._objectId = objectInfo._objectId;
 
             // Get array type
-            Array array = (Array)objectInfo._obj;
+            Array array = (Array)objectInfo._obj!;
             //Type arrayType = array.GetType();
-            Type arrayType = objectInfo._objectType;
+            Type arrayType = objectInfo._objectType!;
 
             // Get type of array element
-            Type arrayElemType = arrayType.GetElementType();
-            WriteObjectInfo arrayElemObjectInfo = null;
+            Type arrayElemType = arrayType.GetElementType()!;
+            WriteObjectInfo? arrayElemObjectInfo = null;
             if (!arrayElemType.IsPrimitive)
             {
+                Debug.Assert(_serObjectInfoInit != null && _formatterConverter != null);
                 arrayElemObjectInfo = WriteObjectInfo.Serialize(arrayElemType, _surrogates, _context, _serObjectInfoInit, _formatterConverter, _binder);
                 arrayElemObjectInfo._assemId = GetAssemblyId(arrayElemObjectInfo);
             }
@@ -448,7 +445,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             NameInfo arrayElemTypeNameInfo = arrayElemObjectInfo == null ?
                 TypeToNameInfo(arrayElemType) :
                 TypeToNameInfo(arrayElemObjectInfo);
-            arrayElemTypeNameInfo._isArray = arrayElemTypeNameInfo._type.IsArray;
+            arrayElemTypeNameInfo._isArray = arrayElemTypeNameInfo._type!.IsArray;
 
             NameInfo arrayNameInfo = memberNameInfo;
             arrayNameInfo._objectId = objectId;
@@ -485,6 +482,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
             arrayElemTypeNameInfo._arrayEnum = arrayEnum;
 
+            Debug.Assert(_serWriter != null);
             // Byte array
             if ((ReferenceEquals(arrayElemType, Converter.s_typeofByte)) && (rank == 1) && (lowerBoundA[0] == 0))
             {
@@ -514,7 +512,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
                 if (!(Converter.IsWriteAsByteArray(arrayElemTypeNameInfo._primitiveTypeEnum) && (lowerBoundA[0] == 0)))
                 {
-                    object[] objectA = null;
+                    object[]? objectA = null;
                     if (!arrayElemType.IsValueType)
                     {
                         // Non-primitive type array
@@ -587,7 +585,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Writes out an array element
-        private void WriteArrayMember(WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, object data)
+        private void WriteArrayMember(WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, object? data)
         {
             arrayElemTypeNameInfo._isArrayItem = true;
 
@@ -596,8 +594,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 return;
             }
 
-            NameInfo actualTypeInfo = null;
-            Type dataType = null;
+            NameInfo? actualTypeInfo = null;
+            Type? dataType = null;
             bool isObjectOnMember = false;
 
             if (arrayElemTypeNameInfo._transmitTypeOnMember)
@@ -607,7 +605,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             if (!isObjectOnMember && !arrayElemTypeNameInfo.IsSealed)
             {
-                dataType = GetType(data);
+                dataType = GetType(data!);
                 if (!ReferenceEquals(arrayElemTypeNameInfo._type, dataType))
                 {
                     isObjectOnMember = true;
@@ -619,7 +617,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 // Object array, need type of member
                 if (dataType == null)
                 {
-                    dataType = GetType(data);
+                    dataType = GetType(data!);
                 }
                 actualTypeInfo = TypeToNameInfo(dataType);
                 actualTypeInfo._transmitTypeOnMember = true;
@@ -633,9 +631,9 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 actualTypeInfo._isArrayItem = true;
             }
 
-            if (!WriteKnownValueClass(arrayElemTypeNameInfo, actualTypeInfo, data))
+            if (!WriteKnownValueClass(arrayElemTypeNameInfo, actualTypeInfo, data!))
             {
-                object obj = data;
+                object obj = data!;
                 bool assignUniqueIdForValueTypes = false;
                 if (ReferenceEquals(arrayElemTypeNameInfo._type, Converter.s_typeofObject))
                 {
@@ -647,9 +645,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 actualTypeInfo._objectId = arrayId;
                 if (arrayId < 1)
                 {
+                    Debug.Assert(_serObjectInfoInit != null && _formatterConverter != null);
                     WriteObjectInfo newObjectInfo = WriteObjectInfo.Serialize(obj, _surrogates, _context, _serObjectInfoInit, _formatterConverter, this, _binder);
                     newObjectInfo._objectId = arrayId;
-                    newObjectInfo._assemId = !ReferenceEquals(arrayElemTypeNameInfo._type, Converter.s_typeofObject) && Nullable.GetUnderlyingType(arrayElemTypeNameInfo._type) == null ?
+                    newObjectInfo._assemId = !ReferenceEquals(arrayElemTypeNameInfo._type, Converter.s_typeofObject) && Nullable.GetUnderlyingType(arrayElemTypeNameInfo._type!) == null ?
                         actualTypeInfo._assemId :
                         GetAssemblyId(newObjectInfo);
                     NameInfo typeNameInfo = TypeToNameInfo(newObjectInfo);
@@ -660,6 +659,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 }
                 else
                 {
+                    Debug.Assert(_serWriter != null);
                     _serWriter.WriteItemObjectRef(arrayElemTypeNameInfo, (int)arrayId);
                 }
             }
@@ -670,10 +670,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Iterates over a Rectangle array, for each element of the array invokes WriteArrayMember
-        private void WriteRectangle(WriteObjectInfo objectInfo, int rank, int[] maxA, Array array, NameInfo arrayElemNameTypeInfo, int[] lowerBoundA)
+        private void WriteRectangle(WriteObjectInfo objectInfo, int rank, int[] maxA, Array array, NameInfo arrayElemNameTypeInfo, int[]? lowerBoundA)
         {
             int[] currentA = new int[rank];
-            int[] indexMap = null;
+            int[]? indexMap = null;
             bool isLowerBound = false;
             if (lowerBoundA != null)
             {
@@ -698,10 +698,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 {
                     for (int i = 0; i < rank; i++)
                     {
-                        indexMap[i] = currentA[i] + lowerBoundA[i];
+                        indexMap![i] = currentA[i] + lowerBoundA![i];
                     }
 
-                    WriteArrayMember(objectInfo, arrayElemNameTypeInfo, array.GetValue(indexMap));
+                    WriteArrayMember(objectInfo, arrayElemNameTypeInfo, array.GetValue(indexMap!));
                 }
                 else
                 {
@@ -734,12 +734,12 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // are returned in a FIFO order based on how they were passed
         // to Schedule.  The id of the object is put into the objID parameter
         // and the Object itself is returned from the function.
-        private object GetNext(out long objID)
+        private object? GetNext(out long objID)
         {
             bool isNew;
 
             //The Queue is empty here.  We'll throw if we try to dequeue the empty queue.
-            if (_objectQueue.Count == 0)
+            if (_objectQueue!.Count == 0)
             {
                 objID = 0;
                 return null;
@@ -748,8 +748,9 @@ namespace System.Runtime.Serialization.Formatters.Binary
             object obj = _objectQueue.Dequeue();
 
             // A WriteObjectInfo is queued if this object was a member of another object
-            object realObj = obj is WriteObjectInfo ? ((WriteObjectInfo)obj)._obj : obj;
-            objID = _idGenerator.HasId(realObj, out isNew);
+            object? realObj = obj is WriteObjectInfo ? ((WriteObjectInfo)obj)._obj : obj;
+            Debug.Assert(realObj != null);
+            objID = _idGenerator!.HasId(realObj, out isNew);
             if (isNew)
             {
                 throw new SerializationException(SR.Format(SR.Serialization_ObjNoID, realObj));
@@ -761,7 +762,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // If the type is a value type, we dont attempt to generate a unique id, unless its a boxed entity
         // (in which case, there might be 2 references to the same boxed obj. in a graph.)
         // "assignUniqueIdToValueType" is true, if the field type holding reference to "obj" is Object.
-        private long InternalGetId(object obj, bool assignUniqueIdToValueType, Type type, out bool isNew)
+        private long InternalGetId(object obj, bool assignUniqueIdToValueType, Type? type, out bool isNew)
         {
             if (obj == _previousObj)
             {
@@ -769,6 +770,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 isNew = false;
                 return _previousId;
             }
+            Debug.Assert(_idGenerator != null);
             _idGenerator._currentCount = _currentId;
             if (type != null && type.IsValueType)
             {
@@ -791,10 +793,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // We get an ID for obj and put it on the queue for later serialization
         // if this is a new object id.
 
-        private long Schedule(object obj, bool assignUniqueIdToValueType, Type type) =>
+        private long Schedule(object obj, bool assignUniqueIdToValueType, Type? type) =>
             Schedule(obj, assignUniqueIdToValueType, type, null);
 
-        private long Schedule(object obj, bool assignUniqueIdToValueType, Type type, WriteObjectInfo objectInfo)
+        private long Schedule(object obj, bool assignUniqueIdToValueType, Type? type, WriteObjectInfo? objectInfo)
         {
             long id = 0;
             if (obj != null)
@@ -803,6 +805,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 id = InternalGetId(obj, assignUniqueIdToValueType, type, out isNew);
                 if (isNew && id > 0)
                 {
+                    Debug.Assert(_objectQueue != null);
                     _objectQueue.Enqueue(objectInfo ?? obj);
                 }
             }
@@ -824,6 +827,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 }
                 else
                 {
+                    Debug.Assert(_serWriter != null);
                     if (typeNameInfo._isArray) // null if an array
                     {
                         _serWriter.WriteItem(memberNameInfo, typeNameInfo, data);
@@ -841,7 +845,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         // Writes an object reference to the stream.
         private void WriteObjectRef(NameInfo nameInfo, long objectId) =>
-            _serWriter.WriteMemberObjectRef(nameInfo, (int)objectId);
+            _serWriter!.WriteMemberObjectRef(nameInfo, (int)objectId);
 
         // Writes a string into the XML stream
         private void WriteString(NameInfo memberNameInfo, NameInfo typeNameInfo, object stringObject)
@@ -858,6 +862,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             if ((isFirstTime) || (stringId < 0))
             {
+                Debug.Assert(_serWriter != null);
                 _serWriter.WriteMemberString(memberNameInfo, typeNameInfo, (string)stringObject);
             }
             else
@@ -867,7 +872,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Writes a null member into the stream
-        private bool CheckForNull(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo, object data)
+        private bool CheckForNull(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo, object? data)
         {
             bool isNull = data == null;
 
@@ -879,6 +884,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                              objectInfo._isSi ||
                              (CheckTypeFormat(_formatterEnums._typeFormat, FormatterTypeStyle.TypesAlways))))
             {
+                Debug.Assert(_serWriter != null);
                 if (typeNameInfo._isArrayItem)
                 {
                     if (typeNameInfo._arrayEnum == InternalArrayTypeE.Single)
@@ -902,10 +908,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         // Writes the SerializedStreamHeader
         private void WriteSerializedStreamHeader(long topId, long headerId) =>
-            _serWriter.WriteSerializationHeader((int)topId, (int)headerId, 1, 0);
+            _serWriter!.WriteSerializationHeader((int)topId, (int)headerId, 1, 0);
 
         // Transforms a type to the serialized string form. URT Primitive types are converted to XMLData Types
-        private NameInfo TypeToNameInfo(Type type, WriteObjectInfo objectInfo, InternalPrimitiveTypeE code, NameInfo nameInfo)
+        private NameInfo TypeToNameInfo(Type? type, WriteObjectInfo? objectInfo, InternalPrimitiveTypeE code, NameInfo? nameInfo)
         {
             if (nameInfo == null)
             {
@@ -949,7 +955,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             return memberNameInfo;
         }
 
-        internal InternalPrimitiveTypeE ToCode(Type type)
+        internal InternalPrimitiveTypeE ToCode(Type? type)
         {
             if (ReferenceEquals(_previousType, type))
             {
@@ -967,7 +973,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
         }
 
-        private Dictionary<string, long> _assemblyToIdTable = null;
+        private Dictionary<string, long>? _assemblyToIdTable = null;
         private long GetAssemblyId(WriteObjectInfo objectInfo)
         {
             //use objectInfo to get assembly string with new criteria
@@ -1007,6 +1013,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     _assemblyToIdTable[assemblyString] = assemId;
                 }
 
+                Debug.Assert(_serWriter != null);
                 _serWriter.WriteAssembly(objectInfo._objectType, serializedAssemblyString, (int)assemId, isNew);
             }
             return assemId;
@@ -1018,11 +1025,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private NameInfo GetNameInfo()
         {
-            NameInfo nameInfo = null;
+            NameInfo nameInfo;
 
             if (!_niPool.IsEmpty())
             {
-                nameInfo = (NameInfo)_niPool.Pop();
+                nameInfo = (NameInfo)_niPool.Pop()!;
                 nameInfo.Init();
             }
             else
index 0869d2c..8a64314 100644 (file)
@@ -19,30 +19,30 @@ namespace System.Runtime.Serialization.Formatters.Binary
         internal Stream _input;
         internal long _topId;
         internal long _headerId;
-        internal SizedArray _objectMapIdTable;
-        internal SizedArray _assemIdToAssemblyTable;    // Used to hold assembly information
+        internal SizedArray? _objectMapIdTable;
+        internal SizedArray? _assemIdToAssemblyTable;    // Used to hold assembly information
         internal SerStack _stack = new SerStack("ObjectProgressStack");
 
         internal BinaryTypeEnum _expectedType = BinaryTypeEnum.ObjectUrt;
-        internal object _expectedTypeInformation;
-        internal ParseRecord _prs;
+        internal object? _expectedTypeInformation;
+        internal ParseRecord? _prs;
 
-        private BinaryAssemblyInfo _systemAssemblyInfo;
+        private BinaryAssemblyInfo? _systemAssemblyInfo;
         private readonly BinaryReader _dataReader;
-        private SerStack _opPool;
+        private SerStack? _opPool;
 
-        private BinaryObject _binaryObject;
-        private BinaryObjectWithMap _bowm;
-        private BinaryObjectWithMapTyped _bowmt;
+        private BinaryObject? _binaryObject;
+        private BinaryObjectWithMap? _bowm;
+        private BinaryObjectWithMapTyped? _bowmt;
 
-        internal BinaryObjectString _objectString;
-        internal BinaryCrossAppDomainString _crossAppDomainString;
-        internal MemberPrimitiveTyped _memberPrimitiveTyped;
-        private byte[] _byteBuffer;
-        internal MemberPrimitiveUnTyped memberPrimitiveUnTyped;
-        internal MemberReference _memberReference;
-        internal ObjectNull _objectNull;
-        internal static volatile MessageEnd _messageEnd;
+        internal BinaryObjectString? _objectString;
+        internal BinaryCrossAppDomainString? _crossAppDomainString;
+        internal MemberPrimitiveTyped? _memberPrimitiveTyped;
+        private byte[]? _byteBuffer;
+        internal MemberPrimitiveUnTyped? memberPrimitiveUnTyped;
+        internal MemberReference? _memberReference;
+        internal ObjectNull? _objectNull;
+        internal static volatile MessageEnd? _messageEnd;
 
         internal BinaryParser(Stream stream, ObjectReader objectReader)
         {
@@ -156,7 +156,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                         // If this is an object, and the end of object has been reached, then parse object end.
                         while (!isData)
                         {
-                            ObjectProgress op = (ObjectProgress)_stack.Peek();
+                            ObjectProgress? op = (ObjectProgress?)_stack.Peek();
                             if (op == null)
                             {
                                 // No more object on stack, then the next record is a top level object
@@ -301,7 +301,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 record.Read(this);
             }
 
-            AssemIdToAssemblyTable[record._assemId] = new BinaryAssemblyInfo(record._assemblyString);
+            AssemIdToAssemblyTable[record._assemId] = new BinaryAssemblyInfo(record._assemblyString!);
         }
 
         private void ReadObject()
@@ -312,7 +312,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
             _binaryObject.Read(this);
 
-            ObjectMap objectMap = (ObjectMap)ObjectMapIdTable[_binaryObject._mapId];
+            ObjectMap? objectMap = (ObjectMap?)ObjectMapIdTable[_binaryObject._mapId];
             if (objectMap == null)
             {
                 throw new SerializationException(SR.Format(SR.Serialization_Map, _binaryObject._mapId));
@@ -328,7 +328,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             op._memberTypes = objectMap._memberTypes;
             op._typeInformationA = objectMap._typeInformationA;
             op._memberLength = op._binaryTypeEnumA.Length;
-            ObjectProgress objectOp = (ObjectProgress)_stack.PeekPeek();
+            ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek();
             if ((objectOp == null) || (objectOp._isInitial))
             {
                 // Non-Nested Object
@@ -379,15 +379,13 @@ namespace System.Runtime.Serialization.Formatters.Binary
             BinaryCrossAppDomainMap record = new BinaryCrossAppDomainMap();
             record.Read(this);
             object mapObject = _objectReader.CrossAppDomainArray(record._crossAppDomainArrayIndex);
-            BinaryObjectWithMap binaryObjectWithMap = mapObject as BinaryObjectWithMap;
-            if (binaryObjectWithMap != null)
+            if (mapObject is BinaryObjectWithMap binaryObjectWithMap)
             {
                 ReadObjectWithMap(binaryObjectWithMap);
             }
             else
             {
-                BinaryObjectWithMapTyped binaryObjectWithMapTyped = mapObject as BinaryObjectWithMapTyped;
-                if (binaryObjectWithMapTyped != null)
+                if (mapObject is BinaryObjectWithMapTyped binaryObjectWithMapTyped)
                 {
                     ReadObjectWithMapTyped(binaryObjectWithMapTyped);
                 }
@@ -414,7 +412,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private void ReadObjectWithMap(BinaryObjectWithMap record)
         {
-            BinaryAssemblyInfo assemblyInfo = null;
+            BinaryAssemblyInfo? assemblyInfo = null;
             ObjectProgress op = GetOp();
             ParseRecord pr = op._pr;
             _stack.Push(op);
@@ -426,7 +424,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     throw new SerializationException(SR.Format(SR.Serialization_Assembly, record._name));
                 }
 
-                assemblyInfo = ((BinaryAssemblyInfo)AssemIdToAssemblyTable[record._assemId]);
+                assemblyInfo = ((BinaryAssemblyInfo?)AssemIdToAssemblyTable[record._assemId]);
 
                 if (assemblyInfo == null)
                 {
@@ -438,9 +436,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 assemblyInfo = SystemAssemblyInfo; //Urt assembly
             }
 
-            Type objectType = _objectReader.GetType(assemblyInfo, record._name);
+            Debug.Assert(record._name != null && record._memberNames != null);
+            Type? objectType = _objectReader.GetType(assemblyInfo!, record._name);
 
-            ObjectMap objectMap = ObjectMap.Create(record._name, objectType, record._memberNames, _objectReader, record._objectId, assemblyInfo);
+            Debug.Assert(objectType != null);
+            ObjectMap objectMap = ObjectMap.Create(record._name, objectType, record._memberNames, _objectReader, record._objectId, assemblyInfo!);
             ObjectMapIdTable[record._objectId] = objectMap;
 
             op._objectTypeEnum = InternalObjectTypeE.Object;
@@ -450,7 +450,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             op._memberNames = objectMap._memberNames;
             op._memberTypes = objectMap._memberTypes;
 
-            ObjectProgress objectOp = (ObjectProgress)_stack.PeekPeek();
+            ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek();
 
             if ((objectOp == null) || (objectOp._isInitial))
             {
@@ -512,7 +512,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private void ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
         {
-            BinaryAssemblyInfo assemblyInfo = null;
+            BinaryAssemblyInfo? assemblyInfo = null;
             ObjectProgress op = GetOp();
             ParseRecord pr = op._pr;
             _stack.Push(op);
@@ -524,7 +524,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, record._name));
                 }
 
-                assemblyInfo = (BinaryAssemblyInfo)AssemIdToAssemblyTable[record._assemId];
+                assemblyInfo = (BinaryAssemblyInfo?)AssemIdToAssemblyTable[record._assemId];
                 if (assemblyInfo == null)
                 {
                     throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, record._assemId + " " + record._name));
@@ -535,7 +535,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 assemblyInfo = SystemAssemblyInfo; // Urt assembly
             }
 
-            ObjectMap objectMap = ObjectMap.Create(record._name, record._memberNames, record._binaryTypeEnumA, record._typeInformationA, record._memberAssemIds, _objectReader, record._objectId, assemblyInfo, AssemIdToAssemblyTable);
+            Debug.Assert(record._name != null && record._memberNames != null && record._binaryTypeEnumA != null && record._typeInformationA != null && record._memberAssemIds != null);
+            ObjectMap objectMap = ObjectMap.Create(record._name, record._memberNames, record._binaryTypeEnumA, record._typeInformationA, record._memberAssemIds, _objectReader, record._objectId, assemblyInfo!, AssemIdToAssemblyTable);
             ObjectMapIdTable[record._objectId] = objectMap;
             op._objectTypeEnum = InternalObjectTypeE.Object;
             op._binaryTypeEnumA = objectMap._binaryTypeEnumA;
@@ -544,7 +545,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             op._memberNames = objectMap._memberNames;
             op._memberTypes = objectMap._memberTypes;
 
-            ObjectProgress objectOp = (ObjectProgress)_stack.PeekPeek();
+            ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek();
 
             if ((objectOp == null) || (objectOp._isInitial))
             {
@@ -627,7 +628,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
             PRs._objectTypeEnum = InternalObjectTypeE.Object;
 
-            ObjectProgress objectOp = (ObjectProgress)_stack.Peek();
+            ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek();
 
             PRs._value = _objectString._value;
             PRs._keyDt = "System.String";
@@ -674,7 +675,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _memberPrimitiveTyped.Read(this);
 
             PRs._objectTypeEnum = InternalObjectTypeE.Object; //Get rid of
-            ObjectProgress objectOp = (ObjectProgress)_stack.Peek();
+            ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek();
 
             PRs.Init();
             PRs._varValue = _memberPrimitiveTyped._value;
@@ -714,7 +715,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private void ReadArray(BinaryHeaderEnum binaryHeaderEnum)
         {
-            BinaryAssemblyInfo assemblyInfo = null;
+            BinaryAssemblyInfo? assemblyInfo = null;
             BinaryArray record = new BinaryArray(binaryHeaderEnum);
             record.Read(this);
 
@@ -724,7 +725,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 {
                     throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, record._typeInformation));
                 }
-                assemblyInfo = (BinaryAssemblyInfo)AssemIdToAssemblyTable[record._assemId];
+                assemblyInfo = (BinaryAssemblyInfo?)AssemIdToAssemblyTable[record._assemId];
             }
             else
             {
@@ -738,7 +739,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             op._binaryTypeEnum = record._binaryTypeEnum;
             op._typeInformation = record._typeInformation;
 
-            ObjectProgress objectOp = (ObjectProgress)_stack.PeekPeek();
+            ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek();
             if ((objectOp == null) || (record._objectId > 0))
             {
                 // Non-Nested Object
@@ -798,12 +799,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
             pr._lowerBoundA = record._lowerBoundA;
             bool isPrimitiveArray = false;
 
+            Debug.Assert(record._lengthA != null);
             switch (record._binaryArrayTypeEnum)
             {
                 case BinaryArrayTypeEnum.Single:
                 case BinaryArrayTypeEnum.SingleOffset:
                     op._numItems = record._lengthA[0];
                     pr._arrayTypeEnum = InternalArrayTypeE.Single;
+                    Debug.Assert(record._lowerBoundA != null);
                     if (Converter.IsWriteAsByteArray(pr._arrayElementTypeCode) &&
                         (record._lowerBoundA[0] == 0))
                     {
@@ -848,6 +851,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private void ReadArrayAsBytes(ParseRecord pr)
         {
+            Debug.Assert(pr._lengthA != null);
             if (pr._arrayElementTypeCode == InternalPrimitiveTypeE.Byte)
             {
                 pr._newObj = ReadBytes(pr._lengthA[0]);
@@ -897,22 +901,23 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private void ReadMemberPrimitiveUnTyped()
         {
-            ObjectProgress objectOp = (ObjectProgress)_stack.Peek();
+            ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek();
             if (memberPrimitiveUnTyped == null)
             {
                 memberPrimitiveUnTyped = new MemberPrimitiveUnTyped();
             }
-            memberPrimitiveUnTyped.Set((InternalPrimitiveTypeE)_expectedTypeInformation);
+            memberPrimitiveUnTyped.Set((InternalPrimitiveTypeE)_expectedTypeInformation!);
             memberPrimitiveUnTyped.Read(this);
 
             PRs.Init();
             PRs._varValue = memberPrimitiveUnTyped._value;
 
-            PRs._dtTypeCode = (InternalPrimitiveTypeE)_expectedTypeInformation;
+            PRs._dtTypeCode = (InternalPrimitiveTypeE)_expectedTypeInformation!;
             PRs._dtType = Converter.ToType(PRs._dtTypeCode);
             PRs._parseTypeEnum = InternalParseTypeE.Member;
             PRs._memberValueEnum = InternalMemberValueE.InlineValue;
 
+            Debug.Assert(objectOp != null);
             if (objectOp._objectTypeEnum == InternalObjectTypeE.Object)
             {
                 PRs._memberTypeEnum = InternalMemberTypeE.Field;
@@ -934,13 +939,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
             _memberReference.Read(this);
 
-            ObjectProgress objectOp = (ObjectProgress)_stack.Peek();
+            ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek();
 
             PRs.Init();
             PRs._idRef = _objectReader.GetId(_memberReference._idRef);
             PRs._parseTypeEnum = InternalParseTypeE.Member;
             PRs._memberValueEnum = InternalMemberValueE.Reference;
 
+            Debug.Assert(objectOp != null);
             if (objectOp._objectTypeEnum == InternalObjectTypeE.Object)
             {
                 PRs._memberTypeEnum = InternalMemberTypeE.Field;
@@ -963,12 +969,13 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
             _objectNull.Read(this, binaryHeaderEnum);
 
-            ObjectProgress objectOp = (ObjectProgress)_stack.Peek();
+            ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek();
 
             PRs.Init();
             PRs._parseTypeEnum = InternalParseTypeE.Member;
             PRs._memberValueEnum = InternalMemberValueE.Null;
 
+            Debug.Assert(objectOp != null);
             if (objectOp._objectTypeEnum == InternalObjectTypeE.Object)
             {
                 PRs._memberTypeEnum = InternalMemberTypeE.Field;
@@ -1024,11 +1031,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private ObjectProgress GetOp()
         {
-            ObjectProgress op = null;
+            ObjectProgress op;
 
             if (_opPool != null && !_opPool.IsEmpty())
             {
-                op = (ObjectProgress)_opPool.Pop();
+                op = (ObjectProgress)_opPool.Pop()!;
                 op.Init();
             }
             else
index 9ce50ec..f4c3029 100644 (file)
@@ -11,7 +11,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
     internal static class BinaryTypeConverter
     {
         // From the type create the BinaryTypeEnum and typeInformation which describes the type on the wire
-        internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo objectInfo, string typeName, ObjectWriter objectWriter, out object typeInformation, out int assemId)
+        internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo? objectInfo, string? typeName, ObjectWriter objectWriter, out object? typeInformation, out int assemId)
         {
             BinaryTypeEnum binaryTypeEnum;
 
@@ -45,7 +45,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 switch (primitiveTypeEnum)
                 {
                     case InternalPrimitiveTypeE.Invalid:
-                        string assembly = null;
+                        string? assembly = null;
                         if (objectInfo == null)
                         {
                             assembly = type.Assembly.FullName;
@@ -57,6 +57,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                             typeInformation = objectInfo.GetTypeFullName();
                         }
 
+                        Debug.Assert(assembly != null);
                         if (assembly.Equals(Converter.s_urtAssemblyString) || assembly.Equals(Converter.s_urtAlternativeAssemblyString))
                         {
                             binaryTypeEnum = BinaryTypeEnum.ObjectUrt;
@@ -84,7 +85,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Used for non Si types when Parsing
-        internal static BinaryTypeEnum GetParserBinaryTypeInfo(Type type, out object typeInformation)
+        internal static BinaryTypeEnum GetParserBinaryTypeInfo(Type type, out object? typeInformation)
         {
             BinaryTypeEnum binaryTypeEnum;
             typeInformation = null;
@@ -131,7 +132,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Writes the type information on the wire
-        internal static void WriteTypeInfo(BinaryTypeEnum binaryTypeEnum, object typeInformation, int assemId, BinaryFormatterWriter output)
+        internal static void WriteTypeInfo(BinaryTypeEnum binaryTypeEnum, object? typeInformation, int assemId, BinaryFormatterWriter output)
         {
             switch (binaryTypeEnum)
             {
@@ -147,11 +148,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     break;
                 case BinaryTypeEnum.ObjectUrt:
                     Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null");
-                    output.WriteString(typeInformation.ToString());
+                    output.WriteString(typeInformation.ToString()!);
                     break;
                 case BinaryTypeEnum.ObjectUser:
                     Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null");
-                    output.WriteString(typeInformation.ToString());
+                    output.WriteString(typeInformation.ToString()!);
                     output.WriteInt32(assemId);
                     break;
                 default:
@@ -162,7 +163,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // Reads the type information from the wire
         internal static object ReadTypeInfo(BinaryTypeEnum binaryTypeEnum, BinaryParser input, out int assemId)
         {
-            object var = null;
+            object var = null!;
             int readAssemId = 0;
 
             switch (binaryTypeEnum)
@@ -192,12 +193,12 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         // Given the wire type information, returns the actual type and additional information
         internal static void TypeFromInfo(BinaryTypeEnum binaryTypeEnum,
-                                          object typeInformation,
+                                          object? typeInformation,
                                           ObjectReader objectReader,
-                                          BinaryAssemblyInfo assemblyInfo,
+                                          BinaryAssemblyInfo? assemblyInfo,
                                           out InternalPrimitiveTypeE primitiveTypeEnum,
-                                          out string typeString,
-                                          out Type type,
+                                          out string? typeString,
+                                          out Type? type,
                                           out bool isVariant)
         {
             isVariant = false;
@@ -208,7 +209,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             switch (binaryTypeEnum)
             {
                 case BinaryTypeEnum.Primitive:
-                    primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation;
+                    primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation!;
                     typeString = Converter.ToComType(primitiveTypeEnum);
                     type = Converter.ToType(primitiveTypeEnum);
                     break;
@@ -226,7 +227,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     type = Converter.s_typeofStringArray;
                     break;
                 case BinaryTypeEnum.PrimitiveArray:
-                    primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation;
+                    primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation!;
                     type = Converter.ToArrayType(primitiveTypeEnum);
                     break;
                 case BinaryTypeEnum.ObjectUser:
@@ -234,7 +235,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                     if (typeInformation != null)
                     {
                         typeString = typeInformation.ToString();
-                        type = objectReader.GetType(assemblyInfo, typeString);
+                        type = objectReader.GetType(assemblyInfo!, typeString!);
                         if (ReferenceEquals(type, Converter.s_typeofObject))
                         {
                             isVariant = true;
index 70da380..a00c57b 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Collections.Concurrent;
+using System.Diagnostics;
 using System.Globalization;
 using System.Reflection;
 
@@ -19,15 +20,15 @@ namespace System.Runtime.Serialization.Formatters.Binary
         internal InternalObjectPositionE _objectPositionEnum = InternalObjectPositionE.Empty;
 
         // Object
-        internal string _name;
+        internal string? _name;
 
         // Value
-        internal string _value;
-        internal object _varValue;
+        internal string? _value;
+        internal object? _varValue;
 
         // dt attribute
-        internal string _keyDt;
-        internal Type _dtType;
+        internal string? _keyDt;
+        internal Type? _dtType;
         internal InternalPrimitiveTypeE _dtTypeCode;
 
         // Object ID
@@ -39,37 +40,37 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // Array
 
         // Array Element Type
-        internal string _arrayElementTypeString;
-        internal Type _arrayElementType;
+        internal string? _arrayElementTypeString;
+        internal Type? _arrayElementType;
         internal bool _isArrayVariant = false;
         internal InternalPrimitiveTypeE _arrayElementTypeCode;
 
         // Parsed array information
         internal int _rank;
-        internal int[] _lengthA;
-        internal int[] _lowerBoundA;
+        internal int[]? _lengthA;
+        internal int[]? _lowerBoundA;
 
         // Array map for placing array elements in array
-        internal int[] _indexMap;
+        internal int[]? _indexMap;
         internal int _memberIndex;
         internal int _linearlength;
-        internal int[] _rectangularMap;
+        internal int[]? _rectangularMap;
         internal bool _isLowerBound;
 
         // MemberInfo accumulated during parsing of members
 
-        internal ReadObjectInfo _objectInfo;
+        internal ReadObjectInfo? _objectInfo;
 
         // ValueType Fixup needed
         internal bool _isValueTypeFixup = false;
 
         // Created object
-        internal object _newObj;
-        internal object[] _objectA; //optimization, will contain object[]
-        internal PrimitiveArray _primitiveArray; // for Primitive Soap arrays, optimization
+        internal object? _newObj;
+        internal object?[]? _objectA; //optimization, will contain object[]
+        internal PrimitiveArray? _primitiveArray; // for Primitive Soap arrays, optimization
         internal bool _isRegistered; // Used when registering nested classes
-        internal object[] _memberData; // member data is collected here before populating
-        internal SerializationInfo _si;
+        internal object?[]? _memberData; // member data is collected here before populating
+        internal SerializationInfo? _si;
 
         internal int _consecutiveNullArrayEntryCount;
 
@@ -141,7 +142,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
     // Implements a stack used for parsing
     internal sealed class SerStack
     {
-        internal object[] _objects = new object[5];
+        internal object?[] _objects = new object?[5];
         internal string _stackId;
         internal int _top = -1;
 
@@ -161,14 +162,14 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Pop the object from the stack
-        internal object Pop()
+        internal object? Pop()
         {
             if (_top < 0)
             {
                 return null;
             }
 
-            object obj = _objects[_top];
+            object? obj = _objects[_top];
             _objects[_top--] = null;
             return obj;
         }
@@ -182,10 +183,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
         }
 
         // Gets the object on the top of the stack
-        internal object Peek() => _top < 0 ? null : _objects[_top];
+        internal object? Peek() => _top < 0 ? null : _objects[_top];
 
         // Gets the second entry in the stack.
-        internal object PeekPeek() => _top < 1 ? null : _objects[_top - 1];
+        internal object? PeekPeek() => _top < 1 ? null : _objects[_top - 1];
 
         // The number of entries in the stack
         internal bool IsEmpty() => _top <= 0;
@@ -194,8 +195,8 @@ namespace System.Runtime.Serialization.Formatters.Binary
     // Implements a Growable array
     internal sealed class SizedArray : ICloneable
     {
-        internal object[] _objects = null;
-        internal object[] _negObjects = null;
+        internal object?[] _objects;
+        internal object?[] _negObjects;
 
         internal SizedArray()
         {
@@ -219,7 +220,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         public object Clone() => new SizedArray(this);
 
-        internal object this[int index]
+        internal object? this[int index]
         {
             get
             {
@@ -359,16 +360,15 @@ namespace System.Runtime.Serialization.Formatters.Binary
     internal sealed class NameCache
     {
         private static readonly ConcurrentDictionary<string, object> s_ht = new ConcurrentDictionary<string, object>();
-        private string _name = null;
+        private string? _name = null;
 
-        internal object GetCachedValue(string name)
+        internal object? GetCachedValue(string name)
         {
             _name = name;
-            object value;
-            return s_ht.TryGetValue(name, out value) ? value : null;
+            return s_ht.TryGetValue(name, out object? value) ? value : null;
         }
 
-        internal void SetCachedValue(object value) => s_ht[_name] = value;
+        internal void SetCachedValue(object value) => s_ht[_name!] = value;
     }
 
 
@@ -376,12 +376,12 @@ namespace System.Runtime.Serialization.Formatters.Binary
     internal sealed class ValueFixup
     {
         internal ValueFixupEnum _valueFixupEnum = ValueFixupEnum.Empty;
-        internal Array _arrayObj;
-        internal int[] _indexMap;
-        internal object _header = null;
-        internal object _memberObject;
-        internal ReadObjectInfo _objectInfo;
-        internal string _memberName;
+        internal Array? _arrayObj;
+        internal int[]? _indexMap;
+        internal object? _header = null;
+        internal object? _memberObject;
+        internal ReadObjectInfo? _objectInfo;
+        internal string? _memberName;
 
         internal ValueFixup(Array arrayObj, int[] indexMap)
         {
@@ -390,7 +390,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _indexMap = indexMap;
         }
 
-        internal ValueFixup(object memberObject, string memberName, ReadObjectInfo objectInfo)
+        internal ValueFixup(object? memberObject, string memberName, ReadObjectInfo objectInfo)
         {
             _valueFixupEnum = ValueFixupEnum.Member;
             _memberObject = memberObject;
@@ -400,22 +400,23 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         internal void Fixup(ParseRecord record, ParseRecord parent)
         {
-            object obj = record._newObj;
+            object? obj = record._newObj;
             switch (_valueFixupEnum)
             {
                 case ValueFixupEnum.Array:
-                    _arrayObj.SetValue(obj, _indexMap);
+                    _arrayObj!.SetValue(obj, _indexMap!);
                     break;
                 case ValueFixupEnum.Header:
                     throw new PlatformNotSupportedException();
                 case ValueFixupEnum.Member:
+                    Debug.Assert(_objectInfo!._objectManager != null);
                     if (_objectInfo._isSi)
                     {
-                        _objectInfo._objectManager.RecordDelayedFixup(parent._objectId, _memberName, record._objectId);
+                        _objectInfo._objectManager.RecordDelayedFixup(parent._objectId, _memberName!, record._objectId);
                     }
                     else
                     {
-                        MemberInfo memberInfo = _objectInfo.GetMemberInfo(_memberName);
+                        MemberInfo? memberInfo = _objectInfo.GetMemberInfo(_memberName);
                         if (memberInfo != null)
                         {
                             _objectInfo._objectManager.RecordFixup(parent._objectId, memberInfo, record._objectId);
@@ -437,11 +438,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
     internal sealed class NameInfo
     {
-        internal string _fullName; // Name from SerObjectInfo.GetType
+        internal string? _fullName; // Name from SerObjectInfo.GetType
         internal long _objectId;
         internal long _assemId;
         internal InternalPrimitiveTypeE _primitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
-        internal Type _type;
+        internal Type? _type;
         internal bool _isSealed;
         internal bool _isArray;
         internal bool _isArrayItem;
@@ -476,6 +477,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             {
                 if (!_sealedStatusChecked)
                 {
+                    Debug.Assert(_type != null);
                     _isSealed = _type.IsSealed;
                     _sealedStatusChecked = true;
                 }
@@ -483,9 +485,9 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
         }
 
-        public string NIname
+        public string? NIname
         {
-            get { return _fullName ?? (_fullName = _type.FullName); }
+            get { return _fullName ?? (_fullName = _type?.FullName); }
             set { _fullName = value; }
         }
     }
@@ -493,17 +495,17 @@ namespace System.Runtime.Serialization.Formatters.Binary
     internal sealed class PrimitiveArray
     {
         private readonly InternalPrimitiveTypeE _code;
-        private readonly bool[] _booleanA = null;
-        private readonly char[] _charA = null;
-        private readonly double[] _doubleA = null;
-        private readonly short[] _int16A = null;
-        private readonly int[] _int32A = null;
-        private readonly long[] _int64A = null;
-        private readonly sbyte[] _sbyteA = null;
-        private readonly float[] _singleA = null;
-        private readonly ushort[] _uint16A = null;
-        private readonly uint[] _uint32A = null;
-        private readonly ulong[] _uint64A = null;
+        private readonly bool[] _booleanA = null!;
+        private readonly char[] _charA = null!;
+        private readonly double[] _doubleA = null!;
+        private readonly short[] _int16A = null!;
+        private readonly int[] _int32A = null!;
+        private readonly long[] _int64A = null!;
+        private readonly sbyte[] _sbyteA = null!;
+        private readonly float[] _singleA = null!;
+        private readonly ushort[] _uint16A = null!;
+        private readonly uint[] _uint32A = null!;
+        private readonly ulong[] _uint64A = null!;
 
         internal PrimitiveArray(InternalPrimitiveTypeE code, Array array)
         {
index d527a06..138fdf8 100644 (file)
@@ -5,6 +5,7 @@
 using System.Reflection;
 using System.Globalization;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization.Formatters.Binary
 {
@@ -36,10 +37,10 @@ namespace System.Runtime.Serialization.Formatters.Binary
         // contain all the types which are living in mscorlib in netfx. Therefore we
         // use our mscorlib facade which also contains manual type forwards for deserialization.
         internal static readonly Assembly s_urtAssembly = Assembly.Load("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
-        internal static readonly string s_urtAssemblyString = s_urtAssembly.FullName;
+        internal static readonly string s_urtAssemblyString = s_urtAssembly.FullName!;
 
         internal static readonly Assembly s_urtAlternativeAssembly = s_typeofString.Assembly;
-        internal static readonly string s_urtAlternativeAssemblyString = s_urtAlternativeAssembly.FullName;
+        internal static readonly string s_urtAlternativeAssemblyString = s_urtAlternativeAssembly.FullName!;
 
         // Arrays
         internal static readonly Type s_typeofTypeArray = typeof(Type[]);
@@ -64,13 +65,13 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private const int PrimitiveTypeEnumLength = 17; //Number of PrimitiveTypeEnums
 
-        private static volatile Type[] s_typeA;
-        private static volatile Type[] s_arrayTypeA;
-        private static volatile string[] s_valueA;
-        private static volatile TypeCode[] s_typeCodeA;
-        private static volatile InternalPrimitiveTypeE[] s_codeA;
+        private static volatile Type?[]? s_typeA;
+        private static volatile Type?[]? s_arrayTypeA;
+        private static volatile string?[]? s_valueA;
+        private static volatile TypeCode[]? s_typeCodeA;
+        private static volatile InternalPrimitiveTypeE[]? s_codeA;
 
-        internal static InternalPrimitiveTypeE ToCode(Type type) =>
+        internal static InternalPrimitiveTypeE ToCode(Type? type) =>
                 type == null ? ToPrimitiveTypeEnum(TypeCode.Empty) :
                 type.IsPrimitive ? ToPrimitiveTypeEnum(Type.GetTypeCode(type)) :
                 ReferenceEquals(type, s_typeofDateTime) ? InternalPrimitiveTypeE.DateTime :
@@ -118,18 +119,18 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 _ => 0,
             };
 
-        internal static Type ToArrayType(InternalPrimitiveTypeE code)
+        internal static Type? ToArrayType(InternalPrimitiveTypeE code)
         {
             if (s_arrayTypeA == null)
             {
                 InitArrayTypeA();
             }
-            return s_arrayTypeA[(int)code];
+            return s_arrayTypeA![(int)code];
         }
 
         private static void InitTypeA()
         {
-            var typeATemp = new Type[PrimitiveTypeEnumLength];
+            var typeATemp = new Type?[PrimitiveTypeEnumLength];
             typeATemp[(int)InternalPrimitiveTypeE.Invalid] = null;
             typeATemp[(int)InternalPrimitiveTypeE.Boolean] = s_typeofBoolean;
             typeATemp[(int)InternalPrimitiveTypeE.Byte] = s_typeofByte;
@@ -151,7 +152,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private static void InitArrayTypeA()
         {
-            var arrayTypeATemp = new Type[PrimitiveTypeEnumLength];
+            var arrayTypeATemp = new Type?[PrimitiveTypeEnumLength];
             arrayTypeATemp[(int)InternalPrimitiveTypeE.Invalid] = null;
             arrayTypeATemp[(int)InternalPrimitiveTypeE.Boolean] = s_typeofBooleanArray;
             arrayTypeATemp[(int)InternalPrimitiveTypeE.Byte] = s_typeofByteArray;
@@ -171,16 +172,16 @@ namespace System.Runtime.Serialization.Formatters.Binary
             s_arrayTypeA = arrayTypeATemp;
         }
 
-        internal static Type ToType(InternalPrimitiveTypeE code)
+        internal static Type? ToType(InternalPrimitiveTypeE code)
         {
             if (s_typeA == null)
             {
                 InitTypeA();
             }
-            return s_typeA[(int)code];
+            return s_typeA![(int)code];
         }
 
-        internal static Array CreatePrimitiveArray(InternalPrimitiveTypeE code, int length) =>
+        internal static Array? CreatePrimitiveArray(InternalPrimitiveTypeE code, int length) =>
             code switch
             {
                 InternalPrimitiveTypeE.Boolean => new bool[length],
@@ -201,7 +202,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 _ => null,
             };
 
-        internal static bool IsPrimitiveArray(Type type, out object typeInformation)
+        internal static bool IsPrimitiveArray(Type? type, [NotNullWhen(true)] out object? typeInformation)
         {
             bool bIsPrimitive = true;
 
@@ -228,7 +229,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         private static void InitValueA()
         {
-            var valueATemp = new string[PrimitiveTypeEnumLength];
+            var valueATemp = new string?[PrimitiveTypeEnumLength];
             valueATemp[(int)InternalPrimitiveTypeE.Invalid] = null;
             valueATemp[(int)InternalPrimitiveTypeE.Boolean] = "Boolean";
             valueATemp[(int)InternalPrimitiveTypeE.Byte] = "Byte";
@@ -248,13 +249,13 @@ namespace System.Runtime.Serialization.Formatters.Binary
             s_valueA = valueATemp;
         }
 
-        internal static string ToComType(InternalPrimitiveTypeE code)
+        internal static string? ToComType(InternalPrimitiveTypeE code)
         {
             if (s_valueA == null)
             {
                 InitValueA();
             }
-            return s_valueA[(int)code];
+            return s_valueA![(int)code];
         }
 
         private static void InitTypeCodeA()
@@ -286,7 +287,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             {
                 InitTypeCodeA();
             }
-            return s_typeCodeA[(int)code];
+            return s_typeCodeA![(int)code];
         }
 
         private static void InitCodeA()
@@ -321,11 +322,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
             {
                 InitCodeA();
             }
-            return s_codeA[(int)typeCode];
+            return s_codeA![(int)typeCode];
         }
 
         // Translates a string into an Object
-        internal static object FromString(string value, InternalPrimitiveTypeE code)
+        internal static object? FromString(string? value, InternalPrimitiveTypeE code)
         {
             // InternalPrimitiveTypeE needs to be a primitive type
             Debug.Assert((code != InternalPrimitiveTypeE.Invalid), "[Converter.FromString]!InternalPrimitiveTypeE.Invalid ");
index e2c5cc5..d0df192 100644 (file)
@@ -7,11 +7,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
     internal sealed class MemberPrimitiveTyped : IStreamable
     {
         internal InternalPrimitiveTypeE _primitiveTypeEnum;
-        internal object _value;
+        internal object? _value;
 
         internal MemberPrimitiveTyped() { }
 
-        internal void Set(InternalPrimitiveTypeE primitiveTypeEnum, object value)
+        internal void Set(InternalPrimitiveTypeE primitiveTypeEnum, object? value)
         {
             _primitiveTypeEnum = primitiveTypeEnum;
             _value = value;
index 4b63a81..fae2a82 100644 (file)
@@ -8,11 +8,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
     {
         // Used for members with primitive values and types are needed
         internal InternalPrimitiveTypeE _typeInformation;
-        internal object _value;
+        internal object? _value;
 
         internal MemberPrimitiveUnTyped() { }
 
-        internal void Set(InternalPrimitiveTypeE typeInformation, object value)
+        internal void Set(InternalPrimitiveTypeE typeInformation, object? value)
         {
             _typeInformation = typeInformation;
             _value = value;
index e628f4f..b7620a2 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Diagnostics;
+
 namespace System.Runtime.Serialization.Formatters.Binary
 {
     // When an ObjectWithMap or an ObjectWithMapTyped is read off the stream, an ObjectMap class is created
@@ -9,15 +11,15 @@ namespace System.Runtime.Serialization.Formatters.Binary
     internal sealed class ObjectMap
     {
         internal string _objectName;
-        internal Type _objectType;
+        internal Type? _objectType;
 
         internal BinaryTypeEnum[] _binaryTypeEnumA;
-        internal object[] _typeInformationA;
-        internal Type[] _memberTypes;
+        internal object?[] _typeInformationA;
+        internal Type?[] _memberTypes;
         internal string[] _memberNames;
         internal ReadObjectInfo _objectInfo;
         internal bool _isInitObjectInfo = true;
-        internal ObjectReader _objectReader = null;
+        internal ObjectReader? _objectReader = null;
         internal int _objectId;
         internal BinaryAssemblyInfo _assemblyInfo;
 
@@ -31,21 +33,20 @@ namespace System.Runtime.Serialization.Formatters.Binary
             _assemblyInfo = assemblyInfo;
 
             _objectInfo = objectReader.CreateReadObjectInfo(objectType);
-            _memberTypes = _objectInfo.GetMemberTypes(memberNames, objectType);
+            _memberTypes = _objectInfo.GetMemberTypes(memberNames, objectType)!;
 
             _binaryTypeEnumA = new BinaryTypeEnum[_memberTypes.Length];
             _typeInformationA = new object[_memberTypes.Length];
 
             for (int i = 0; i < _memberTypes.Length; i++)
             {
-                object typeInformation = null;
-                BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetParserBinaryTypeInfo(_memberTypes[i], out typeInformation);
+                BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetParserBinaryTypeInfo(_memberTypes[i]!, out object? typeInformation);
                 _binaryTypeEnumA[i] = binaryTypeEnum;
                 _typeInformationA[i] = typeInformation;
             }
         }
 
-        internal ObjectMap(string objectName, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object[] typeInformationA, int[] memberAssemIds, ObjectReader objectReader, int objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
+        internal ObjectMap(string objectName, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object?[] typeInformationA, int[] memberAssemIds, ObjectReader objectReader, int objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
         {
             _objectName = objectName;
             _memberNames = memberNames;
@@ -66,13 +67,11 @@ namespace System.Runtime.Serialization.Formatters.Binary
             for (int i = 0; i < memberNames.Length; i++)
             {
                 InternalPrimitiveTypeE primitiveTypeEnum;
-                string typeString;
-                Type type;
                 bool isVariant;
 
                 BinaryTypeConverter.TypeFromInfo(
-                    binaryTypeEnumA[i], typeInformationA[i], objectReader, (BinaryAssemblyInfo)assemIdToAssemblyTable[memberAssemIds[i]],
-                    out primitiveTypeEnum, out typeString, out type, out isVariant);
+                    binaryTypeEnumA[i], typeInformationA[i], objectReader, (BinaryAssemblyInfo?)assemIdToAssemblyTable[memberAssemIds[i]],
+                    out primitiveTypeEnum, out string? typeString, out Type? type, out isVariant);
                 _memberTypes[i] = type;
             }
 
@@ -83,7 +82,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
             }
         }
 
-        internal ReadObjectInfo CreateObjectInfo(ref SerializationInfo si, ref object[] memberData)
+        internal ReadObjectInfo CreateObjectInfo(ref SerializationInfo? si, ref object?[]? memberData)
         {
             if (_isInitObjectInfo)
             {
@@ -107,7 +106,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
         // Member type information
         internal static ObjectMap Create(
-            string name, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object[] typeInformationA,
+            string name, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object?[] typeInformationA,
             int[] memberAssemIds, ObjectReader objectReader, int objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable) =>
             new ObjectMap(name, memberNames, binaryTypeEnumA, typeInformationA, memberAssemIds, objectReader, objectId, assemblyInfo, assemIdToAssemblyTable);
     }
index 78fb1c5..64c0a19 100644 (file)
@@ -2,6 +2,9 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+
 namespace System.Runtime.Serialization.Formatters.Binary
 {
     // For each object or array being read off the stream, an ObjectProgress object is created. This object
@@ -14,25 +17,25 @@ namespace System.Runtime.Serialization.Formatters.Binary
         internal bool _isInitial;
         internal int _count; //Progress count
         internal BinaryTypeEnum _expectedType = BinaryTypeEnum.ObjectUrt;
-        internal object _expectedTypeInformation = null;
+        internal object? _expectedTypeInformation = null;
 
-        internal string _name;
+        internal string? _name;
         internal InternalObjectTypeE _objectTypeEnum = InternalObjectTypeE.Empty;
         internal InternalMemberTypeE _memberTypeEnum;
         internal InternalMemberValueE _memberValueEnum;
-        internal Type _dtType;
+        internal Type? _dtType;
 
         // Array Information
         internal int _numItems;
         internal BinaryTypeEnum _binaryTypeEnum;
-        internal object _typeInformation;
+        internal object? _typeInformation;
 
         // Member Information
         internal int _memberLength;
-        internal BinaryTypeEnum[] _binaryTypeEnumA;
-        internal object[] _typeInformationA;
-        internal string[] _memberNames;
-        internal Type[] _memberTypes;
+        internal BinaryTypeEnum[]? _binaryTypeEnumA;
+        internal object?[]? _typeInformationA;
+        internal string[]? _memberNames;
+        internal Type?[]? _memberTypes;
 
         // ParseRecord
         internal ParseRecord _pr = new ParseRecord();
@@ -73,7 +76,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
         internal void ArrayCountIncrement(int value) => _count += value;
 
         // Specifies what is to parsed next from the wire.
-        internal bool GetNext(out BinaryTypeEnum outBinaryTypeEnum, out object outTypeInformation)
+        internal bool GetNext(out BinaryTypeEnum outBinaryTypeEnum, [NotNullWhen(true)] out object? outTypeInformation)
         {
             //Initialize the out params up here.
             outBinaryTypeEnum = BinaryTypeEnum.Primitive;
@@ -105,6 +108,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
                 }
                 else
                 {
+                    Debug.Assert(_binaryTypeEnumA != null && _typeInformationA != null && _memberNames != null && _memberTypes != null);
                     outBinaryTypeEnum = _binaryTypeEnumA[_count];
                     outTypeInformation = _typeInformationA[_count];
                     if (_count == 0)
index ccc2d2b..3a85e6b 100644 (file)
@@ -6,7 +6,7 @@ namespace System.Runtime.Serialization.Formatters
 {
     public interface IFieldInfo
     {
-        string[] FieldNames { get; set; }
-        Type[] FieldTypes { get; set; }
+        string[]? FieldNames { get; set; }
+        Type[]? FieldTypes { get; set; }
     }
 }
index 2887878..16a2b01 100644 (file)
@@ -10,8 +10,8 @@ namespace System.Runtime.Serialization
     {
         object Deserialize(Stream serializationStream);
         void Serialize(Stream serializationStream, object graph);
-        ISurrogateSelector SurrogateSelector { get; set; }
-        SerializationBinder Binder { get; set; }
+        ISurrogateSelector? SurrogateSelector { get; set; }
+        SerializationBinder? Binder { get; set; }
         StreamingContext Context { get; set; }
     }
 }
index c2bf679..3c1233a 100644 (file)
@@ -7,6 +7,6 @@ namespace System.Runtime.Serialization
     public interface ISerializationSurrogate
     {
         void GetObjectData(object obj, SerializationInfo info, StreamingContext context);
-        object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector);
+        object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector? selector);
     }
 }
index 3ec0715..e67764b 100644 (file)
@@ -7,7 +7,7 @@ namespace System.Runtime.Serialization
     public interface ISurrogateSelector
     {
         void ChainSelector(ISurrogateSelector selector);
-        ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector);
-        ISurrogateSelector GetNextSelector();
+        ISerializationSurrogate? GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector);
+        ISurrogateSelector? GetNextSelector();
     }
 }
index 12ed50c..42991a4 100644 (file)
@@ -8,7 +8,7 @@ namespace System.Runtime.Serialization
 {
     internal sealed class MemberHolder
     {
-        internal readonly MemberInfo[] _members = null;
+        internal readonly MemberInfo[]? _members = null;
         internal readonly Type _memberType;
         internal readonly StreamingContext _context;
 
@@ -20,11 +20,9 @@ namespace System.Runtime.Serialization
 
         public override int GetHashCode() => _memberType.GetHashCode();
 
-        public override bool Equals(object obj)
+        public override bool Equals(object? obj)
         {
-            var mh = obj as MemberHolder;
-            return
-                mh != null &&
+            return obj is MemberHolder mh &&
                 ReferenceEquals(mh._memberType, _memberType) &&
                 mh._context.State == _context.State;
         }
index 251749f..18a5456 100644 (file)
@@ -5,6 +5,7 @@
 using System.Diagnostics;
 using System.Reflection;
 using System.Globalization;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Runtime.Serialization
 {
@@ -15,26 +16,26 @@ namespace System.Runtime.Serialization
         private const int ArrayMask = MaxArraySize - 1;
         private const int MaxReferenceDepth = 100;
 
-        private DeserializationEventHandler _onDeserializationHandler;
-        private SerializationEventHandler _onDeserializedHandler;
+        private DeserializationEventHandler? _onDeserializationHandler;
+        private SerializationEventHandler? _onDeserializedHandler;
 
         internal ObjectHolder[] _objects;
-        internal object _topObject = null;
-        internal ObjectHolderList _specialFixupObjects; //This is IObjectReference, ISerializable, or has a Surrogate.
+        internal object? _topObject = null;
+        internal ObjectHolderList? _specialFixupObjects; //This is IObjectReference, ISerializable, or has a Surrogate.
         internal long _fixupCount;
-        internal readonly ISurrogateSelector _selector;
+        internal readonly ISurrogateSelector? _selector;
         internal readonly StreamingContext _context;
 
-        public ObjectManager(ISurrogateSelector selector, StreamingContext context)
+        public ObjectManager(ISurrogateSelector? selector, StreamingContext context)
         {
             _objects = new ObjectHolder[DefaultInitialSize];
             _selector = selector;
             _context = context;
         }
 
-        private bool CanCallGetType(object obj) => true;
+        private bool CanCallGetType(object? obj) => true;
 
-        internal object TopObject
+        internal object? TopObject
         {
             get { return _topObject; }
             set { _topObject = value; }
@@ -43,7 +44,7 @@ namespace System.Runtime.Serialization
         internal ObjectHolderList SpecialFixupObjects =>
             _specialFixupObjects ?? (_specialFixupObjects = new ObjectHolderList());
 
-        internal ObjectHolder FindObjectHolder(long objectID)
+        internal ObjectHolder? FindObjectHolder(long objectID)
         {
             // The  index of the bin in which we live is rightmost n bits of the objectID.
             int index = (int)(objectID & ArrayMask);
@@ -53,7 +54,7 @@ namespace System.Runtime.Serialization
             }
 
             // Find the bin in which we live.
-            ObjectHolder temp = _objects[index];
+            ObjectHolder? temp = _objects[index];
 
             // Walk the chain in that bin.  Return the ObjectHolder if we find it, otherwise
             // return null.
@@ -71,8 +72,7 @@ namespace System.Runtime.Serialization
 
         internal ObjectHolder FindOrCreateObjectHolder(long objectID)
         {
-            ObjectHolder holder;
-            holder = FindObjectHolder(objectID);
+            ObjectHolder? holder = FindObjectHolder(objectID);
             if (holder == null)
             {
                 holder = new ObjectHolder(objectID);
@@ -125,7 +125,7 @@ namespace System.Runtime.Serialization
             _objects[index] = holder;
         }
 
-        private bool GetCompletionInfo(FixupHolder fixup, out ObjectHolder holder, out object member, bool bThrowIfMissing)
+        private bool GetCompletionInfo(FixupHolder fixup, [NotNullWhen(true)] out ObjectHolder? holder, out object member, bool bThrowIfMissing)
         {
             //Set the member id (String or MemberInfo) for the member being fixed up.
             member = fixup._fixupInfo;
@@ -133,18 +133,6 @@ namespace System.Runtime.Serialization
             //Find the object required for the fixup.  Throw if we can't find it.
             holder = FindObjectHolder(fixup._id);
 
-            // CompletelyFixed is our poorly named property which indicates if something requires a SerializationInfo fixup
-            // or is an incomplete object reference.  We have this particular branch to handle valuetypes which implement
-            // ISerializable.  In that case, we can't do any fixups on them later, so we need to delay the fixups further.
-            if (!holder.CompletelyFixed)
-            {
-                if (holder.ObjectValue != null && holder.ObjectValue is ValueType)
-                {
-                    SpecialFixupObjects.Add(holder);
-                    return false;
-                }
-            }
-
             if (holder == null || holder.CanObjectValueChange || holder.ObjectValue == null)
             {
                 if (bThrowIfMissing)
@@ -161,19 +149,33 @@ namespace System.Runtime.Serialization
                 }
                 return false;
             }
+
+            // CompletelyFixed is our poorly named property which indicates if something requires a SerializationInfo fixup
+            // or is an incomplete object reference.  We have this particular branch to handle valuetypes which implement
+            // ISerializable.  In that case, we can't do any fixups on them later, so we need to delay the fixups further.
+            if (!holder.CompletelyFixed)
+            {
+                if (holder.ObjectValue != null && holder.ObjectValue is ValueType)
+                {
+                    SpecialFixupObjects.Add(holder);
+                    return false;
+                }
+            }
+
             return true;
         }
 
         private void FixupSpecialObject(ObjectHolder holder)
         {
-            ISurrogateSelector uselessSelector = null;
+            ISurrogateSelector? uselessSelector = null;
 
             Debug.Assert(holder.RequiresSerInfoFixup, "[ObjectManager.FixupSpecialObject]holder.HasSurrogate||holder.HasISerializable");
             if (holder.HasSurrogate)
             {
-                ISerializationSurrogate surrogate = holder.Surrogate;
+                ISerializationSurrogate? surrogate = holder.Surrogate;
                 Debug.Assert(surrogate != null, "surrogate!=null");
-                object returnValue = surrogate.SetObjectData(holder.ObjectValue, holder.SerializationInfo, _context, uselessSelector);
+                Debug.Assert(holder.SerializationInfo != null);
+                object? returnValue = surrogate.SetObjectData(holder.ObjectValue!, holder.SerializationInfo, _context, uselessSelector);
                 if (returnValue != null)
                 {
                     if (!holder.CanSurrogatedObjectValueChange && returnValue != holder.ObjectValue)
@@ -214,7 +216,7 @@ namespace System.Runtime.Serialization
         /// <param name="holder"></param>
         private bool ResolveObjectReference(ObjectHolder holder)
         {
-            object tempObject;
+            object? tempObject;
             Debug.Assert(holder.IsIncompleteObjectReference, "holder.IsIncompleteObjectReference");
 
             //In the pathological case, an Object implementing IObjectReference could return a reference
@@ -234,6 +236,7 @@ namespace System.Runtime.Serialization
                 do
                 {
                     tempObject = holder.ObjectValue;
+                    Debug.Assert(holder.ObjectValue != null);
                     holder.SetObjectValue(((IObjectReference)(holder.ObjectValue)).GetRealObject(_context), this);
                     //The object didn't yet have enough information to resolve the reference, so we'll
                     //return false and the graph walker should call us back again after more objects have
@@ -265,15 +268,14 @@ namespace System.Runtime.Serialization
         ** holder -- the ObjectHolder for the object (a value type in this case) being completed.
         ** value  -- the data to set into the field.
         ==============================================================================*/
-        private bool DoValueTypeFixup(FieldInfo memberToFix, ObjectHolder holder, object value)
+        private bool DoValueTypeFixup(FieldInfo? memberToFix, ObjectHolder holder, object? value)
         {
             var fieldsTemp = new FieldInfo[4];
-            FieldInfo[] fields = null;
+            FieldInfo[] fields;
             int currentFieldIndex = 0;
-            int[] arrayIndex = null;
-            ValueTypeFixupInfo currFixup = null;
-            object fixupObj = holder.ObjectValue;
-            ObjectHolder originalHolder = holder;
+            int[]? arrayIndex = null;
+            ValueTypeFixupInfo currFixup;
+            object? fixupObj = holder.ObjectValue;
 
             Debug.Assert(holder != null, "[TypedReferenceBuilder.ctor]holder!=null");
             Debug.Assert(holder.RequiresValueTypeFixup, "[TypedReferenceBuilder.ctor]holder.RequiresValueTypeFixup");
@@ -297,20 +299,21 @@ namespace System.Runtime.Serialization
                 //object that we have.  In most cases, we could have just grabbed it after this loop finished.
                 //However, if the outermost containing object is an array, we need the object one further
                 //down the chain, so we have to do a lot of caching.
-                currFixup = holder.ValueFixup;
+                currFixup = holder.ValueFixup!;
                 fixupObj = holder.ObjectValue;  //Save the most derived
                 if (currFixup.ParentField != null)
                 {
                     FieldInfo parentField = currFixup.ParentField;
 
-                    ObjectHolder tempHolder = FindObjectHolder(currFixup.ContainerID);
+                    ObjectHolder? tempHolder = FindObjectHolder(currFixup.ContainerID);
+                    Debug.Assert(tempHolder != null);
                     if (tempHolder.ObjectValue == null)
                     {
                         break;
                     }
                     if (Nullable.GetUnderlyingType(parentField.FieldType) != null)
                     {
-                        fieldsTemp[currentFieldIndex] = parentField.FieldType.GetField(nameof(value), BindingFlags.NonPublic | BindingFlags.Instance);
+                        fieldsTemp[currentFieldIndex] = parentField.FieldType.GetField(nameof(value), BindingFlags.NonPublic | BindingFlags.Instance)!;
                         currentFieldIndex++;
                     }
 
@@ -322,7 +325,7 @@ namespace System.Runtime.Serialization
                 {
                     //If we find an index into an array, save that information.
                     Debug.Assert(currFixup.ParentIndex != null, "[ObjectManager.DoValueTypeFixup]currFixup.ParentIndex!=null");
-                    holder = FindObjectHolder(currFixup.ContainerID); //find the array to fix.
+                    holder = FindObjectHolder(currFixup.ContainerID)!; //find the array to fix.
                     arrayIndex = currFixup.ParentIndex;
                     break;
                 }
@@ -345,8 +348,8 @@ namespace System.Runtime.Serialization
                 fields = new FieldInfo[currentFieldIndex];
                 for (int i = 0; i < currentFieldIndex; i++)
                 {
-                    FieldInfo fieldInfo = fieldsTemp[(currentFieldIndex - 1 - i)];
-                    SerializationFieldInfo serInfo = fieldInfo as SerializationFieldInfo;
+                    FieldInfo? fieldInfo = fieldsTemp[(currentFieldIndex - 1 - i)];
+                    SerializationFieldInfo? serInfo = fieldInfo as SerializationFieldInfo;
                     fields[i] = serInfo == null ? fieldInfo : serInfo.FieldInfo;
                 }
 
@@ -355,7 +358,7 @@ namespace System.Runtime.Serialization
                 TypedReference typedRef = TypedReference.MakeTypedReference(fixupObj, fields);
                 if (memberToFix != null)
                 {
-                    memberToFix.SetValueDirect(typedRef, value);
+                    memberToFix.SetValueDirect(typedRef, value!);
                 }
                 else
                 {
@@ -379,11 +382,11 @@ namespace System.Runtime.Serialization
 
         internal void CompleteObject(ObjectHolder holder, bool bObjectFullyComplete)
         {
-            FixupHolderList fixups = holder._missingElements;
-            FixupHolder currentFixup;
-            SerializationInfo si;
-            object fixupInfo = null;
-            ObjectHolder tempObjectHolder = null;
+            FixupHolderList? fixups = holder._missingElements;
+            FixupHolder? currentFixup;
+            SerializationInfo? si;
+            object? fixupInfo = null;
+            ObjectHolder? tempObjectHolder = null;
             int fixupsPerformed = 0;
 
             Debug.Assert(holder != null, "[ObjectManager.CompleteObject]holder.m_object!=null");
@@ -415,12 +418,13 @@ namespace System.Runtime.Serialization
                         {
                             continue;
                         }
-                        Debug.Assert(fixups._values[i]._fixupType == FixupHolder.DelayedFixup, "fixups.m_values[i].m_fixupType==FixupHolder.DelayedFixup");
-                        if (GetCompletionInfo(fixups._values[i], out tempObjectHolder, out fixupInfo, bObjectFullyComplete))
+                        Debug.Assert(fixups._values[i]!._fixupType == FixupHolder.DelayedFixup, "fixups.m_values[i].m_fixupType==FixupHolder.DelayedFixup");
+                        if (GetCompletionInfo(fixups._values[i]!, out tempObjectHolder, out fixupInfo, bObjectFullyComplete))
                         {
                             //Walk the SerializationInfo and find the member needing completion.  All we have to do
                             //at this point is set the member into the Object
-                            object holderValue = tempObjectHolder.ObjectValue;
+                            object? holderValue = tempObjectHolder.ObjectValue;
+                            Debug.Assert(holderValue != null);
                             if (CanCallGetType(holderValue))
                             {
                                 si.UpdateValue((string)fixupInfo, holderValue, holderValue.GetType());
@@ -461,7 +465,7 @@ namespace System.Runtime.Serialization
                             // throw an exception with the type name
                             if (holder.Reachable)
                             {
-                                throw new SerializationException(SR.Format(SR.Serialization_TypeLoadFailure, holder.TypeLoadException.TypeName));
+                                throw new SerializationException(SR.Format(SR.Serialization_TypeLoadFailure, holder.TypeLoadException!.TypeName));
                             }
                         }
 
@@ -539,7 +543,7 @@ namespace System.Runtime.Serialization
 
             _fixupCount -= fixupsPerformed;
 
-            if (fixups._count == fixupsPerformed)
+            if (fixups!._count == fixupsPerformed)
             {
                 holder._missingElements = null;
             }
@@ -560,7 +564,7 @@ namespace System.Runtime.Serialization
             }
 
             //If we don't have any dependencies, we're done.
-            LongList dependencies = holder.DependentObjects;
+            LongList? dependencies = holder.DependentObjects;
             if (dependencies == null)
             {
                 return;
@@ -572,7 +576,8 @@ namespace System.Runtime.Serialization
             dependencies.StartEnumeration();
             while (dependencies.MoveNext())
             {
-                ObjectHolder temp = FindObjectHolder(dependencies.Current);
+                ObjectHolder? temp = FindObjectHolder(dependencies.Current);
+                Debug.Assert(temp != null);
                 Debug.Assert(temp.DirectlyDependentObjects > 0, "temp.m_missingElementsRemaining>0");
                 temp.DecrementFixupsRemaining(this);
                 if (((temp.DirectlyDependentObjects)) == 0)
@@ -591,7 +596,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        public virtual object GetObject(long objectID)
+        public virtual object? GetObject(long objectID)
         {
             if (objectID <= 0)
             {
@@ -600,7 +605,7 @@ namespace System.Runtime.Serialization
 
             //Find the bin in which we're interested.  IObjectReference's shouldn't be returned -- the graph
             //needs to link to the objects to which they refer, not to the references themselves.
-            ObjectHolder holder = FindObjectHolder(objectID);
+            ObjectHolder? holder = FindObjectHolder(objectID);
             if (holder == null || holder.CanObjectValueChange)
             {
                 return null;
@@ -619,22 +624,22 @@ namespace System.Runtime.Serialization
             RegisterObject(obj, objectID, info, 0, null);
         }
 
-        public void RegisterObject(object obj, long objectID, SerializationInfo info, long idOfContainingObj, MemberInfo member)
+        public void RegisterObject(object obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member)
         {
             RegisterObject(obj, objectID, info, idOfContainingObj, member, null);
         }
 
-        internal void RegisterString(string obj, long objectID, SerializationInfo info, long idOfContainingObj, MemberInfo member)
+        internal void RegisterString(string? obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member)
         {
             ObjectHolder temp;
             Debug.Assert(member == null || member is FieldInfo, "RegisterString - member is FieldInfo");
 
-            temp = new ObjectHolder(obj, objectID, info, null, idOfContainingObj, (FieldInfo)member, null);
+            temp = new ObjectHolder(obj, objectID, info, null, idOfContainingObj, (FieldInfo?)member, null);
             AddObjectHolder(temp);
             return;
         }
 
-        public void RegisterObject(object obj, long objectID, SerializationInfo info, long idOfContainingObj, MemberInfo member, int[] arrayIndex)
+        public void RegisterObject(object obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member, int[]? arrayIndex)
         {
             if (obj == null)
             {
@@ -649,8 +654,8 @@ namespace System.Runtime.Serialization
                 throw new SerializationException(SR.Serialization_UnknownMemberInfo);
             }
 
-            ObjectHolder temp;
-            ISerializationSurrogate surrogate = null;
+            ObjectHolder? temp;
+            ISerializationSurrogate? surrogate = null;
             ISurrogateSelector useless;
 
             if (_selector != null)
@@ -681,7 +686,7 @@ namespace System.Runtime.Serialization
             temp = FindObjectHolder(objectID);
             if (temp == null)
             {
-                temp = new ObjectHolder(obj, objectID, info, surrogate, idOfContainingObj, (FieldInfo)member, arrayIndex);
+                temp = new ObjectHolder(obj, objectID, info, surrogate, idOfContainingObj, (FieldInfo?)member, arrayIndex);
                 AddObjectHolder(temp);
                 if (temp.RequiresDelayedFixup)
                 {
@@ -700,7 +705,7 @@ namespace System.Runtime.Serialization
             }
 
             //Complete the data in the ObjectHolder
-            temp.UpdateData(obj, info, surrogate, idOfContainingObj, (FieldInfo)member, arrayIndex, this);
+            temp.UpdateData(obj, info, surrogate, idOfContainingObj, (FieldInfo?)member, arrayIndex, this);
 
             // The following case will only be true when somebody has registered a fixup on an object before
             // registering the object itself.  I don't believe that most well-behaved formatters will do this,
@@ -746,7 +751,7 @@ namespace System.Runtime.Serialization
         /// <param name="obj">The object to be completed.</param>
         /// <param name="info">The SerializationInfo containing all info for obj.</param>
         /// <param name="context">The streaming context in which the serialization is taking place.</param>
-        internal void CompleteISerializableObject(object obj, SerializationInfo info, StreamingContext context)
+        internal void CompleteISerializableObject(object obj, SerializationInfo? info, StreamingContext context)
         {
             if (obj == null)
             {
@@ -757,7 +762,7 @@ namespace System.Runtime.Serialization
                 throw new ArgumentException(SR.Serialization_NotISer);
             }
 
-            ConstructorInfo constInfo = null;
+            ConstructorInfo constInfo;
             Type t = obj.GetType();
             try
             {
@@ -768,7 +773,7 @@ namespace System.Runtime.Serialization
                 throw new SerializationException(SR.Format(SR.Serialization_ConstructorNotFound, t), e);
             }
 
-            constInfo.Invoke(obj, new object[] { info, context });
+            constInfo.Invoke(obj, new object?[] { info, context });
         }
 
         internal static ConstructorInfo GetDeserializationConstructor(Type t)
@@ -790,7 +795,7 @@ namespace System.Runtime.Serialization
 
         public virtual void DoFixups()
         {
-            ObjectHolder temp;
+            ObjectHolder? temp;
             int fixupCount = -1;
 
             //The first thing that we need to do is fixup all of the objects which implement
@@ -1001,19 +1006,19 @@ namespace System.Runtime.Serialization
         internal const int SER_INFO_FIXED = 0x4000;
         internal const int VALUETYPE_FIXUP_PERFORMED = 0x8000;
 
-        private object _object;
+        private object? _object;
         internal readonly long _id;
         private int _missingElementsRemaining;
         private int _missingDecendents;
-        internal SerializationInfo _serInfo;
-        internal ISerializationSurrogate _surrogate;
-        internal FixupHolderList _missingElements;
-        internal LongList _dependentObjects;
-        internal ObjectHolder _next;
+        internal SerializationInfo? _serInfo;
+        internal ISerializationSurrogate? _surrogate;
+        internal FixupHolderList? _missingElements;
+        internal LongList? _dependentObjects;
+        internal ObjectHolder? _next;
         internal int _flags;
         private bool _markForFixupWhenAvailable;
-        private ValueTypeFixupInfo _valueFixup;
-        private TypeLoadExceptionHolder _typeLoad = null;
+        private ValueTypeFixupInfo? _valueFixup;
+        private TypeLoadExceptionHolder? _typeLoad = null;
         private bool _reachable = false;
 
         internal ObjectHolder(long objID) : this(null, objID, null, null, 0, null, null)
@@ -1021,8 +1026,8 @@ namespace System.Runtime.Serialization
         }
 
         internal ObjectHolder(
-            object obj, long objID, SerializationInfo info, ISerializationSurrogate surrogate,
-            long idOfContainingObj, FieldInfo field, int[] arrayIndex)
+            object? obj, long objID, SerializationInfo? info, ISerializationSurrogate? surrogate,
+            long idOfContainingObj, FieldInfo? field, int[]? arrayIndex)
         {
             Debug.Assert(objID >= 0, "objID>=0");
 
@@ -1058,8 +1063,8 @@ namespace System.Runtime.Serialization
         }
 
         internal ObjectHolder(
-            string obj, long objID, SerializationInfo info, ISerializationSurrogate surrogate,
-            long idOfContainingObj, FieldInfo field, int[] arrayIndex)
+            string? obj, long objID, SerializationInfo? info, ISerializationSurrogate? surrogate,
+            long idOfContainingObj, FieldInfo? field, int[]? arrayIndex)
         {
             Debug.Assert(objID >= 0, "objID>=0");
 
@@ -1183,8 +1188,8 @@ namespace System.Runtime.Serialization
         /// <param name="surrogate">The surrogate handling this object.  May be null.</param>
         /// <param name="idOfContainer">The id of the object containing this one if this is a valuetype.</param>
         internal void UpdateData(
-            object obj, SerializationInfo info, ISerializationSurrogate surrogate, long idOfContainer,
-            FieldInfo field, int[] arrayIndex, ObjectManager manager)
+            object obj, SerializationInfo? info, ISerializationSurrogate? surrogate, long idOfContainer,
+            FieldInfo? field, int[]? arrayIndex, ObjectManager manager)
         {
             Debug.Assert(obj != null, "obj!=null");
             Debug.Assert(_id > 0, "m_id>0");
@@ -1302,11 +1307,11 @@ namespace System.Runtime.Serialization
 
         internal bool TypeLoadExceptionReachable => _typeLoad != null;
 
-        internal TypeLoadExceptionHolder TypeLoadException { get { return _typeLoad; } set { _typeLoad = value; } }
+        internal TypeLoadExceptionHolder? TypeLoadException { get { return _typeLoad; } set { _typeLoad = value; } }
 
-        internal object ObjectValue => _object;
+        internal object? ObjectValue => _object;
 
-        internal void SetObjectValue(object obj, ObjectManager manager)
+        internal void SetObjectValue(object? obj, ObjectManager manager)
         {
             _object = obj;
             if (obj == manager.TopObject)
@@ -1324,11 +1329,11 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal SerializationInfo SerializationInfo { get { return _serInfo; } set { _serInfo = value; } }
+        internal SerializationInfo? SerializationInfo { get { return _serInfo; } set { _serInfo = value; } }
 
-        internal ISerializationSurrogate Surrogate => _surrogate;
+        internal ISerializationSurrogate? Surrogate => _surrogate;
 
-        internal LongList DependentObjects { get { return _dependentObjects; } set { _dependentObjects = value; } }
+        internal LongList? DependentObjects { get { return _dependentObjects; } set { _dependentObjects = value; } }
 
         internal bool RequiresSerInfoFixup
         {
@@ -1354,7 +1359,7 @@ namespace System.Runtime.Serialization
             }
         }
 
-        internal ValueTypeFixupInfo ValueFixup => _valueFixup;
+        internal ValueTypeFixupInfo? ValueFixup => _valueFixup;
 
         internal bool CompletelyFixed => !RequiresSerInfoFixup && !IsIncompleteObjectReference;
 
@@ -1387,7 +1392,7 @@ namespace System.Runtime.Serialization
     {
         internal const int InitialSize = 2;
 
-        internal FixupHolder[] _values;
+        internal FixupHolder?[] _values;
         internal int _count;
 
         internal FixupHolderList() : this(InitialSize)
@@ -1599,19 +1604,19 @@ namespace System.Runtime.Serialization
 
     public sealed class TypeLoadExceptionHolder
     {
-        internal TypeLoadExceptionHolder(string typeName)
+        internal TypeLoadExceptionHolder(string? typeName)
         {
             TypeName = typeName;
         }
 
-        internal string TypeName { get; }
+        internal string? TypeName { get; }
     }
 
     internal static class SerializationInfoExtensions
     {
         private static readonly Action<SerializationInfo, string, object, Type> s_updateValue =
             (Action<SerializationInfo, string, object, Type>)typeof(SerializationInfo)
-            .GetMethod("UpdateValue", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
+            .GetMethod("UpdateValue", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)!
             .CreateDelegate(typeof(Action<SerializationInfo, string, object, Type>));
 
         public static void UpdateValue(this SerializationInfo si, string name, object value, Type type) =>
index 6a8adca..9444ae4 100644 (file)
@@ -6,12 +6,12 @@ namespace System.Runtime.Serialization
 {
     public abstract class SerializationBinder
     {
-        public virtual void BindToName(Type serializedType, out string assemblyName, out string typeName)
+        public virtual void BindToName(Type serializedType, out string? assemblyName, out string? typeName)
         {
             assemblyName = null;
             typeName = null;
         }
 
-        public abstract Type BindToType(string assemblyName, string typeName);
+        public abstract Type? BindToType(string assemblyName, string typeName);
     }
 }
index 896afe1..bd194c3 100644 (file)
@@ -11,12 +11,12 @@ namespace System.Runtime.Serialization
 {
     internal sealed class SerializationEvents
     {
-        private readonly List<MethodInfo> _onSerializingMethods;
-        private readonly List<MethodInfo> _onSerializedMethods;
-        private readonly List<MethodInfo> _onDeserializingMethods;
-        private readonly List<MethodInfo> _onDeserializedMethods;
+        private readonly List<MethodInfo>? _onSerializingMethods;
+        private readonly List<MethodInfo>? _onSerializedMethods;
+        private readonly List<MethodInfo>? _onDeserializingMethods;
+        private readonly List<MethodInfo>? _onDeserializedMethods;
 
-        internal SerializationEvents(Type t)
+        internal SerializationEvents(Type? t)
         {
             _onSerializingMethods = GetMethodsWithAttribute(typeof(OnSerializingAttribute), t);
             _onSerializedMethods = GetMethodsWithAttribute(typeof(OnSerializedAttribute), t);
@@ -24,12 +24,12 @@ namespace System.Runtime.Serialization
             _onDeserializedMethods = GetMethodsWithAttribute(typeof(OnDeserializedAttribute), t);
         }
 
-        private List<MethodInfo> GetMethodsWithAttribute(Type attribute, Type t)
+        private List<MethodInfo>? GetMethodsWithAttribute(Type attribute, Type? t)
         {
-            List<MethodInfo> mi = null;
+            List<MethodInfo>? mi = null;
 
             // Traverse the hierarchy to find all methods with the particular attribute
-            Type baseType = t;
+            Type? baseType = t;
             while (baseType != null && baseType != typeof(object))
             {
                 // Get all methods which are declared on this type, instance and public or nonpublic
@@ -62,21 +62,21 @@ namespace System.Runtime.Serialization
         internal void InvokeOnDeserialized(object obj, StreamingContext context) =>
             InvokeOnDelegate(obj, context, _onDeserializedMethods);
 
-        internal SerializationEventHandler AddOnSerialized(object obj, SerializationEventHandler handler) =>
+        internal SerializationEventHandler? AddOnSerialized(object obj, SerializationEventHandler? handler) =>
             AddOnDelegate(obj, handler, _onSerializedMethods);
 
-        internal SerializationEventHandler AddOnDeserialized(object obj, SerializationEventHandler handler) =>
+        internal SerializationEventHandler? AddOnDeserialized(object obj, SerializationEventHandler? handler) =>
             AddOnDelegate(obj, handler, _onDeserializedMethods);
 
         /// <summary>Invoke all methods.</summary>
-        private static void InvokeOnDelegate(object obj, StreamingContext context, List<MethodInfo> methods)
+        private static void InvokeOnDelegate(object obj, StreamingContext context, List<MethodInfo>? methods)
         {
             Debug.Assert(obj != null, "object should have been initialized");
             AddOnDelegate(obj, null, methods)?.Invoke(context);
         }
 
         /// <summary>Add all methods to a delegate.</summary>
-        private static SerializationEventHandler AddOnDelegate(object obj, SerializationEventHandler handler, List<MethodInfo> methods)
+        private static SerializationEventHandler? AddOnDelegate(object obj, SerializationEventHandler? handler, List<MethodInfo>? methods)
         {
             if (methods != null)
             {
index 582a31f..c994b5c 100644 (file)
@@ -33,9 +33,9 @@ namespace System.Runtime.Serialization
 
         public override int MetadataToken { get { return m_field.MetadataToken; } }
 
-        public override Type DeclaringType => m_field.DeclaringType;
+        public override Type? DeclaringType => m_field.DeclaringType;
 
-        public override Type ReflectedType => m_field.ReflectedType;
+        public override Type? ReflectedType => m_field.ReflectedType;
 
         public override object[] GetCustomAttributes(bool inherit) => m_field.GetCustomAttributes(inherit);
 
@@ -45,9 +45,9 @@ namespace System.Runtime.Serialization
 
         public override Type FieldType => m_field.FieldType;
 
-        public override object GetValue(object obj) => m_field.GetValue(obj);
+        public override object? GetValue(object? obj) => m_field.GetValue(obj);
 
-        public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) => m_field.SetValue(obj, value, invokeAttr, binder, culture);
+        public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture) => m_field.SetValue(obj, value, invokeAttr, binder, culture);
 
         public override RuntimeFieldHandle FieldHandle => m_field.FieldHandle;
 
index def16b6..a71523f 100644 (file)
@@ -10,7 +10,7 @@ namespace System.Runtime.Serialization
     {
         private readonly Dictionary<object, object> _objectSeenTable; // Table to keep track of objects [OnSerializing] has been called on
         private readonly StreamingContext _context;
-        private SerializationEventHandler _onSerializedHandler;
+        private SerializationEventHandler? _onSerializedHandler;
 
         public SerializationObjectManager(StreamingContext context)
         {
index 626ab40..0b73a24 100644 (file)
@@ -10,7 +10,7 @@ namespace System.Runtime.Serialization
     public class SurrogateSelector : ISurrogateSelector
     {
         internal readonly SurrogateHashtable _surrogates = new SurrogateHashtable(32);
-        internal ISurrogateSelector _nextSelector;
+        internal ISurrogateSelector? _nextSelector;
 
         public virtual void AddSurrogate(Type type, StreamingContext context, ISerializationSurrogate surrogate)
         {
@@ -31,7 +31,7 @@ namespace System.Runtime.Serialization
         {
             Debug.Assert(selector != null, "[HasCycle]selector!=null");
 
-            ISurrogateSelector head = selector, tail = selector;
+            ISurrogateSelector? head = selector, tail = selector;
             while (head != null)
             {
                 head = head.GetNextSelector();
@@ -44,7 +44,7 @@ namespace System.Runtime.Serialization
                     return false;
                 }
                 head = head.GetNextSelector();
-                tail = tail.GetNextSelector();
+                tail = tail!.GetNextSelector();
 
                 if (head == tail)
                 {
@@ -78,7 +78,7 @@ namespace System.Runtime.Serialization
 
             // Check for a cycle that would lead back to this.  We find the end of the list that we're being asked to
             // insert for use later.
-            ISurrogateSelector tempCurr = selector.GetNextSelector();
+            ISurrogateSelector? tempCurr = selector.GetNextSelector();
             ISurrogateSelector tempEnd = selector;
             while (tempCurr != null && tempCurr != this)
             {
@@ -92,7 +92,7 @@ namespace System.Runtime.Serialization
 
             // Check for a cycle later in the list which would be introduced by this insertion.
             tempCurr = selector;
-            ISurrogateSelector tempPrev = selector;
+            ISurrogateSelector? tempPrev = selector;
             while (tempCurr != null)
             {
                 if (tempCurr == tempEnd)
@@ -128,6 +128,7 @@ namespace System.Runtime.Serialization
                 }
                 else
                 {
+                    Debug.Assert(tempPrev != null);
                     tempPrev = tempPrev.GetNextSelector();
                 }
                 if (tempCurr == tempPrev)
@@ -137,7 +138,7 @@ namespace System.Runtime.Serialization
             }
 
             // Add the new selector and it's entire chain of selectors as the next thing that we check.
-            ISurrogateSelector temp = _nextSelector;
+            ISurrogateSelector? temp = _nextSelector;
             _nextSelector = selector;
             if (temp != null)
             {
@@ -146,11 +147,11 @@ namespace System.Runtime.Serialization
         }
 
         // Get the next selector on the chain of selectors.
-        public virtual ISurrogateSelector GetNextSelector() => _nextSelector;
+        public virtual ISurrogateSelector? GetNextSelector() => _nextSelector;
 
         // Gets the surrogate for a particular type.  If this selector can't
         // provide a surrogate, it checks with all of it's children before returning null.
-        public virtual ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector)
+        public virtual ISerializationSurrogate? GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector)
         {
             if (type == null)
             {
@@ -160,7 +161,7 @@ namespace System.Runtime.Serialization
             selector = this;
 
             SurrogateKey key = new SurrogateKey(type, context);
-            ISerializationSurrogate temp = (ISerializationSurrogate)_surrogates[key];
+            ISerializationSurrogate? temp = (ISerializationSurrogate?)_surrogates[key];
             if (temp != null)
             {
                 return temp;
@@ -212,7 +213,9 @@ namespace System.Runtime.Serialization
         // is a subset of the context for which the serialization selector is provided (presentContext)
         // Note: This is done by overriding KeyEquals rather than overriding Equals() in the SurrogateKey
         // class because Equals() method must be commutative.
+#pragma warning disable CS8610
         protected override bool KeyEquals(object key, object item)
+#pragma warning restore CS8610
         {
             SurrogateKey givenValue = (SurrogateKey)item;
             SurrogateKey presentValue = (SurrogateKey)key;
index 87053a0..f4f0f1c 100644 (file)
@@ -21,15 +21,15 @@ namespace System.Runtime.Serialization
         /// apply if the containing body is a field info or another
         /// value type.
         /// </summary>
-        private readonly FieldInfo _parentField;
+        private readonly FieldInfo? _parentField;
 
         /// <summary>
         /// The array index of the index into the parent.  This will only
         /// apply if the containing body is an array.
         /// </summary>
-        private readonly int[] _parentIndex;
+        private readonly int[]? _parentIndex;
 
-        public ValueTypeFixupInfo(long containerID, FieldInfo member, int[] parentIndex)
+        public ValueTypeFixupInfo(long containerID, FieldInfo? member, int[]? parentIndex)
         {
             // If both member and arrayIndex are null, we don't have enough information to create
             // a tunnel to do the fixup.
@@ -67,8 +67,8 @@ namespace System.Runtime.Serialization
 
         public long ContainerID => _containerID;
 
-        public FieldInfo ParentField => _parentField;
+        public FieldInfo? ParentField => _parentField;
 
-        public int[] ParentIndex => _parentIndex;
+        public int[]? ParentIndex => _parentIndex;
     }
 }