Merge pull request #35319 from krwq/nullable-xml-1
authorKrzysztof Wicher <mordotymoja@gmail.com>
Mon, 27 Apr 2020 17:51:31 +0000 (10:51 -0700)
committerGitHub <noreply@github.com>
Mon, 27 Apr 2020 17:51:31 +0000 (10:51 -0700)
Nullable: System.Xml, part 1

41 files changed:
src/libraries/System.Private.Xml/src/Misc/HResults.cs
src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/BinXmlToken.cs
src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/SqlUtils.cs
src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/CharEntityEncoderFallback.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/ConformanceLevel.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/DtdProcessing.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/EntityHandling.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlTernaryTree.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdInfo.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParser.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAdapter.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAdapterAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/NewLineHandling.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/ReadState.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/ValidationType.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/WhitespaceHandling.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlParserContext.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSpace.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReaderAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpers.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/IXmlLineInfo.cs
src/libraries/System.Private.Xml/src/System/Xml/IXmlNamespaceResolver.cs
src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs
src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManager.cs
src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs
src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs
src/libraries/System.Private.Xml/src/System/Xml/XmlNameTable.cs
src/libraries/System.Private.Xml/src/System/Xml/XmlNamespacemanager.cs
src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs
src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolver.cs
src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs

index 8432621..2208da6 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.
 
+#nullable enable
 /*
 These HRESULTs are used for mapping managed exceptions to COM error codes
 and vice versa through COM Interop.  For background on COM error codes see
index a6a2f96..ebfd45d 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.
 
+#nullable enable
 using System;
 using System.Collections;
 using System.IO;
@@ -81,4 +82,4 @@ namespace System.Xml
         XSD_UNSIGNEDLONG = 0x8B,
         XSD_QNAME = 0x8C,
     }
-}
\ No newline at end of file
+}
index cd38dc9..b0542a0 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.
 
+#nullable enable
 using System;
 using System.Collections;
 using System.IO;
@@ -46,7 +47,7 @@ namespace System.Xml
                 11 => 2,
                 15 => 3,
                 19 => 4,
-                _ => throw new XmlException(SR.XmlBinary_InvalidSqlDecimal, (string[])null),
+                _ => throw new XmlException(SR.XmlBinary_InvalidSqlDecimal, (string[]?)null),
             };
             m_bPrec = data[offset + 1];
             m_bScale = data[offset + 2];
@@ -109,6 +110,7 @@ namespace System.Xml
             iulR = ulCarry;
             MpNormalize(rgulU, ref ciulU);
         }
+
         // Normalize multi-precision number - remove leading zeroes
         private static void MpNormalize(uint[] rgulU,      // In   | Number
                                         ref int ciulU       // InOut| # of digits
@@ -131,6 +133,7 @@ namespace System.Xml
         private static ReadOnlySpan<byte> RgCLenFromPrec => new byte[] { // rely on C# compiler optimization to eliminate allocation
             1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4
         };
+
         private static byte CLenFromPrec(byte bPrec)
         {
             Debug.Assert(bPrec <= s_maxPrecision && bPrec > 0, "bPrec <= MaxPrecision && bPrec > 0", "Invalid numeric precision");
@@ -146,7 +149,7 @@ namespace System.Xml
         public decimal ToDecimal()
         {
             if ((int)m_data4 != 0 || m_bScale > 28)
-                throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+                throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
 
             return new decimal((int)m_data1, (int)m_data2, (int)m_data3, !IsPositive, m_bScale);
         }
@@ -452,7 +455,7 @@ namespace System.Xml
                 goto Error;
             return;
 Error:
-            throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+            throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
         }
 
         private static void BreakDownXsdDate(long val, out int yr, out int mnth, out int day, out bool negTimeZone, out int hr, out int min)
@@ -477,7 +480,7 @@ Error:
                 goto Error;
             return;
 Error:
-            throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+            throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
         }
 
         private static void BreakDownXsdTime(long val, out int hr, out int min, out int sec, out int ms)
@@ -495,7 +498,7 @@ Error:
                 goto Error;
             return;
 Error:
-            throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+            throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
         }
 
         public static string XsdDateTimeToString(long val)
@@ -765,7 +768,7 @@ Error:
             }
             else
             {
-                throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+                throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
             }
             return timeTicks * KatmaiTimeScaleMultiplicator[scale];
         }
index 655ae56..c7a8e0f 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.
 
+#nullable enable
 using System;
 using System.Collections;
 using System.Collections.Generic;
@@ -18,7 +19,7 @@ namespace System.Xml
         internal static readonly Type TypeOfObject = typeof(object);
         internal static readonly Type TypeOfString = typeof(string);
 
-        private static volatile Type[] s_tokenTypeMap = null;
+        private static volatile Type?[] s_tokenTypeMap = null!;
 
         private static ReadOnlySpan<byte> XsdKatmaiTimeScaleToValueLengthMap => new byte[8] { // rely on C# compiler optimization to eliminate allocation
         // length scale
@@ -82,6 +83,7 @@ namespace System.Xml
             {
                 return lname == this.localname && nsUri == this.namespaceUri;
             }
+
             public bool MatchPrefix(string prefix, string lname)
             {
                 return lname == this.localname && prefix == this.prefix;
@@ -104,11 +106,10 @@ namespace System.Xml
             }
 
 
-            public override bool Equals(object other)
+            public override bool Equals(object? other)
             {
-                if (other is QName)
+                if (other is QName that)
                 {
-                    QName that = (QName)other;
                     return this == that;
                 }
                 return false;
@@ -138,10 +139,10 @@ namespace System.Xml
         private struct ElemInfo
         {
             public QName name;
-            public string xmlLang;
+            public string? xmlLang;
             public XmlSpace xmlSpace;
             public bool xmlspacePreserve;
-            public NamespaceDecl nsdecls;
+            public NamespaceDecl? nsdecls;
 
             public void Set(QName name, bool xmlspacePreserve)
             {
@@ -150,9 +151,9 @@ namespace System.Xml
                 this.xmlSpace = XmlSpace.None;
                 this.xmlspacePreserve = xmlspacePreserve;
             }
-            public NamespaceDecl Clear()
+            public NamespaceDecl? Clear()
             {
-                NamespaceDecl nsdecls = this.nsdecls;
+                NamespaceDecl? nsdecls = this.nsdecls;
                 this.nsdecls = null;
                 return nsdecls;
             }
@@ -161,7 +162,7 @@ namespace System.Xml
         private struct AttrInfo
         {
             public QName name;
-            public string val;
+            public string? val;
             public int contentPos;
             public int hashCode;
             public int prevHash;
@@ -174,6 +175,7 @@ namespace System.Xml
                 this.hashCode = 0;
                 this.prevHash = 0;
             }
+
             public void Set(QName n, int pos)
             {
                 this.name = n;
@@ -217,13 +219,13 @@ namespace System.Xml
         {
             public string prefix;
             public string uri;
-            public NamespaceDecl scopeLink;
-            public NamespaceDecl prevLink;
+            public NamespaceDecl? scopeLink;
+            public NamespaceDecl? prevLink;
             public int scope;
             public bool implied;
 
             public NamespaceDecl(string prefix, string nsuri,
-                                NamespaceDecl nextInScope, NamespaceDecl prevDecl,
+                                NamespaceDecl? nextInScope, NamespaceDecl? prevDecl,
                                 int scope, bool implied)
             {
                 this.prefix = prefix;
@@ -251,12 +253,13 @@ namespace System.Xml
                 this.qnameCount = 1;
             }
         }
+
         private class NestedBinXml
         {
             public SymbolTables symbolTables;
             public int docState;
-            public NestedBinXml next;
-            public NestedBinXml(SymbolTables symbolTables, int docState, NestedBinXml next)
+            public NestedBinXml? next;
+            public NestedBinXml(SymbolTables symbolTables, int docState, NestedBinXml? next)
             {
                 this.symbolTables = symbolTables;
                 this.docState = docState;
@@ -315,14 +318,14 @@ namespace System.Xml
         private bool _hasTypedValue;
         private System.Type _valueType;
         // if it is a simple string value, we cache it
-        private string _stringValue;
+        private string? _stringValue;
         // hashtable of current namespaces
         private readonly Dictionary<string, NamespaceDecl> _namespaces;
         //Hashtable namespaces;
         // linked list of pushed nametables (to support nested binary-xml documents)
-        private NestedBinXml _prevNameInfo;
+        private NestedBinXml? _prevNameInfo;
         // XmlTextReader to handle embeded text blocks
-        private XmlReader _textXmlReader;
+        private XmlReader? _textXmlReader;
         // close input flag
         private readonly bool _closeInput;
 
@@ -338,12 +341,12 @@ namespace System.Xml
         // current version of the protocol
         private byte _version;
 
-        public XmlSqlBinaryReader(System.IO.Stream stream, byte[] data, int len, string baseUri, bool closeInput, XmlReaderSettings settings)
+        public XmlSqlBinaryReader(Stream stream, byte[] data, int len, string baseUri, bool closeInput, XmlReaderSettings settings)
         {
             _unicode = System.Text.Encoding.Unicode;
             _xmlCharType = XmlCharType.Instance;
 
-            _xnt = settings.NameTable;
+            _xnt = settings.NameTable!;
             if (_xnt == null)
             {
                 _xnt = new NameTable();
@@ -353,6 +356,7 @@ namespace System.Xml
             {
                 _xntFromSettings = true;
             }
+
             _xml = _xnt.Add("xml");
             _xmlns = _xnt.Add("xmlns");
             _nsxmlns = _xnt.Add(XmlReservedNs.NsXmlNs);
@@ -408,8 +412,7 @@ namespace System.Xml
             _ignorePIs = settings.IgnoreProcessingInstructions;
             _ignoreComments = settings.IgnoreComments;
 
-            if (s_tokenTypeMap == null)
-                GenerateTokenTypeMap();
+            s_tokenTypeMap = s_tokenTypeMap ?? GenerateTokenTypeMap();
         }
 
         public override XmlReaderSettings Settings
@@ -477,7 +480,10 @@ namespace System.Xml
             get
             {
                 if (ScanState.XmlText == _state)
+                {
+                    Debug.Assert(_textXmlReader != null);
                     return _textXmlReader.HasValue;
+                }
                 else
                     return XmlReader.HasValueInternal(_nodetype);
             }
@@ -513,7 +519,10 @@ namespace System.Xml
                         break;
 
                     case ScanState.XmlText:
-                        return _textXmlReader.Value;
+                        {
+                            Debug.Assert(_textXmlReader != null);
+                            return _textXmlReader.Value;
+                        }
 
                     case ScanState.Attr:
                     case ScanState.AttrValPseudoValue:
@@ -540,6 +549,7 @@ namespace System.Xml
                         break;
 
                     case ScanState.XmlText:
+                        Debug.Assert(_textXmlReader != null);
                         adj = _textXmlReader.Depth;
                         break;
 
@@ -599,6 +609,7 @@ namespace System.Xml
                 }
                 else
                 {
+                    Debug.Assert(_textXmlReader != null);
                     return _textXmlReader.XmlSpace;
                 }
             }
@@ -612,7 +623,7 @@ namespace System.Xml
                 {
                     for (int i = _elemDepth; i >= 0; i--)
                     {
-                        string xl = _elementStack[i].xmlLang;
+                        string? xl = _elementStack[i].xmlLang;
                         if (null != xl)
                             return xl;
                     }
@@ -620,6 +631,7 @@ namespace System.Xml
                 }
                 else
                 {
+                    Debug.Assert(_textXmlReader != null);
                     return _textXmlReader.XmlLang;
                 }
             }
@@ -649,17 +661,21 @@ namespace System.Xml
                     case ScanState.AttrValPseudoValue:
                         return _attrCount;
                     case ScanState.XmlText:
-                        return _textXmlReader.AttributeCount;
+                        {
+                            Debug.Assert(_textXmlReader != null);
+                            return _textXmlReader.AttributeCount;
+                        }
                     default:
                         return 0;
                 }
             }
         }
 
-        public override string GetAttribute(string name, string ns)
+        public override string? GetAttribute(string name, string ns)
         {
             if (ScanState.XmlText == _state)
             {
+                Debug.Assert(_textXmlReader != null);
                 return _textXmlReader.GetAttribute(name, ns);
             }
             else
@@ -675,10 +691,11 @@ namespace System.Xml
             }
         }
 
-        public override string GetAttribute(string name)
+        public override string? GetAttribute(string name)
         {
             if (ScanState.XmlText == _state)
             {
+                Debug.Assert(_textXmlReader != null);
                 return _textXmlReader.GetAttribute(name);
             }
             else
@@ -694,6 +711,7 @@ namespace System.Xml
         {
             if (ScanState.XmlText == _state)
             {
+                Debug.Assert(_textXmlReader != null);
                 return _textXmlReader.GetAttribute(i);
             }
             else
@@ -708,6 +726,7 @@ namespace System.Xml
         {
             if (ScanState.XmlText == _state)
             {
+                Debug.Assert(_textXmlReader != null);
                 return UpdateFromTextReader(_textXmlReader.MoveToAttribute(name, ns));
             }
             else
@@ -730,6 +749,7 @@ namespace System.Xml
         {
             if (ScanState.XmlText == _state)
             {
+                Debug.Assert(_textXmlReader != null);
                 return UpdateFromTextReader(_textXmlReader.MoveToAttribute(name));
             }
             else
@@ -748,6 +768,7 @@ namespace System.Xml
         {
             if (ScanState.XmlText == _state)
             {
+                Debug.Assert(_textXmlReader != null);
                 _textXmlReader.MoveToAttribute(i);
                 UpdateFromTextReader(true);
             }
@@ -765,6 +786,7 @@ namespace System.Xml
         {
             if (ScanState.XmlText == _state)
             {
+                Debug.Assert(_textXmlReader != null);
                 return UpdateFromTextReader(_textXmlReader.MoveToFirstAttribute());
             }
             else
@@ -791,6 +813,7 @@ namespace System.Xml
                     return true;
 
                 case ScanState.XmlText:
+                    Debug.Assert(_textXmlReader != null);
                     return UpdateFromTextReader(_textXmlReader.MoveToNextAttribute());
 
                 default:
@@ -822,6 +845,7 @@ namespace System.Xml
                     return true;
 
                 case ScanState.XmlText:
+                    Debug.Assert(_textXmlReader != null);
                     return UpdateFromTextReader(_textXmlReader.MoveToElement());
 
                 default:
@@ -870,6 +894,7 @@ namespace System.Xml
                     return false;
 
                 case ScanState.XmlText:
+                    Debug.Assert(_textXmlReader != null);
                     return UpdateFromTextReader(_textXmlReader.ReadAttributeValue());
 
                 default:
@@ -888,9 +913,10 @@ namespace System.Xml
                 _textXmlReader.Close();
                 _textXmlReader = null;
             }
+
             if (null != _inStrm && _closeInput)
                 _inStrm.Dispose();
-            _inStrm = null;
+            _inStrm = null!;
             _pos = _end = 0;
         }
 
@@ -902,11 +928,15 @@ namespace System.Xml
             }
         }
 
-        public override string LookupNamespace(string prefix)
+        public override string? LookupNamespace(string prefix)
         {
             if (ScanState.XmlText == _state)
+            {
+                Debug.Assert(_textXmlReader != null);
                 return _textXmlReader.LookupNamespace(prefix);
-            NamespaceDecl decl;
+            }
+
+            NamespaceDecl? decl;
             if (prefix != null && _namespaces.TryGetValue(prefix, out decl))
             {
                 Debug.Assert(decl != null);
@@ -941,10 +971,13 @@ namespace System.Xml
                         return ReadDoc();
 
                     case ScanState.XmlText:
+                        Debug.Assert(_textXmlReader != null);
+
                         if (_textXmlReader.Read())
                         {
                             return UpdateFromTextReader(true);
                         }
+
                         _state = ScanState.Doc;
                         _nodetype = XmlNodeType.None;
                         _isEmpty = false;
@@ -1805,6 +1838,7 @@ namespace System.Xml
         {
             if (ScanState.XmlText == _state)
             {
+                Debug.Assert(_textXmlReader != null);
                 IXmlNamespaceResolver resolver = (IXmlNamespaceResolver)_textXmlReader;
                 return resolver.GetNamespacesInScope(scope);
             }
@@ -1816,7 +1850,7 @@ namespace System.Xml
                     // are we even inside an element? (depth==0 is where we have xml, and xmlns declared...)
                     if (_elemDepth > 0)
                     {
-                        NamespaceDecl nsdecl = _elementStack[_elemDepth].nsdecls;
+                        NamespaceDecl? nsdecl = _elementStack[_elemDepth].nsdecls;
                         while (null != nsdecl)
                         {
                             nstable.Add(nsdecl.prefix, nsdecl.uri);
@@ -1841,10 +1875,11 @@ namespace System.Xml
             }
         }
 
-        string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
+        string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
         {
             if (ScanState.XmlText == _state)
             {
+                Debug.Assert(_textXmlReader != null);
                 IXmlNamespaceResolver resolver = (IXmlNamespaceResolver)_textXmlReader;
                 return resolver.LookupPrefix(namespaceName);
             }
@@ -1853,16 +1888,16 @@ namespace System.Xml
                 if (null == namespaceName)
                     return null;
 
-                namespaceName = _xnt.Get(namespaceName);
-                if (null == namespaceName)
+                string? atomizedNamespaceName = _xnt.Get(namespaceName);
+                if (null == atomizedNamespaceName)
                     return null;
 
                 for (int i = _elemDepth; i >= 0; i--)
                 {
-                    NamespaceDecl nsdecl = _elementStack[i].nsdecls;
+                    NamespaceDecl? nsdecl = _elementStack[i].nsdecls;
                     while (null != nsdecl)
                     {
-                        if ((object)nsdecl.uri == (object)namespaceName)
+                        if ((object)nsdecl.uri == (object?)atomizedNamespaceName)
                             return nsdecl.prefix;
                         nsdecl = nsdecl.scopeLink;
                     }
@@ -1951,7 +1986,7 @@ namespace System.Xml
             qnametable[qnameNum].Set(prefixStr, lnameStr, nsUriStr);
             return;
         BadDecl:
-            throw new XmlException(SR.Xml_BadNamespaceDecl, (string[])null);
+            throw new XmlException(SR.Xml_BadNamespaceDecl, (string[]?)null);
         }
 
         private void NameFlush()
@@ -2319,7 +2354,7 @@ namespace System.Xml
         {
             Debug.Assert(pos >= 0 && cch >= 0);
             if (checked(pos + (cch * 2)) > _end)
-                throw new XmlException(SR.Xml_UnexpectedEOF1, (string[])null);
+                throw new XmlException(SR.Xml_UnexpectedEOF1, (string[]?)null);
             if (cch == 0)
                 return string.Empty;
             // GetStringUnaligned is _significantly_ faster than unicode.GetString()
@@ -2344,7 +2379,7 @@ namespace System.Xml
 
         private string GetAttributeText(int i)
         {
-            string val = _attributes[i].val;
+            string? val = _attributes[i].val;
 
             if (null != val)
                 return val;
@@ -2440,7 +2475,7 @@ namespace System.Xml
             if (prefix == "xml")
                 return;
             int elemDepth = _elemDepth;
-            NamespaceDecl curDecl;
+            NamespaceDecl? curDecl;
             _namespaces.TryGetValue(prefix, out curDecl);
             if (null != curDecl)
             {
@@ -2474,16 +2509,16 @@ namespace System.Xml
             _namespaces[prefix] = decl;
         }
 
-        private void PopNamespaces(NamespaceDecl firstInScopeChain)
+        private void PopNamespaces(NamespaceDecl? firstInScopeChain)
         {
-            NamespaceDecl decl = firstInScopeChain;
+            NamespaceDecl? decl = firstInScopeChain;
             while (null != decl)
             {
                 if (null == decl.prevLink)
                     _namespaces.Remove(decl.prefix);
                 else
                     _namespaces[decl.prefix] = decl.prevLink;
-                NamespaceDecl next = decl.scopeLink;
+                NamespaceDecl? next = decl.scopeLink;
                 // unlink chains for better gc behaviour
                 decl.prevLink = null;
                 decl.scopeLink = null;
@@ -2494,7 +2529,7 @@ namespace System.Xml
         private void GenerateImpliedXmlnsAttrs()
         {
             QName name;
-            NamespaceDecl decl = _elementStack[_elemDepth].nsdecls;
+            NamespaceDecl? decl = _elementStack[_elemDepth].nsdecls;
             while (null != decl)
             {
                 if (decl.implied)
@@ -2514,7 +2549,7 @@ namespace System.Xml
 
         private bool ReadInit(bool skipXmlDecl)
         {
-            string err = null;
+            string? err = null;
             if (!_sniffed)
             {
                 // check magic header
@@ -2582,7 +2617,7 @@ namespace System.Xml
 
         Error:
             _state = ScanState.Error;
-            throw new XmlException(err, (string[])null);
+            throw new XmlException(err, (string[]?)null);
         }
 
         private void ScanAttributes()
@@ -2592,7 +2627,7 @@ namespace System.Xml
             int xmllang = -1;
 
             _mark = _pos;
-            string curDeclPrefix = null;
+            string? curDeclPrefix = null;
             bool lastWasValue = false;
 
             while (BinXmlToken.EndAttrs != (token = NextToken()))
@@ -2655,12 +2690,14 @@ namespace System.Xml
                     // if char checking is on, we need to scan text values to
                     // validate that they don't use invalid CharData, so we
                     // might as well store the saved string for quick attr value access
-                    string val = _stringValue;
+                    string? val = _stringValue;
+
                     if (null != val)
                     {
                         _attributes[_attrCount - 1].val = val;
                         _stringValue = null;
                     }
+
                     // namespace decls can only have text values, and should only
                     // have a single value, so we just grab it here...
                     if (null != curDeclPrefix)
@@ -2669,6 +2706,7 @@ namespace System.Xml
                         PushNamespace(curDeclPrefix, nsuri, false);
                         curDeclPrefix = null;
                     }
+
                     lastWasValue = true;
                 }
             }
@@ -2734,6 +2772,7 @@ namespace System.Xml
                     next = _attributes[next].prevHash;
                 }
             }
+
             Array.Clear(_attrHashTbl, 0, tblSize);
         }
 
@@ -2757,7 +2796,7 @@ namespace System.Xml
             Debug.Assert(_stringValue == null, "this.stringValue == null");
             Debug.Assert(_token == BinXmlToken.CData, "this.token == BinXmlToken.CData");
             string value = GetString(_tokDataPos, _tokLen);
-            StringBuilder sb = null;
+            StringBuilder? sb = null;
             while (PeekToken() == BinXmlToken.CData)
             {
                 _pos++; // skip over token byte
@@ -2799,7 +2838,7 @@ namespace System.Xml
 
         private void FinishEndElement()
         {
-            NamespaceDecl nsdecls = _elementStack[_elemDepth].Clear();
+            NamespaceDecl? nsdecls = _elementStack[_elemDepth].Clear();
             this.PopNamespaces(nsdecls);
             _elemDepth--;
         }
@@ -2841,7 +2880,7 @@ namespace System.Xml
             {
                 case BinXmlToken.EOF:
                     if (_elemDepth > 0)
-                        throw new XmlException(SR.Xml_UnexpectedEOF1, (string[])null);
+                        throw new XmlException(SR.Xml_UnexpectedEOF1, (string[]?)null);
                     _state = ScanState.EOF;
                     return false;
 
@@ -3185,6 +3224,7 @@ namespace System.Xml
 
         private void ImplReadEndNest()
         {
+            Debug.Assert(_prevNameInfo != null);
             NestedBinXml nested = _prevNameInfo;
             _symbolTables = nested.symbolTables;
             _docState = nested.docState;
@@ -3201,9 +3241,9 @@ namespace System.Xml
                 if (decl.scope > 0)
                 {
 #if DEBUG
-                    if ((object)decl.prefix != (object)this._xnt.Get(decl.prefix))
+                    if ((object)decl.prefix != (object?)this._xnt.Get(decl.prefix))
                         throw new Exception("Prefix not interned: \'" + decl.prefix + "\'");
-                    if ((object)decl.uri != (object)this._xnt.Get(decl.uri))
+                    if ((object)decl.uri != (object?)this._xnt.Get(decl.uri))
                         throw new Exception("Uri not interned: \'" + decl.uri + "\'");
 #endif
                     xnm.AddNamespace(decl.prefix, decl.uri);
@@ -3236,6 +3276,7 @@ namespace System.Xml
 
         private void UpdateFromTextReader()
         {
+            Debug.Assert(_textXmlReader != null);
             XmlReader r = _textXmlReader;
             _nodetype = r.NodeType;
             _qnameOther.prefix = r.Prefix;
@@ -3267,9 +3308,9 @@ namespace System.Xml
             }
         }
 
-        private void GenerateTokenTypeMap()
+        private Type?[] GenerateTokenTypeMap()
         {
-            Type[] map = new Type[256];
+            Type?[] map = new Type[256];
             map[(int)BinXmlToken.XSD_BOOLEAN] = typeof(bool);
             map[(int)BinXmlToken.SQL_TINYINT] = typeof(byte);
             map[(int)BinXmlToken.XSD_BYTE] = typeof(sbyte);
@@ -3317,15 +3358,16 @@ namespace System.Xml
             map[(int)BinXmlToken.SQL_NVARCHAR] = TypeOfString;
             map[(int)BinXmlToken.SQL_NTEXT] = TypeOfString;
             map[(int)BinXmlToken.SQL_UUID] = TypeOfString;
-            if (s_tokenTypeMap == null)
-                s_tokenTypeMap = map;
+            return map;
         }
 
         private System.Type GetValueType(BinXmlToken token)
         {
-            Type t = s_tokenTypeMap[(int)token];
+            Type? t = s_tokenTypeMap[(int)token];
+
             if (t == null)
                 throw ThrowUnexpectedToken(token);
+
             return t;
         }
 
@@ -3611,7 +3653,7 @@ namespace System.Xml
         {
             if (scale > 7)
             {
-                throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+                throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
             }
             return XsdKatmaiTimeScaleToValueLengthMap[scale];
         }
@@ -4463,7 +4505,7 @@ namespace System.Xml
         private Exception ThrowXmlException(string res)
         {
             _state = ScanState.Error;
-            return new XmlException(res, (string[])null);
+            return new XmlException(res, (string[]?)null);
         }
 
         private Exception ThrowXmlException(string res, string arg1, string arg2)
index aedab7e..5e5f922 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.
 
+#nullable enable
 using System.Text;
 using System.Diagnostics;
 using System.Globalization;
@@ -13,9 +14,9 @@ namespace System.Xml
     //
     internal class CharEntityEncoderFallback : EncoderFallback
     {
-        private CharEntityEncoderFallbackBuffer _fallbackBuffer;
+        private CharEntityEncoderFallbackBuffer? _fallbackBuffer;
 
-        private int[] _textContentMarks;
+        private int[]? _textContentMarks;
         private int _endMarkPos;
         private int _curMarkPos;
         private int _startOffset;
@@ -62,6 +63,8 @@ namespace System.Xml
 
         internal bool CanReplaceAt(int index)
         {
+            Debug.Assert(_textContentMarks != null);
+
             int mPos = _curMarkPos;
             int charPos = _startOffset + index;
             while (mPos < _endMarkPos && charPos >= _textContentMarks[mPos + 1])
index 73d2f6f..26902e0 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.
 
+#nullable enable
 namespace System.Xml
 {
     public enum ConformanceLevel
index 1ebbd2c..47b85d7 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.
 
+#nullable enable
 namespace System.Xml
 {
     // DtdProcessing enumerations specifies how will an XmlReader handle DTDs in the XML document.
index f46c19d..70b893f 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.
 
+#nullable enable
 namespace System.Xml
 {
     // Specifies how entities are handled in XmlTextReader and XmlValidatingReader.
index 10dadaf..109687f 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.
 
+#nullable enable
 // This file is generated by TernaryTreeGenerator.cs,
 // and is used by the TernaryTreeRO class.
 
index 21e3451..2eb8905 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.
 
+#nullable enable
 using System;
 using System.Collections.Generic;
 
@@ -45,7 +46,7 @@ namespace System.Xml
         /// <param name="prefix">The prefix of the attribute list to look for</param>
         /// <param name="localName">The local name of the attribute list to look for</param>
         /// <returns>Interface representing an attribute list or null if none was found.</returns>
-        IDtdAttributeListInfo LookupAttributeList(string prefix, string localName);
+        IDtdAttributeListInfo? LookupAttributeList(string prefix, string localName);
 
         /// <summary>
         /// Returns an enumerator of all attribute lists defined in the DTD.
index 29cb220..062f9e8 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.
 
+#nullable enable
 using System;
 using System.Xml;
 
index 634f939..0d9075f 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.
 
+#nullable enable
 using System;
 using System.Text;
 using System.Xml.Schema;
@@ -11,11 +12,11 @@ namespace System.Xml
     internal partial interface IDtdParserAdapter
     {
         XmlNameTable NameTable { get; }
-        IXmlNamespaceResolver NamespaceResolver { get; }
+        IXmlNamespaceResolver? NamespaceResolver { get; }
 
-        Uri BaseUri { get; }
+        Uri? BaseUri { get; }
 
-        char[] ParsingBuffer { get; }
+        char[]? ParsingBuffer { get; }
         int ParsingBufferLength { get; }
         int CurrentPosition { get; set; }
         int LineNo { get; }
@@ -35,7 +36,7 @@ namespace System.Xml
 
         bool PushEntity(IDtdEntityInfo entity, out int entityId);
 
-        bool PopEntity(out IDtdEntityInfo oldEntity, out int newEntityId);
+        bool PopEntity(out IDtdEntityInfo? oldEntity, out int newEntityId);
 
         bool PushExternalSubset(string systemId, string publicId);
 
@@ -49,7 +50,7 @@ namespace System.Xml
     internal interface IDtdParserAdapterWithValidation : IDtdParserAdapter
     {
         bool DtdValidation { get; }
-        IValidationEventHandling ValidationEventHandling { get; }
+        IValidationEventHandling? ValidationEventHandling { get; }
     }
 
     internal interface IDtdParserAdapterV1 : IDtdParserAdapterWithValidation
index 69ab5f3..fbe5652 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.
 
+#nullable enable
 using System;
 using System.Text;
 using System.Xml.Schema;
index 929a69f..e9acace 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.
 
+#nullable enable
 using System;
 using System.Xml;
 
index eb38768..9ab4aeb 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.
 
+#nullable enable
 namespace System.Xml
 {
     // NewLineHandling specifies what will XmlWriter do with new line characters. The options are:
index debd969..b70702a 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.
 
+#nullable enable
 namespace System.Xml
 {
     // Specifies the state of the XmlReader.
index b3d10f3..a5c9f0f 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.
 
+#nullable enable
 namespace System.Xml
 {
     // Specifies the type of validation to perform in XmlValidatingReader or in XmlReaderSettings.
index fb26691..650cbf2 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.
 
+#nullable enable
 namespace System.Xml
 {
     // Specifies how whitespace is handled in XmlTextReader.
index e6a6dd5..252d39c 100644 (file)
@@ -2,17 +2,19 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Xml;
 using System.Text;
 using System;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
     // Specifies the context that the XmLReader will use for xml fragment
     public class XmlParserContext
     {
-        private XmlNameTable _nt = null;
-        private XmlNamespaceManager _nsMgr = null;
+        private XmlNameTable? _nt = null;
+        private XmlNamespaceManager? _nsMgr = null;
         private string _docTypeName = string.Empty;
         private string _pubId = string.Empty;
         private string _sysId = string.Empty;
@@ -20,31 +22,31 @@ namespace System.Xml
         private string _xmlLang = string.Empty;
         private XmlSpace _xmlSpace;
         private string _baseURI = string.Empty;
-        private Encoding _encoding = null;
+        private Encoding? _encoding = null;
 
-        public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, string xmlLang, XmlSpace xmlSpace)
+        public XmlParserContext(XmlNameTable? nt, XmlNamespaceManager? nsMgr, string? xmlLang, XmlSpace xmlSpace)
         : this(nt, nsMgr, null, null, null, null, string.Empty, xmlLang, xmlSpace)
         {
             // Intentionally Empty
         }
 
-        public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, string xmlLang, XmlSpace xmlSpace, Encoding enc)
+        public XmlParserContext(XmlNameTable? nt, XmlNamespaceManager? nsMgr, string? xmlLang, XmlSpace xmlSpace, Encoding? enc)
         : this(nt, nsMgr, null, null, null, null, string.Empty, xmlLang, xmlSpace, enc)
         {
             // Intentionally Empty
         }
 
-        public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, string docTypeName,
-                  string pubId, string sysId, string internalSubset, string baseURI,
-                  string xmlLang, XmlSpace xmlSpace)
+        public XmlParserContext(XmlNameTable? nt, XmlNamespaceManager? nsMgr, string? docTypeName,
+                  string? pubId, string? sysId, string? internalSubset, string? baseURI,
+                  string? xmlLang, XmlSpace xmlSpace)
         : this(nt, nsMgr, docTypeName, pubId, sysId, internalSubset, baseURI, xmlLang, xmlSpace, null)
         {
             // Intentionally Empty
         }
 
-        public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, string docTypeName,
-                          string pubId, string sysId, string internalSubset, string baseURI,
-                          string xmlLang, XmlSpace xmlSpace, Encoding enc)
+        public XmlParserContext(XmlNameTable? nt, XmlNamespaceManager? nsMgr, string? docTypeName,
+                          string? pubId, string? sysId, string? internalSubset, string? baseURI,
+                          string? xmlLang, XmlSpace xmlSpace, Encoding? enc)
         {
             if (nsMgr != null)
             {
@@ -54,10 +56,11 @@ namespace System.Xml
                 }
                 else
                 {
-                    if ((object)nt != (object)nsMgr.NameTable)
+                    if ((object)nt != (object?)nsMgr.NameTable)
                     {
                         throw new XmlException(SR.Xml_NotSameNametable, string.Empty);
                     }
+
                     _nt = nt;
                 }
             }
@@ -77,7 +80,7 @@ namespace System.Xml
             _encoding = enc;
         }
 
-        public XmlNameTable NameTable
+        public XmlNameTable? NameTable
         {
             get
             {
@@ -89,7 +92,7 @@ namespace System.Xml
             }
         }
 
-        public XmlNamespaceManager NamespaceManager
+        public XmlNamespaceManager? NamespaceManager
         {
             get
             {
@@ -101,6 +104,7 @@ namespace System.Xml
             }
         }
 
+        [AllowNull]
         public string DocTypeName
         {
             get
@@ -113,6 +117,7 @@ namespace System.Xml
             }
         }
 
+        [AllowNull]
         public string PublicId
         {
             get
@@ -125,6 +130,7 @@ namespace System.Xml
             }
         }
 
+        [AllowNull]
         public string SystemId
         {
             get
@@ -137,6 +143,7 @@ namespace System.Xml
             }
         }
 
+        [AllowNull]
         public string BaseURI
         {
             get
@@ -149,6 +156,7 @@ namespace System.Xml
             }
         }
 
+        [AllowNull]
         public string InternalSubset
         {
             get
@@ -161,6 +169,7 @@ namespace System.Xml
             }
         }
 
+        [AllowNull]
         public string XmlLang
         {
             get
@@ -185,7 +194,7 @@ namespace System.Xml
             }
         }
 
-        public Encoding Encoding
+        public Encoding? Encoding
         {
             get
             {
index 8809d5f..dfbf9cc 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.
 
+#nullable enable
 using System.Collections;
 using System.Diagnostics;
 using System.Globalization;
@@ -88,7 +89,7 @@ namespace System.Xml
         internal const int AsyncBufferSize = 64 * 1024; //64KB
 
         // Settings
-        public virtual XmlReaderSettings Settings
+        public virtual XmlReaderSettings? Settings
         {
             get
             {
@@ -141,7 +142,7 @@ namespace System.Xml
         public abstract int Depth { get; }
 
         // Gets the base URI of the current node.
-        public abstract string BaseURI { get; }
+        public abstract string? BaseURI { get; }
 
         // Gets a value indicating whether the current node is an empty element (for example, <MyElement/>).
         public abstract bool IsEmptyElement { get; }
@@ -184,7 +185,7 @@ namespace System.Xml
         }
 
         // returns the schema info interface of the reader
-        public virtual IXmlSchemaInfo SchemaInfo
+        public virtual IXmlSchemaInfo? SchemaInfo
         {
             get
             {
@@ -220,6 +221,7 @@ namespace System.Xml
             {
                 throw CreateReadContentAsException(nameof(ReadContentAsBoolean));
             }
+
             try
             {
                 return XmlConvert.ToBoolean(InternalReadContentAsString());
@@ -238,6 +240,7 @@ namespace System.Xml
             {
                 throw CreateReadContentAsException(nameof(ReadContentAsDateTime));
             }
+
             try
             {
                 return XmlConvert.ToDateTime(InternalReadContentAsString(), XmlDateTimeSerializationMode.RoundtripKind);
@@ -256,6 +259,7 @@ namespace System.Xml
             {
                 throw CreateReadContentAsException(nameof(ReadContentAsDateTimeOffset));
             }
+
             try
             {
                 return XmlConvert.ToDateTimeOffset(InternalReadContentAsString());
@@ -274,6 +278,7 @@ namespace System.Xml
             {
                 throw CreateReadContentAsException(nameof(ReadContentAsDouble));
             }
+
             try
             {
                 return XmlConvert.ToDouble(InternalReadContentAsString());
@@ -292,6 +297,7 @@ namespace System.Xml
             {
                 throw CreateReadContentAsException(nameof(ReadContentAsFloat));
             }
+
             try
             {
                 return XmlConvert.ToSingle(InternalReadContentAsString());
@@ -310,6 +316,7 @@ namespace System.Xml
             {
                 throw CreateReadContentAsException(nameof(ReadContentAsDecimal));
             }
+
             try
             {
                 return XmlConvert.ToDecimal(InternalReadContentAsString());
@@ -328,6 +335,7 @@ namespace System.Xml
             {
                 throw CreateReadContentAsException(nameof(ReadContentAsInt));
             }
+
             try
             {
                 return XmlConvert.ToInt32(InternalReadContentAsString());
@@ -346,6 +354,7 @@ namespace System.Xml
             {
                 throw CreateReadContentAsException(nameof(ReadContentAsLong));
             }
+
             try
             {
                 return XmlConvert.ToInt64(InternalReadContentAsString());
@@ -364,6 +373,7 @@ namespace System.Xml
             {
                 throw CreateReadContentAsException(nameof(ReadContentAsString));
             }
+
             return InternalReadContentAsString();
         }
 
@@ -407,6 +417,7 @@ namespace System.Xml
                 FinishReadElementContentAsXxx();
                 return value;
             }
+
             return string.Empty;
         }
 
@@ -426,6 +437,7 @@ namespace System.Xml
                 FinishReadElementContentAsXxx();
                 return value;
             }
+
             return XmlConvert.ToBoolean(string.Empty);
         }
 
@@ -445,6 +457,7 @@ namespace System.Xml
                 FinishReadElementContentAsXxx();
                 return value;
             }
+
             return XmlConvert.ToDateTime(string.Empty, XmlDateTimeSerializationMode.RoundtripKind);
         }
 
@@ -465,6 +478,7 @@ namespace System.Xml
                 FinishReadElementContentAsXxx();
                 return value;
             }
+
             return XmlConvert.ToDouble(string.Empty);
         }
 
@@ -485,6 +499,7 @@ namespace System.Xml
                 FinishReadElementContentAsXxx();
                 return value;
             }
+
             return XmlConvert.ToSingle(string.Empty);
         }
 
@@ -565,6 +580,7 @@ namespace System.Xml
                 FinishReadElementContentAsXxx();
                 return value;
             }
+
             return string.Empty;
         }
 
@@ -585,6 +601,7 @@ namespace System.Xml
                 FinishReadElementContentAsXxx();
                 return value;
             }
+
             return (returnType == typeof(string)) ? string.Empty : XmlUntypedStringConverter.Instance.FromString(string.Empty, returnType, namespaceResolver);
         }
 
@@ -601,10 +618,10 @@ namespace System.Xml
         public abstract int AttributeCount { get; }
 
         // Gets the value of the attribute with the specified Name
-        public abstract string GetAttribute(string name);
+        public abstract string? GetAttribute(string name);
 
         // Gets the value of the attribute with the LocalName and NamespaceURI
-        public abstract string GetAttribute(string name, string namespaceURI);
+        public abstract string? GetAttribute(string name, string namespaceURI);
 
         // Gets the value of the attribute with the specified index.
         public abstract string GetAttribute(int i);
@@ -619,7 +636,7 @@ namespace System.Xml
         }
 
         // Gets the value of the attribute with the specified Name.
-        public virtual string this[string name]
+        public virtual string? this[string name]
         {
             get
             {
@@ -628,7 +645,7 @@ namespace System.Xml
         }
 
         // Gets the value of the attribute with the LocalName and NamespaceURI
-        public virtual string this[string name, string namespaceURI]
+        public virtual string? this[string name, string namespaceURI]
         {
             get
             {
@@ -700,7 +717,7 @@ namespace System.Xml
         public abstract XmlNameTable NameTable { get; }
 
         // Resolves a namespace prefix in the current element's scope.
-        public abstract string LookupNamespace(string prefix);
+        public abstract string? LookupNamespace(string prefix);
 
         // Returns true if the XmlReader can expand general entities.
         public virtual bool CanResolveEntity
@@ -1365,15 +1382,14 @@ namespace System.Xml
 
         private void SetNamespacesFlag(XmlTextWriter xtw)
         {
-            XmlTextReader tr = this as XmlTextReader;
-            if (tr != null)
+            if (this is XmlTextReader tr)
             {
                 xtw.Namespaces = tr.Namespaces;
             }
             else
             {
 #pragma warning disable 618
-                XmlValidatingReader vr = this as XmlValidatingReader;
+                XmlValidatingReader? vr = this as XmlValidatingReader;
                 if (vr != null)
                 {
                     xtw.Namespaces = vr.Namespaces;
@@ -1389,6 +1405,7 @@ namespace System.Xml
             {
                 throw new InvalidOperationException(SR.Xml_ReadSubtreeNotOnElement);
             }
+
             return new XmlSubtreeReader(this);
         }
 
@@ -1421,7 +1438,7 @@ namespace System.Xml
         // Internal methods
         //
         // Validation support
-        internal virtual XmlNamespaceManager NamespaceManager
+        internal virtual XmlNamespaceManager? NamespaceManager
         {
             get
             {
@@ -1573,17 +1590,17 @@ namespace System.Xml
             return CanReadContentAs(this.NodeType);
         }
 
-        internal static Exception CreateReadContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo lineInfo)
+        internal static Exception CreateReadContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo? lineInfo)
         {
             return new InvalidOperationException(AddLineInfo(SR.Format(SR.Xml_InvalidReadContentAs, methodName, nodeType), lineInfo));
         }
 
-        internal static Exception CreateReadElementContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo lineInfo)
+        internal static Exception CreateReadElementContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo? lineInfo)
         {
             return new InvalidOperationException(AddLineInfo(SR.Format(SR.Xml_InvalidReadElementContentAs, methodName, nodeType), lineInfo));
         }
 
-        private static string AddLineInfo(string message, IXmlLineInfo lineInfo)
+        private static string AddLineInfo(string message, IXmlLineInfo? lineInfo)
         {
             if (lineInfo != null)
             {
@@ -1598,7 +1615,7 @@ namespace System.Xml
         internal string InternalReadContentAsString()
         {
             string value = string.Empty;
-            StringBuilder sb = null;
+            StringBuilder? sb = null;
             do
             {
                 switch (this.NodeType)
@@ -1673,6 +1690,7 @@ namespace System.Xml
             {
                 throw new XmlException(SR.Xml_MixedReadElementContentAs, string.Empty, this as IXmlLineInfo);
             }
+
             return true;
         }
 
@@ -1682,6 +1700,7 @@ namespace System.Xml
             {
                 throw new XmlException(SR.Xml_InvalidNodeType, this.NodeType.ToString());
             }
+
             this.Read();
         }
 
@@ -1693,16 +1712,18 @@ namespace System.Xml
                 {
                     return true;
                 }
-                IXmlSchemaInfo schemaInfo = this.SchemaInfo;
+
+                IXmlSchemaInfo? schemaInfo = this.SchemaInfo;
                 if (schemaInfo != null && schemaInfo.IsDefault)
                 {
                     return true;
                 }
+
                 return false;
             }
         }
 
-        internal virtual IDtdInfo DtdInfo
+        internal virtual IDtdInfo? DtdInfo
         {
             get
             {
@@ -1712,33 +1733,30 @@ namespace System.Xml
 
         internal static ConformanceLevel GetV1ConformanceLevel(XmlReader reader)
         {
-            XmlTextReaderImpl tri = GetXmlTextReaderImpl(reader);
+            XmlTextReaderImpl? tri = GetXmlTextReaderImpl(reader);
             return tri != null ? tri.V1ComformanceLevel : ConformanceLevel.Document;
         }
 
-        private static XmlTextReaderImpl GetXmlTextReaderImpl(XmlReader reader)
+        private static XmlTextReaderImpl? GetXmlTextReaderImpl(XmlReader reader)
         {
-            XmlTextReaderImpl tri = reader as XmlTextReaderImpl;
-            if (tri != null)
+            if (reader is XmlTextReaderImpl tri)
             {
                 return tri;
             }
 
-            XmlTextReader tr = reader as XmlTextReader;
-            if (tr != null)
+            if (reader is XmlTextReader tr)
             {
                 return tr.Impl;
             }
 
-            XmlValidatingReaderImpl vri = reader as XmlValidatingReaderImpl;
-            if (vri != null)
+            if (reader is XmlValidatingReaderImpl vri)
             {
                 return vri.ReaderImpl;
             }
+
 #pragma warning disable 618
-            XmlValidatingReader vr = reader as XmlValidatingReader;
+            if (reader is XmlValidatingReader vr)
 #pragma warning restore 618
-            if (vr != null)
             {
                 return vr.Impl.ReaderImpl;
             }
@@ -1768,13 +1786,13 @@ namespace System.Xml
         }
 
         // Creates an XmlReader according to the settings for parsing XML from the given Uri.
-        public static XmlReader Create(string inputUri, XmlReaderSettings settings)
+        public static XmlReader Create(string inputUri, XmlReaderSettings? settings)
         {
-            return XmlReader.Create(inputUri, settings, (XmlParserContext)null);
+            return XmlReader.Create(inputUri, settings, (XmlParserContext?)null);
         }
 
         // Creates an XmlReader according to the settings and parser context for parsing XML from the given Uri.
-        public static XmlReader Create(string inputUri, XmlReaderSettings settings, XmlParserContext inputContext)
+        public static XmlReader Create(string inputUri, XmlReaderSettings? settings, XmlParserContext? inputContext)
         {
             settings ??= XmlReaderSettings.s_defaultReaderSettings;
             return settings.CreateReader(inputUri, inputContext);
@@ -1794,20 +1812,20 @@ namespace System.Xml
         }
 
         // Creates an XmlReader according to the settings for parsing XML from the given stream.
-        public static XmlReader Create(Stream input, XmlReaderSettings settings)
+        public static XmlReader Create(Stream input, XmlReaderSettings? settings)
         {
             return Create(input, settings, string.Empty);
         }
 
         // Creates an XmlReader according to the settings and base Uri for parsing XML from the given stream.
-        public static XmlReader Create(Stream input, XmlReaderSettings settings, string baseUri)
+        public static XmlReader Create(Stream input, XmlReaderSettings? settings, string? baseUri)
         {
             settings ??= XmlReaderSettings.s_defaultReaderSettings;
-            return settings.CreateReader(input, null, (string)baseUri, null);
+            return settings.CreateReader(input, null, baseUri, null);
         }
 
         // Creates an XmlReader according to the settings and parser context for parsing XML from the given stream.
-        public static XmlReader Create(Stream input, XmlReaderSettings settings, XmlParserContext inputContext)
+        public static XmlReader Create(Stream input, XmlReaderSettings? settings, XmlParserContext? inputContext)
         {
             settings ??= XmlReaderSettings.s_defaultReaderSettings;
             return settings.CreateReader(input, null, (string)string.Empty, inputContext);
@@ -1827,27 +1845,27 @@ namespace System.Xml
         }
 
         // Creates an XmlReader according to the settings for parsing XML from the given TextReader.
-        public static XmlReader Create(TextReader input, XmlReaderSettings settings)
+        public static XmlReader Create(TextReader input, XmlReaderSettings? settings)
         {
             return Create(input, settings, string.Empty);
         }
 
         // Creates an XmlReader according to the settings and baseUri for parsing XML from the given TextReader.
-        public static XmlReader Create(TextReader input, XmlReaderSettings settings, string baseUri)
+        public static XmlReader Create(TextReader input, XmlReaderSettings? settings, string? baseUri)
         {
             settings ??= XmlReaderSettings.s_defaultReaderSettings;
             return settings.CreateReader(input, baseUri, null);
         }
 
         // Creates an XmlReader according to the settings and parser context for parsing XML from the given TextReader.
-        public static XmlReader Create(TextReader input, XmlReaderSettings settings, XmlParserContext inputContext)
+        public static XmlReader Create(TextReader input, XmlReaderSettings? settings, XmlParserContext? inputContext)
         {
             settings ??= XmlReaderSettings.s_defaultReaderSettings;
             return settings.CreateReader(input, string.Empty, inputContext);
         }
 
         // Creates an XmlReader according to the settings wrapped over the given reader.
-        public static XmlReader Create(XmlReader reader, XmlReaderSettings settings)
+        public static XmlReader Create(XmlReader reader, XmlReaderSettings? settings)
         {
             settings ??= XmlReaderSettings.s_defaultReaderSettings;
             return settings.CreateReader(reader);
@@ -1856,12 +1874,13 @@ namespace System.Xml
         // !!!!!!
         // NOTE: This method is called via reflection from System.Data.Common.dll.
         // !!!!!!
-        internal static XmlReader CreateSqlReader(Stream input, XmlReaderSettings settings, XmlParserContext inputContext)
+        internal static XmlReader CreateSqlReader(Stream input, XmlReaderSettings? settings, XmlParserContext inputContext)
         {
             if (input == null)
             {
                 throw new ArgumentNullException(nameof(input));
             }
+
             settings ??= XmlReaderSettings.s_defaultReaderSettings;
 
             XmlReader reader;
index 098d367..ceefc44 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.
 
+#nullable enable
 using System.IO;
 using System.Text;
 using System.Security;
@@ -340,7 +341,7 @@ namespace System.Xml
         internal async Task<string> InternalReadContentAsStringAsync()
         {
             string value = string.Empty;
-            StringBuilder sb = null;
+            StringBuilder? sb = null;
             do
             {
                 switch (this.NodeType)
index e74adf0..93eb9bb 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.
 
+#nullable enable
 using System.IO;
 using System.Diagnostics;
 using System.Globalization;
@@ -23,10 +24,10 @@ namespace System.Xml
 
 
         // Nametable
-        private XmlNameTable _nameTable;
+        private XmlNameTable? _nameTable;
 
         // XmlResolver
-        private XmlResolver _xmlResolver = null;
+        private XmlResolver? _xmlResolver = null;
 
         // Text settings
         private int _lineNumberOffset;
@@ -50,8 +51,8 @@ namespace System.Xml
         //Validation settings
         private ValidationType _validationType;
         private XmlSchemaValidationFlags _validationFlags;
-        private XmlSchemaSet _schemas;
-        private ValidationEventHandler _valEventHandler;
+        private XmlSchemaSet? _schemas;
+        private ValidationEventHandler? _valEventHandler;
 
         // other settings
         private bool _closeInput;
@@ -62,8 +63,8 @@ namespace System.Xml
         // Creation of validating readers is hidden behind a delegate which is only initialized if the ValidationType
         // property is set. This is for AOT builds where the tree shaker can reduce the validating readers away
         // if nobody calls the ValidationType setter. Might also help with non-AOT build when ILLinker is used.
-        private delegate XmlReader AddValidationFunc(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper);
-        private AddValidationFunc _addValidationFunc;
+        private delegate XmlReader AddValidationFunc(XmlReader reader, XmlResolver? resolver, bool addConformanceWrapper);
+        private AddValidationFunc? _addValidationFunc;
 
         //
         // Constructor
@@ -91,7 +92,7 @@ namespace System.Xml
         }
 
         // Nametable
-        public XmlNameTable NameTable
+        public XmlNameTable? NameTable
         {
             get
             {
@@ -111,7 +112,7 @@ namespace System.Xml
             set; // keep set internal as we need to call it from the schema validation code
         }
 
-        public XmlResolver XmlResolver
+        public XmlResolver? XmlResolver
         {
             set
             {
@@ -121,7 +122,7 @@ namespace System.Xml
             }
         }
 
-        internal XmlResolver GetXmlResolver()
+        internal XmlResolver? GetXmlResolver()
         {
             return _xmlResolver;
         }
@@ -129,7 +130,7 @@ namespace System.Xml
         //This is used by get XmlResolver in Xsd.
         //Check if the config set to prohibit default resovler
         //notice we must keep GetXmlResolver() to avoid dead lock when init System.Config.ConfigurationManager
-        internal XmlResolver GetXmlResolver_CheckConfig()
+        internal XmlResolver? GetXmlResolver_CheckConfig()
         {
             if (!LocalAppContextSwitches.AllowDefaultResolver && !IsXmlResolverSet)
                 return null;
@@ -401,7 +402,7 @@ namespace System.Xml
 
         public XmlReaderSettings Clone()
         {
-            XmlReaderSettings clonedSettings = this.MemberwiseClone() as XmlReaderSettings;
+            XmlReaderSettings clonedSettings = (this.MemberwiseClone() as XmlReaderSettings)!;
             clonedSettings.ReadOnly = false;
             return clonedSettings;
         }
@@ -409,12 +410,12 @@ namespace System.Xml
         //
         // Internal methods
         //
-        internal ValidationEventHandler GetEventHandler()
+        internal ValidationEventHandler? GetEventHandler()
         {
             return _valEventHandler;
         }
 
-        internal XmlReader CreateReader(string inputUri, XmlParserContext inputContext)
+        internal XmlReader CreateReader(string inputUri, XmlParserContext? inputContext)
         {
             if (inputUri == null)
             {
@@ -445,12 +446,13 @@ namespace System.Xml
             return reader;
         }
 
-        internal XmlReader CreateReader(Stream input, Uri baseUri, string baseUriString, XmlParserContext inputContext)
+        internal XmlReader CreateReader(Stream input, Uri? baseUri, string? baseUriString, XmlParserContext? inputContext)
         {
             if (input == null)
             {
                 throw new ArgumentNullException(nameof(input));
             }
+
             if (baseUriString == null)
             {
                 if (baseUri == null)
@@ -480,12 +482,13 @@ namespace System.Xml
             return reader;
         }
 
-        internal XmlReader CreateReader(TextReader input, string baseUriString, XmlParserContext inputContext)
+        internal XmlReader CreateReader(TextReader input, string? baseUriString, XmlParserContext? inputContext)
         {
             if (input == null)
             {
                 throw new ArgumentNullException(nameof(input));
             }
+
             if (baseUriString == null)
             {
                 baseUriString = string.Empty;
@@ -514,6 +517,7 @@ namespace System.Xml
             {
                 throw new ArgumentNullException(nameof(reader));
             }
+
             return AddValidationAndConformanceWrapper(reader);
         }
 
@@ -545,7 +549,7 @@ namespace System.Xml
             Initialize(null);
         }
 
-        private void Initialize(XmlResolver resolver)
+        private void Initialize(XmlResolver? resolver)
         {
             _nameTable = null;
             _xmlResolver = resolver;
@@ -579,7 +583,7 @@ namespace System.Xml
 
         internal XmlReader AddValidation(XmlReader reader)
         {
-            XmlResolver resolver = null;
+            XmlResolver? resolver = null;
             if (_validationType == ValidationType.Schema)
             {
                 resolver = GetXmlResolver_CheckConfig();
@@ -596,7 +600,7 @@ namespace System.Xml
 
         private XmlReader AddValidationAndConformanceWrapper(XmlReader reader)
         {
-            XmlResolver resolver = null;
+            XmlResolver? resolver = null;
             if (_validationType == ValidationType.Schema)
             {
                 resolver = GetXmlResolver_CheckConfig();
@@ -605,7 +609,7 @@ namespace System.Xml
             return AddValidationAndConformanceInternal(reader, resolver, addConformanceWrapper: true);
         }
 
-        private XmlReader AddValidationAndConformanceInternal(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper)
+        private XmlReader AddValidationAndConformanceInternal(XmlReader reader, XmlResolver? resolver, bool addConformanceWrapper)
         {
             // We have to avoid calling the _addValidationFunc delegate if there's no validation to setup
             // since it would not be initialized (to allow AOT compilers to reduce it away).
@@ -621,13 +625,14 @@ namespace System.Xml
             }
             else
             {
+                Debug.Assert(_addValidationFunc != null);
                 reader = _addValidationFunc(reader, resolver, addConformanceWrapper);
             }
 
             return reader;
         }
 
-        private XmlReader AddValidationInternal(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper)
+        private XmlReader AddValidationInternal(XmlReader reader, XmlResolver? resolver, bool addConformanceWrapper)
         {
             // wrap with DTD validating reader
             if (_validationType == ValidationType.DTD)
@@ -656,7 +661,7 @@ namespace System.Xml
 
         internal XmlReader AddConformanceWrapper(XmlReader baseReader)
         {
-            XmlReaderSettings baseReaderSettings = baseReader.Settings;
+            XmlReaderSettings? baseReaderSettings = baseReader.Settings;
             bool checkChars = false;
             bool noWhitespace = false;
             bool noComments = false;
@@ -674,10 +679,10 @@ namespace System.Xml
                 }
 
                 // get the V1 XmlTextReader ref
-                XmlTextReader v1XmlTextReader = baseReader as XmlTextReader;
+                XmlTextReader? v1XmlTextReader = baseReader as XmlTextReader;
                 if (v1XmlTextReader == null)
                 {
-                    XmlValidatingReader vr = baseReader as XmlValidatingReader;
+                    XmlValidatingReader? vr = baseReader as XmlValidatingReader;
                     if (vr != null)
                     {
                         v1XmlTextReader = (XmlTextReader)vr.Reader;
@@ -762,7 +767,7 @@ namespace System.Xml
 
             if (needWrap)
             {
-                IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver;
+                IXmlNamespaceResolver? readerAsNSResolver = baseReader as IXmlNamespaceResolver;
                 if (readerAsNSResolver != null)
                 {
                     return new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc);
index 7d6541c..c8f594b 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.
 
+#nullable enable
 namespace System.Xml
 {
     // An enumeration for the xml:space scope used in XmlReader and XmlWriter.
index 82876f5..9432bb5 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.
 
+#nullable enable
 using System;
 using System.Xml;
 using System.Diagnostics;
@@ -25,8 +26,14 @@ namespace System.Xml
             internal string namespaceUri;
             internal string value;
 
-            internal NodeData()
+            internal NodeData(XmlNodeType nodeType, string localName, string prefix, string name, string namespaceUri, string value)
             {
+                this.type = nodeType;
+                this.localName = localName;
+                this.prefix = prefix;
+                this.name = name;
+                this.namespaceUri = namespaceUri;
+                this.value = value;
             }
 
             internal void Set(XmlNodeType nodeType, string localName, string prefix, string name, string namespaceUri, string value)
@@ -66,7 +73,7 @@ namespace System.Xml
 
         // namespace management
         private readonly XmlNamespaceManager _nsManager;
-        private NodeData[] _nsAttributes;
+        private NodeData[]? _nsAttributes;
         private int _nsAttrCount;
         private int _curNsAttr = -1;
 
@@ -75,11 +82,11 @@ namespace System.Xml
 
         // incremental reading of added xmlns nodes (ReadValueChunk, ReadContentAsBase64, ReadContentAsBinHex)
         private int _nsIncReadOffset;
-        private IncrementalReadDecoder _binDecoder;
+        private IncrementalReadDecoder? _binDecoder;
 
         // cached nodes
         private bool _useCurNode;
-        private NodeData _curNode;
+        private NodeData _curNode = null!;
         // node used for a text node of ReadAttributeValue or as Initial or EOF node
         private readonly NodeData _tmpNode;
 
@@ -99,8 +106,7 @@ namespace System.Xml
             _xmlns = reader.NameTable.Add("xmlns");
             _xmlnsUri = reader.NameTable.Add(XmlReservedNs.NsXmlNs);
 
-            _tmpNode = new NodeData();
-            _tmpNode.Set(XmlNodeType.None, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
+            _tmpNode = new NodeData(XmlNodeType.None, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
 
             SetCurrentNode(_tmpNode);
         }
@@ -112,7 +118,7 @@ namespace System.Xml
         {
             get
             {
-                return (_useCurNode) ? _curNode.type : reader.NodeType;
+                return _useCurNode ? _curNode.type : reader.NodeType;
             }
         }
 
@@ -120,7 +126,7 @@ namespace System.Xml
         {
             get
             {
-                return (_useCurNode) ? _curNode.name : reader.Name;
+                return _useCurNode ? _curNode.name : reader.Name;
             }
         }
 
@@ -128,7 +134,7 @@ namespace System.Xml
         {
             get
             {
-                return (_useCurNode) ? _curNode.localName : reader.LocalName;
+                return _useCurNode ? _curNode.localName : reader.LocalName;
             }
         }
 
@@ -136,7 +142,7 @@ namespace System.Xml
         {
             get
             {
-                return (_useCurNode) ? _curNode.namespaceUri : reader.NamespaceURI;
+                return _useCurNode ? _curNode.namespaceUri : reader.NamespaceURI;
             }
         }
 
@@ -144,7 +150,7 @@ namespace System.Xml
         {
             get
             {
-                return (_useCurNode) ? _curNode.prefix : reader.Prefix;
+                return _useCurNode ? _curNode.prefix : reader.Prefix;
             }
         }
 
@@ -152,7 +158,7 @@ namespace System.Xml
         {
             get
             {
-                return (_useCurNode) ? _curNode.value : reader.Value;
+                return _useCurNode ? _curNode.value : reader.Value;
             }
         }
 
@@ -176,7 +182,7 @@ namespace System.Xml
             }
         }
 
-        public override string BaseURI
+        public override string? BaseURI
         {
             get
             {
@@ -238,45 +244,51 @@ namespace System.Xml
             }
         }
 
-        public override string GetAttribute(string name)
+        public override string? GetAttribute(string name)
         {
             if (!InAttributeActiveState)
             {
                 return null;
             }
-            string attr = reader.GetAttribute(name);
+            string? attr = reader.GetAttribute(name);
             if (attr != null)
             {
                 return attr;
             }
+
             for (int i = 0; i < _nsAttrCount; i++)
             {
-                if (name == _nsAttributes[i].name)
+                if (name == _nsAttributes![i].name)
                 {
+                    // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644
                     return _nsAttributes[i].value;
                 }
             }
             return null;
         }
 
-        public override string GetAttribute(string name, string namespaceURI)
+        public override string? GetAttribute(string name, string namespaceURI)
         {
             if (!InAttributeActiveState)
             {
                 return null;
             }
-            string attr = reader.GetAttribute(name, namespaceURI);
+
+            string? attr = reader.GetAttribute(name, namespaceURI);
             if (attr != null)
             {
                 return attr;
             }
+
             for (int i = 0; i < _nsAttrCount; i++)
             {
-                if (name == _nsAttributes[i].localName && namespaceURI == _xmlnsUri)
+                if (name == _nsAttributes![i].localName && namespaceURI == _xmlnsUri)
                 {
+                    // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644
                     return _nsAttributes[i].value;
                 }
             }
+
             return null;
         }
 
@@ -293,7 +305,7 @@ namespace System.Xml
             }
             else if (i - n < _nsAttrCount)
             {
-                return _nsAttributes[i - n].value;
+                return _nsAttributes![i - n].value;
             }
             else
             {
@@ -313,9 +325,10 @@ namespace System.Xml
                 _useCurNode = false;
                 return true;
             }
+
             for (int i = 0; i < _nsAttrCount; i++)
             {
-                if (name == _nsAttributes[i].name)
+                if (name == _nsAttributes![i].name)
                 {
                     MoveToNsAttribute(i);
                     return true;
@@ -336,9 +349,10 @@ namespace System.Xml
                 _useCurNode = false;
                 return true;
             }
+
             for (int i = 0; i < _nsAttrCount; i++)
             {
-                if (name == _nsAttributes[i].localName && ns == _xmlnsUri)
+                if (name == _nsAttributes![i].localName && ns == _xmlnsUri)
                 {
                     MoveToNsAttribute(i);
                     return true;
@@ -854,6 +868,8 @@ namespace System.Xml
                                 {
                                     return 0;
                                 }
+
+                                Debug.Assert(_binDecoder != null);
                                 _binDecoder.SetNextOutputBuffer(buffer, index, count);
                                 _nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
                                 return _binDecoder.DecodedCount;
@@ -990,6 +1006,8 @@ namespace System.Xml
                                 {
                                     return 0;
                                 }
+
+                                Debug.Assert(_binDecoder != null);
                                 _binDecoder.SetNextOutputBuffer(buffer, index, count);
                                 _nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
                                 return _binDecoder.DecodedCount;
@@ -1142,7 +1160,7 @@ namespace System.Xml
             }
         }
 
-        public override string LookupNamespace(string prefix)
+        public override string? LookupNamespace(string prefix)
         {
             return ((IXmlNamespaceResolver)this).LookupNamespace(prefix);
         }
@@ -1165,8 +1183,7 @@ namespace System.Xml
             {
                 if (!_useCurNode)
                 {
-                    IXmlLineInfo lineInfo = reader as IXmlLineInfo;
-                    if (lineInfo != null)
+                    if (reader is IXmlLineInfo lineInfo)
                     {
                         return lineInfo.LineNumber;
                     }
@@ -1181,8 +1198,7 @@ namespace System.Xml
             {
                 if (!_useCurNode)
                 {
-                    IXmlLineInfo lineInfo = reader as IXmlLineInfo;
-                    if (lineInfo != null)
+                    if (reader is IXmlLineInfo lineInfo)
                     {
                         return lineInfo.LinePosition;
                     }
@@ -1208,7 +1224,7 @@ namespace System.Xml
             return _nsManager.GetNamespacesInScope(scope);
         }
 
-        string IXmlNamespaceResolver.LookupNamespace(string prefix)
+        string? IXmlNamespaceResolver.LookupNamespace(string prefix)
         {
             if (!InNamespaceActiveState)
             {
@@ -1217,7 +1233,7 @@ namespace System.Xml
             return _nsManager.LookupNamespace(prefix);
         }
 
-        string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
+        string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
         {
             if (!InNamespaceActiveState)
             {
@@ -1292,6 +1308,7 @@ namespace System.Xml
             {
                 _nsAttributes = new NodeData[InitialNamespaceAttributeCount];
             }
+
             if (index == _nsAttributes.Length)
             {
                 NodeData[] newNsAttrs = new NodeData[_nsAttributes.Length * 2];
@@ -1299,17 +1316,30 @@ namespace System.Xml
                 _nsAttributes = newNsAttrs;
             }
 
-            if (_nsAttributes[index] == null)
+            string localName;
+            string attrPrefix;
+            string name;
+
+            if (prefix.Length == 0)
             {
-                _nsAttributes[index] = new NodeData();
+                localName = _xmlns;
+                attrPrefix = string.Empty;
+                name = _xmlns;
             }
-            if (prefix.Length == 0)
+            else
+            {
+                localName = prefix;
+                attrPrefix = _xmlns;
+                name = reader.NameTable.Add(string.Concat(_xmlns, ":", prefix));
+            }
+
+            if (_nsAttributes[index] == null)
             {
-                _nsAttributes[index].Set(XmlNodeType.Attribute, _xmlns, string.Empty, _xmlns, _xmlnsUri, ns);
+                _nsAttributes[index] = new NodeData(XmlNodeType.Attribute, localName, attrPrefix, name, _xmlnsUri, ns);
             }
             else
             {
-                _nsAttributes[index].Set(XmlNodeType.Attribute, prefix, _xmlns, reader.NameTable.Add(string.Concat(_xmlns, ":", prefix)), _xmlnsUri, ns);
+                _nsAttributes[index].Set(XmlNodeType.Attribute, localName, attrPrefix, name, _xmlnsUri, ns);
             }
 
             Debug.Assert(_state == State.ClearNsAttributes || _state == State.Interactive || _state == State.PopNamespaceScope);
@@ -1322,13 +1352,13 @@ namespace System.Xml
         {
             for (int i = 0; i < _nsAttrCount; i++)
             {
-                if (Ref.Equal(prefix, _nsAttributes[i].prefix) &&
-                     Ref.Equal(localName, _nsAttributes[i].localName))
+                if (Ref.Equal(prefix, _nsAttributes![i].prefix) &&
+                     Ref.Equal(localName, _nsAttributes![i].localName)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644
                 {
                     if (i < _nsAttrCount - 1)
                     {
                         // swap
-                        NodeData tmpNodeData = _nsAttributes[i];
+                        NodeData tmpNodeData = _nsAttributes![i]; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644
                         _nsAttributes[i] = _nsAttributes[_nsAttrCount - 1];
                         _nsAttributes[_nsAttrCount - 1] = tmpNodeData;
                     }
@@ -1344,7 +1374,7 @@ namespace System.Xml
             reader.MoveToElement();
             _curNsAttr = index;
             _nsIncReadOffset = 0;
-            SetCurrentNode(_nsAttributes[index]);
+            SetCurrentNode(_nsAttributes![index]);
         }
 
         private bool InitReadElementContentAsBinary(State binaryState)
index d722745..ecbff26 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.
 
+#nullable enable
 using System;
 using System.Xml;
 using System.Diagnostics;
@@ -272,6 +273,8 @@ namespace System.Xml
                                 {
                                     return 0;
                                 }
+
+                                Debug.Assert(_binDecoder != null);
                                 _binDecoder.SetNextOutputBuffer(buffer, index, count);
                                 _nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
                                 return _binDecoder.DecodedCount;
@@ -408,6 +411,8 @@ namespace System.Xml
                                 {
                                     return 0;
                                 }
+
+                                Debug.Assert(_binDecoder != null);
                                 _binDecoder.SetNextOutputBuffer(buffer, index, count);
                                 _nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
                                 return _binDecoder.DecodedCount;
index b51c0fb..b8a45ad 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.
 
+#nullable enable
 using System;
 using System.IO;
 using System.Text;
@@ -149,7 +150,7 @@ namespace System.Xml
             get { return _impl.Depth; }
         }
 
-        public override string BaseURI
+        public override string? BaseURI
         {
             get { return _impl.BaseURI; }
         }
@@ -183,12 +184,12 @@ namespace System.Xml
 
         public override int AttributeCount { get { return _impl.AttributeCount; } }
 
-        public override string GetAttribute(string name)
+        public override string? GetAttribute(string name)
         {
             return _impl.GetAttribute(name);
         }
 
-        public override string GetAttribute(string localName, string namespaceURI)
+        public override string? GetAttribute(string localName, string? namespaceURI)
         {
             return _impl.GetAttribute(localName, namespaceURI);
         }
@@ -263,9 +264,9 @@ namespace System.Xml
             get { return _impl.NameTable; }
         }
 
-        public override string LookupNamespace(string prefix)
+        public override string? LookupNamespace(string prefix)
         {
-            string ns = _impl.LookupNamespace(prefix);
+            string? ns = _impl.LookupNamespace(prefix);
             if (ns != null && ns.Length == 0)
             {
                 ns = null;
@@ -342,12 +343,12 @@ namespace System.Xml
             return _impl.GetNamespacesInScope(scope);
         }
 
-        string IXmlNamespaceResolver.LookupNamespace(string prefix)
+        string? IXmlNamespaceResolver.LookupNamespace(string prefix)
         {
             return _impl.LookupNamespace(prefix);
         }
 
-        string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
+        string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
         {
             return _impl.LookupPrefix(namespaceName);
         }
@@ -377,7 +378,7 @@ namespace System.Xml
             set { _impl.Normalization = value; }
         }
 
-        public Encoding Encoding
+        public Encoding? Encoding
         {
             get { return _impl.Encoding; }
         }
@@ -444,7 +445,7 @@ namespace System.Xml
             get { return _impl; }
         }
 
-        internal override XmlNamespaceManager NamespaceManager
+        internal override XmlNamespaceManager? NamespaceManager
         {
             get { return _impl.NamespaceManager; }
         }
@@ -455,7 +456,7 @@ namespace System.Xml
             set { _impl.XmlValidatingReaderCompatibilityMode = value; }
         }
 
-        internal override IDtdInfo DtdInfo
+        internal override IDtdInfo? DtdInfo
         {
             get { return _impl.DtdInfo; }
         }
index 491d76a..ae7235e 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.
 
+#nullable enable
 using System.IO;
 using System.Text;
 using System.Xml.Schema;
@@ -11,12 +12,13 @@ using System.Collections.Generic;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Threading.Tasks;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
     internal partial class XmlTextReaderImpl : XmlReader, IXmlLineInfo, IXmlNamespaceResolver
     {
-        private static UTF8Encoding s_utf8BomThrowing;
+        private static UTF8Encoding? s_utf8BomThrowing;
 
         private static UTF8Encoding UTF8BomThrowing =>
             s_utf8BomThrowing ?? (s_utf8BomThrowing = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true, throwOnInvalidBytes: true));
@@ -119,19 +121,19 @@ namespace System.Xml
         {
             public bool useAsync = false;
 
-            public Stream inputStream;
-            public byte[] inputBytes;
+            public Stream? inputStream;
+            public byte[]? inputBytes;
             public int inputByteCount;
-            public Uri inputbaseUri;
-            public string inputUriStr;
-            public XmlResolver inputUriResolver;
-            public XmlParserContext inputContext;
-            public TextReader inputTextReader;
+            public Uri? inputbaseUri;
+            public string? inputUriStr;
+            public XmlResolver? inputUriResolver;
+            public XmlParserContext? inputContext;
+            public TextReader? inputTextReader;
 
             public InitInputType initType = InitInputType.Invalid;
         }
 
-        private LaterInitParam _laterInitParam = null;
+        private LaterInitParam? _laterInitParam = null;
 
         private enum InitInputType
         {
@@ -170,14 +172,14 @@ namespace System.Xml
         private int _attrDuplWalkCount;
         private bool _attrNeedNamespaceLookup;
         private bool _fullAttrCleanup;
-        private NodeData[] _attrDuplSortingArray;
+        private NodeData[]? _attrDuplSortingArray;
 
         // name table
-        private XmlNameTable _nameTable;
+        private XmlNameTable _nameTable = null!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/43523
         private bool _nameTableFromSettings;
 
         // resolver
-        private XmlResolver _xmlResolver;
+        private XmlResolver? _xmlResolver;
 
         // this is only for constructors that takes url
         private readonly string _url = string.Empty;
@@ -202,46 +204,46 @@ namespace System.Xml
         private readonly bool _v1Compat;
 
         // namespace handling
-        private XmlNamespaceManager _namespaceManager;
+        private XmlNamespaceManager? _namespaceManager;
         private string _lastPrefix = string.Empty;
 
         // xml context (xml:space, xml:lang, default namespace)
         private XmlContext _xmlContext;
 
         // stack of parsing states (=stack of entities)
-        private ParsingState[] _parsingStatesStack;
+        private ParsingState[]? _parsingStatesStack;
         private int _parsingStatesStackTop = -1;
 
         // current node base uri and encoding
-        private string _reportedBaseUri;
-        private Encoding _reportedEncoding;
+        private string? _reportedBaseUri;
+        private Encoding? _reportedEncoding;
 
         // DTD
-        private IDtdInfo _dtdInfo;
+        private IDtdInfo? _dtdInfo;
 
         // fragment parsing
         private XmlNodeType _fragmentType = XmlNodeType.Document;
-        private XmlParserContext _fragmentParserContext;
+        private XmlParserContext? _fragmentParserContext;
         private bool _fragment;
 
         // incremental read
-        private IncrementalReadDecoder _incReadDecoder;
+        private IncrementalReadDecoder? _incReadDecoder;
         private IncrementalReadState _incReadState;
         private LineInfo _incReadLineInfo;
-        private BinHexDecoder _binHexDecoder;
-        private Base64Decoder _base64Decoder;
+        private BinHexDecoder? _binHexDecoder;
+        private Base64Decoder? _base64Decoder;
         private int _incReadDepth;
         private int _incReadLeftStartPos;
         private int _incReadLeftEndPos;
-        private IncrementalReadCharsDecoder _readCharsDecoder;
+        private IncrementalReadCharsDecoder? _readCharsDecoder;
 
         // ReadAttributeValue helpers
         private int _attributeValueBaseEntityId;
         private bool _emptyEntityInAttributeResolved;
 
         // Validation helpers
-        private IValidationEventHandling _validationEventHandling;
-        private OnDefaultAttributeUseDelegate _onDefaultAttributeUse;
+        private IValidationEventHandling? _validationEventHandling;
+        private OnDefaultAttributeUseDelegate? _onDefaultAttributeUse;
 
         private bool _validatingReaderCompatFlag;
 
@@ -253,7 +255,7 @@ namespace System.Xml
         private int _nextEntityId = 1;
         private ParsingMode _parsingMode;
         private ReadState _readState = ReadState.Initial;
-        private IDtdEntityInfo _lastEntity;
+        private IDtdEntityInfo? _lastEntity;
         private bool _afterResetState;
         private int _documentStartBytePos;
         private int _readValueOffset;
@@ -263,7 +265,7 @@ namespace System.Xml
         private long _charactersFromEntities;
 
         // All entities that are currently being processed
-        private Dictionary<IDtdEntityInfo, IDtdEntityInfo> _currentEntities;
+        private Dictionary<IDtdEntityInfo, IDtdEntityInfo>? _currentEntities;
 
         // DOM helpers
         private bool _disableUndeclaredEntityCheck;
@@ -301,8 +303,16 @@ namespace System.Xml
 
         internal XmlTextReaderImpl()
         {
-            _curNode = new NodeData();
             _parsingFunction = ParsingFunction.NoData;
+            _outerReader = this;
+            _xmlContext = new XmlContext();
+            _nameTable = new NameTable();
+            _nodes = new NodeData[NodesInitialSize];
+            _nodes[0] = new NodeData();
+            _curNode = _nodes[0];
+            _stringBuilder = new StringBuilder();
+            _xml = _nameTable.Add("xml");
+            _xmlNs = _nameTable.Add("xmlns");
         }
 
         // Initializes a new instance of the XmlTextReaderImpl class with the specified XmlNameTable.
@@ -348,7 +358,7 @@ namespace System.Xml
         }
 
         // This constructor is used when creating XmlTextReaderImpl reader via "XmlReader.Create(..)"
-        private XmlTextReaderImpl(XmlResolver resolver, XmlReaderSettings settings, XmlParserContext context)
+        private XmlTextReaderImpl(XmlResolver? resolver, XmlReaderSettings settings, XmlParserContext? context)
         {
             _useAsync = settings.Async;
             _v1Compat = false;
@@ -357,7 +367,7 @@ namespace System.Xml
             _xmlContext = new XmlContext();
 
             // create or get nametable and namespace manager from XmlParserContext
-            XmlNameTable nt = settings.NameTable;
+            XmlNameTable? nt = settings.NameTable;
             if (context == null)
             {
                 if (nt == null)
@@ -369,6 +379,7 @@ namespace System.Xml
                 {
                     _nameTableFromSettings = true;
                 }
+
                 _nameTable = nt;
                 _namespaceManager = new XmlNamespaceManager(nt);
             }
@@ -443,16 +454,20 @@ namespace System.Xml
         internal XmlTextReaderImpl(Stream input) : this(string.Empty, input, new NameTable())
         {
         }
+
         internal XmlTextReaderImpl(Stream input, XmlNameTable nt) : this(string.Empty, input, nt)
         {
         }
+
         internal XmlTextReaderImpl(string url, Stream input) : this(url, input, new NameTable())
         {
         }
+
         internal XmlTextReaderImpl(string url, Stream input, XmlNameTable nt) : this(nt)
         {
             ConvertAbsoluteUnixPathToAbsoluteUri(ref url, resolver: null);
             _namespaceManager = new XmlNamespaceManager(nt);
+
             if (url == null || url.Length == 0)
             {
                 InitStreamInput(input, null);
@@ -461,6 +476,7 @@ namespace System.Xml
             {
                 InitStreamInput(url, input, null);
             }
+
             _reportedBaseUri = _ps.baseUriStr;
             _reportedEncoding = _ps.encoding;
         }
@@ -470,12 +486,15 @@ namespace System.Xml
         internal XmlTextReaderImpl(TextReader input) : this(string.Empty, input, new NameTable())
         {
         }
+
         internal XmlTextReaderImpl(TextReader input, XmlNameTable nt) : this(string.Empty, input, nt)
         {
         }
+
         internal XmlTextReaderImpl(string url, TextReader input) : this(url, input, new NameTable())
         {
         }
+
         internal XmlTextReaderImpl(string url, TextReader input, XmlNameTable nt) : this(nt)
         {
             ConvertAbsoluteUnixPathToAbsoluteUri(ref url, resolver: null);
@@ -491,7 +510,7 @@ namespace System.Xml
         internal XmlTextReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)
             : this((context != null && context.NameTable != null) ? context.NameTable : new NameTable())
         {
-            Encoding enc = (context != null) ? context.Encoding : null;
+            Encoding? enc = (context != null) ? context.Encoding : null;
             if (context == null || context.BaseURI == null || context.BaseURI.Length == 0)
             {
                 InitStreamInput(xmlFragment, enc);
@@ -502,6 +521,7 @@ namespace System.Xml
                 // it is safe as this resolver will not be used to resolve DTD url's
                 InitStreamInput(GetTempResolver().ResolveUri(null, context.BaseURI), xmlFragment, enc);
             }
+
             InitFragmentReader(fragType, context, false);
 
             _reportedBaseUri = _ps.baseUriStr;
@@ -527,6 +547,7 @@ namespace System.Xml
                 _reportedBaseUri = context.BaseURI;
                 InitStringInput(context.BaseURI, Encoding.Unicode, xmlFragment);
             }
+
             InitFragmentReader(fragType, context, false);
             _reportedEncoding = _ps.encoding;
         }
@@ -555,10 +576,12 @@ namespace System.Xml
             {
                 throw new ArgumentNullException(nameof(url));
             }
+
             if (url.Length == 0)
             {
                 throw new ArgumentException(SR.Xml_EmptyUrl, nameof(url));
             }
+
             _namespaceManager = new XmlNamespaceManager(nt);
 
             _url = url;
@@ -575,7 +598,7 @@ namespace System.Xml
 
         // Initializes a new instance of the XmlTextReaderImpl class with the specified arguments.
         // This constructor is used when creating XmlTextReaderImpl via XmlReader.Create
-        internal XmlTextReaderImpl(string uriStr, XmlReaderSettings settings, XmlParserContext context, XmlResolver uriResolver)
+        internal XmlTextReaderImpl(string uriStr, XmlReaderSettings settings, XmlParserContext? context, XmlResolver uriResolver)
             : this(settings.GetXmlResolver(), settings, context)
         {
             Uri baseUri = uriResolver.ResolveUri(null, uriStr);
@@ -604,6 +627,7 @@ namespace System.Xml
             _laterInitParam.inputContext = context;
             _laterInitParam.inputUriResolver = uriResolver;
             _laterInitParam.initType = InitInputType.UriString;
+
             if (!settings.Async)
             {
                 //if not set Async flag, finish the init in create stage.
@@ -617,18 +641,22 @@ namespace System.Xml
 
         private void FinishInitUriString()
         {
-            Stream stream = null;
+            Stream? stream = null;
+            Debug.Assert(_laterInitParam != null);
+            Debug.Assert(_laterInitParam.inputUriResolver != null);
+            Debug.Assert(_laterInitParam.inputbaseUri != null);
+            Debug.Assert(_reportedBaseUri != null);
 
             if (_laterInitParam.useAsync)
             {
-                //this will be hit when user create a XmlReader by setting Async, but the first call is Read() instead of ReadAsync(),
-                //then we still should create an async stream here. And wait for the method finish.
+                // this will be hit when user create a XmlReader by setting Async, but the first call is Read() instead of ReadAsync(),
+                // then we still should create an async stream here. And wait for the method finish.
                 Task<object> t = _laterInitParam.inputUriResolver.GetEntityAsync(_laterInitParam.inputbaseUri, string.Empty, typeof(Stream));
                 stream = (Stream)t.GetAwaiter().GetResult();
             }
             else
             {
-                stream = (Stream)_laterInitParam.inputUriResolver.GetEntity(_laterInitParam.inputbaseUri, string.Empty, typeof(Stream));
+                stream = (Stream?)_laterInitParam.inputUriResolver.GetEntity(_laterInitParam.inputbaseUri, string.Empty, typeof(Stream));
             }
 
             if (stream == null)
@@ -636,7 +664,7 @@ namespace System.Xml
                 throw new XmlException(SR.Xml_CannotResolveUrl, _laterInitParam.inputUriStr);
             }
 
-            Encoding enc = null;
+            Encoding? enc = null;
             // get Encoding from XmlParserContext
             if (_laterInitParam.inputContext != null)
             {
@@ -661,16 +689,18 @@ namespace System.Xml
                 stream.Dispose();
                 throw;
             }
+
             _laterInitParam = null;
         }
 
         // Initializes a new instance of the XmlTextReaderImpl class with the specified arguments.
         // This constructor is used when creating XmlTextReaderImpl via XmlReader.Create
-        internal XmlTextReaderImpl(Stream stream, byte[] bytes, int byteCount, XmlReaderSettings settings, Uri baseUri, string baseUriStr,
-                                    XmlParserContext context, bool closeInput)
+        internal XmlTextReaderImpl(Stream stream, byte[]? bytes, int byteCount, XmlReaderSettings settings, Uri? baseUri, string baseUriStr,
+                                    XmlParserContext? context, bool closeInput)
             : this(settings.GetXmlResolver(), settings, context)
         {
             ConvertAbsoluteUnixPathToAbsoluteUri(ref baseUriStr, settings.GetXmlResolver());
+
             // get BaseUri from XmlParserContext
             if (context != null)
             {
@@ -681,6 +711,7 @@ namespace System.Xml
                     {
                         Throw(SR.Xml_DoubleBaseUri);
                     }
+
                     Debug.Assert(baseUri == null);
                     baseUriStr = context.BaseURI;
                 }
@@ -710,7 +741,11 @@ namespace System.Xml
 
         private void FinishInitStream()
         {
-            Encoding enc = null;
+            Encoding? enc = null;
+
+            Debug.Assert(_laterInitParam != null);
+            Debug.Assert(_laterInitParam.inputStream != null);
+            Debug.Assert(_reportedBaseUri != null);
 
             // get Encoding from XmlParserContext
             if (_laterInitParam.inputContext != null)
@@ -728,12 +763,13 @@ namespace System.Xml
             {
                 ProcessDtdFromParserContext(_laterInitParam.inputContext);
             }
+
             _laterInitParam = null;
         }
 
         // Initializes a new instance of the XmlTextReaderImpl class with the specified arguments.
         // This constructor is used when creating XmlTextReaderImpl via XmlReader.Create
-        internal XmlTextReaderImpl(TextReader input, XmlReaderSettings settings, string baseUriStr, XmlParserContext context)
+        internal XmlTextReaderImpl(TextReader input, XmlReaderSettings settings, string baseUriStr, XmlParserContext? context)
             : this(settings.GetXmlResolver(), settings, context)
         {
             ConvertAbsoluteUnixPathToAbsoluteUri(ref baseUriStr, settings.GetXmlResolver());
@@ -766,6 +802,10 @@ namespace System.Xml
 
         private void FinishInitTextReader()
         {
+            Debug.Assert(_laterInitParam != null);
+            Debug.Assert(_laterInitParam.inputTextReader != null);
+            Debug.Assert(_reportedBaseUri != null);
+
             // init ParsingState
             InitTextReaderInput(_reportedBaseUri, _laterInitParam.inputTextReader);
 
@@ -813,6 +853,7 @@ namespace System.Xml
                     case XmlNodeType.Document: settings.ConformanceLevel = ConformanceLevel.Document; break;
                     default: Debug.Fail($"Unexpected fragment type {_fragmentType}"); goto case XmlNodeType.None;
                 }
+
                 settings.CheckCharacters = _checkCharacters;
                 settings.LineNumberOffset = _lineNumberOffset;
                 settings.LinePositionOffset = _linePositionOffset;
@@ -860,7 +901,7 @@ namespace System.Xml
         {
             get
             {
-                return _curNode.ns;
+                return _curNode.ns ?? string.Empty;
             }
         }
 
@@ -890,6 +931,7 @@ namespace System.Xml
                         FinishOtherValueIterator();
                     }
                 }
+
                 return _curNode.StringValue;
             }
         }
@@ -904,7 +946,7 @@ namespace System.Xml
         }
 
         // Returns the base URI of the current node.
-        public override string BaseURI
+        public override string? BaseURI
         {
             get
             {
@@ -1003,7 +1045,7 @@ namespace System.Xml
         }
 
         // Returns value of an attribute with the specified Name
-        public override string GetAttribute(string name)
+        public override string? GetAttribute(string name)
         {
             int i;
             if (!name.Contains(':'))
@@ -1014,21 +1056,24 @@ namespace System.Xml
             {
                 i = GetIndexOfAttributeWithPrefix(name);
             }
+
             return (i >= 0) ? _nodes[i].StringValue : null;
         }
 
         // Returns value of an attribute with the specified LocalName and NamespaceURI
-        public override string GetAttribute(string localName, string namespaceURI)
+        public override string? GetAttribute(string localName, string? namespaceURI)
         {
             namespaceURI = (namespaceURI == null) ? string.Empty : _nameTable.Get(namespaceURI);
-            localName = _nameTable.Get(localName);
+            string? localNameAtomized = _nameTable.Get(localName);
+
             for (int i = _index + 1; i < _index + _attrCount + 1; i++)
             {
-                if (Ref.Equal(_nodes[i].localName, localName) && Ref.Equal(_nodes[i].ns, namespaceURI))
+                if (Ref.Equal(_nodes[i].localName, localNameAtomized) && Ref.Equal(_nodes[i].ns, namespaceURI))
                 {
                     return _nodes[i].StringValue;
                 }
             }
+
             return null;
         }
 
@@ -1039,6 +1084,7 @@ namespace System.Xml
             {
                 throw new ArgumentOutOfRangeException(nameof(i));
             }
+
             return _nodes[_index + i + 1].StringValue;
         }
 
@@ -1072,14 +1118,14 @@ namespace System.Xml
         }
 
         // Moves to an attribute with the specified LocalName and NamespceURI
-        public override bool MoveToAttribute(string localName, string namespaceURI)
+        public override bool MoveToAttribute(string localName, string? namespaceURI)
         {
-            namespaceURI = (namespaceURI == null) ? string.Empty : _nameTable.Get(namespaceURI);
-            localName = _nameTable.Get(localName);
+            string? namespaceURIAtomized = (namespaceURI == null) ? string.Empty : _nameTable.Get(namespaceURI);
+            string? localNameAtomized = _nameTable.Get(localName);
             for (int i = _index + 1; i < _index + _attrCount + 1; i++)
             {
-                if (Ref.Equal(_nodes[i].localName, localName) &&
-                     Ref.Equal(_nodes[i].ns, namespaceURI))
+                if (Ref.Equal(_nodes[i].localName, localNameAtomized) &&
+                     Ref.Equal(_nodes[i].ns, namespaceURIAtomized))
                 {
                     _curAttrIndex = i - _index - 1;
                     _curNode = _nodes[i];
@@ -1091,6 +1137,7 @@ namespace System.Xml
                     return true;
                 }
             }
+
             return false;
         }
 
@@ -1106,6 +1153,7 @@ namespace System.Xml
             {
                 FinishAttributeValueIterator();
             }
+
             _curAttrIndex = i;
             _curNode = _nodes[_index + 1 + _curAttrIndex];
         }
@@ -1164,6 +1212,8 @@ namespace System.Xml
 
         private void FinishInit()
         {
+            Debug.Assert(_laterInitParam != null);
+
             switch (_laterInitParam.initType)
             {
                 case InitInputType.UriString:
@@ -1375,13 +1425,14 @@ namespace System.Xml
         }
 
         // Returns NamespaceURI associated with the specified prefix in the current namespace scope.
-        public override string LookupNamespace(string prefix)
+        public override string? LookupNamespace(string prefix)
         {
             if (!_supportNamespaces)
             {
                 return null;
             }
 
+            Debug.Assert(_namespaceManager != null);
             return _namespaceManager.LookupNamespace(prefix);
         }
 
@@ -1495,7 +1546,7 @@ namespace System.Xml
                     case EntityType.ExpandedInAttribute:
                     case EntityType.Expanded:
                         _nextParsingFunction = _parsingFunction;
-                        if (_ps.charsUsed - _ps.charPos == 0 && !_ps.entity.IsExternal)
+                        if (_ps.charsUsed - _ps.charPos == 0 && !_ps.entity!.IsExternal)
                         {  // empty internal entity value
                             _parsingFunction = ParsingFunction.AfterResolveEmptyEntityInContent;
                         }
@@ -1897,6 +1948,8 @@ namespace System.Xml
                     {
                         copyCount = endPos - startPos;
                     }
+
+                    Debug.Assert(_ps.chars != null);
                     BlockCopyChars(_ps.chars, startPos, buffer, (index + readCount), copyCount);
 
                     readCount += copyCount;
@@ -1920,6 +1973,7 @@ namespace System.Xml
                 }
 
                 _readValueOffset = 0;
+                Debug.Assert(_ps.chars != null);
                 _curNode.SetValue(_ps.chars, startPos, endPos - startPos);
             }
             return readCount;
@@ -1959,12 +2013,12 @@ namespace System.Xml
             return this.GetNamespacesInScope(scope);
         }
 
-        string IXmlNamespaceResolver.LookupNamespace(string prefix)
+        string? IXmlNamespaceResolver.LookupNamespace(string prefix)
         {
             return this.LookupNamespace(prefix);
         }
 
-        string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
+        string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
         {
             return this.LookupPrefix(namespaceName);
         }
@@ -1972,13 +2026,15 @@ namespace System.Xml
         // Internal IXmlNamespaceResolver methods
         internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
         {
+            Debug.Assert(_namespaceManager != null);
             return _namespaceManager.GetNamespacesInScope(scope);
         }
 
         // NOTE: there already is virtual method for "string LookupNamespace(string prefix)"
 
-        internal string LookupPrefix(string namespaceName)
+        internal string? LookupPrefix(string namespaceName)
         {
+            Debug.Assert(_namespaceManager != null);
             return _namespaceManager.LookupPrefix(namespaceName);
         }
 
@@ -1998,6 +2054,7 @@ namespace System.Xml
                 {
                     throw new InvalidOperationException(SR.Xml_InvalidOperation);
                 }
+
                 _supportNamespaces = value;
                 if (value)
                 {
@@ -2012,7 +2069,9 @@ namespace System.Xml
                             _namespaceManager = new XmlNamespaceManager(_nameTable);
                         }
                     }
-                    _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty);
+
+                    Debug.Assert(_namespaceManager != null);
+                    _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty)!;
                 }
                 else
                 {
@@ -2020,6 +2079,7 @@ namespace System.Xml
                     {
                         _namespaceManager = new NoNamespaceManager();
                     }
+
                     _xmlContext.defaultNamespace = string.Empty;
                 }
             }
@@ -2050,7 +2110,7 @@ namespace System.Xml
         }
 
         // Returns the Encoding of the XML document
-        internal Encoding Encoding
+        internal Encoding? Encoding
         {
             get
             {
@@ -2078,6 +2138,7 @@ namespace System.Xml
                 {
                     throw new XmlException(SR.Xml_WhitespaceHandling, string.Empty);
                 }
+
                 _whitespaceHandling = value;
             }
         }
@@ -2098,6 +2159,7 @@ namespace System.Xml
                 {
                     throw new ArgumentOutOfRangeException(nameof(value));
                 }
+
                 _dtdProcessing = value;
             }
         }
@@ -2115,6 +2177,7 @@ namespace System.Xml
                 {
                     throw new XmlException(SR.Xml_EntityHandling, string.Empty);
                 }
+
                 _entityHandling = value;
             }
         }
@@ -2134,9 +2197,10 @@ namespace System.Xml
                 _xmlResolverIsSet = true;
                 // invalidate all baseUris on the stack
                 _ps.baseUri = null;
+
                 for (int i = 0; i <= _parsingStatesStackTop; i++)
                 {
-                    _parsingStatesStack[i].baseUri = null;
+                    _parsingStatesStack![i].baseUri = null;
                 }
             }
         }
@@ -2158,6 +2222,7 @@ namespace System.Xml
 
             // Clear
             ResetAttributes();
+            Debug.Assert(_namespaceManager != null);
             while (_namespaceManager.PopScope()) ;
 
             while (InEntity)
@@ -2186,7 +2251,6 @@ namespace System.Xml
         internal TextReader GetRemainder()
         {
             Debug.Assert(_v1Compat, "XmlTextReaderImpl.GetRemainder cannot be called on reader created via XmlReader.Create.");
-
             Debug.Assert(_stringBuilder.Length == 0);
             switch (_parsingFunction)
             {
@@ -2350,7 +2414,7 @@ namespace System.Xml
             }
         }
 
-        internal IXmlNamespaceResolver DtdParserProxy_NamespaceResolver
+        internal IXmlNamespaceResolver? DtdParserProxy_NamespaceResolver
         {
             get
             {
@@ -2390,7 +2454,7 @@ namespace System.Xml
             }
         }
 
-        internal Uri DtdParserProxy_BaseUri
+        internal Uri? DtdParserProxy_BaseUri
         {
             // SxS: ps.baseUri may be initialized in the constructor (public XmlTextReaderImpl( string url, XmlNameTable nt )) based on
             // url provided by the user. Here the property returns ps.BaseUri - so it may expose a path.
@@ -2400,6 +2464,7 @@ namespace System.Xml
                 {
                     _ps.baseUri = _xmlResolver.ResolveUri(null, _ps.baseUriStr);
                 }
+
                 return _ps.baseUri;
             }
         }
@@ -2412,7 +2477,7 @@ namespace System.Xml
             }
         }
 
-        internal char[] DtdParserProxy_ParsingBuffer
+        internal char[]? DtdParserProxy_ParsingBuffer
         {
             get
             {
@@ -2457,7 +2522,7 @@ namespace System.Xml
             }
         }
 
-        internal IValidationEventHandling DtdParserProxy_ValidationEventHandling
+        internal IValidationEventHandling? DtdParserProxy_ValidationEventHandling
         {
             get
             {
@@ -2592,7 +2657,7 @@ namespace System.Xml
             return retValue;
         }
 
-        internal bool DtdParserProxy_PopEntity(out IDtdEntityInfo oldEntity, out int newEntityId)
+        internal bool DtdParserProxy_PopEntity(out IDtdEntityInfo? oldEntity, out int newEntityId)
         {
             if (_parsingStatesStackTop == -1)
             {
@@ -2600,6 +2665,7 @@ namespace System.Xml
                 newEntityId = -1;
                 return false;
             }
+
             oldEntity = _ps.entity;
             PopEntity();
             newEntityId = _ps.entityId;
@@ -2608,7 +2674,7 @@ namespace System.Xml
 
         // SxS: The caller did not provide any SxS sensitive name or resource. No resource is being exposed either.
         // It is OK to suppress SxS warning.
-        internal bool DtdParserProxy_PushExternalSubset(string systemId, string publicId)
+        internal bool DtdParserProxy_PushExternalSubset(string? systemId, string? publicId)
         {
             Debug.Assert(_parsingStatesStackTop == -1);
             Debug.Assert((systemId != null && systemId.Length > 0) || (publicId != null && publicId.Length > 0));
@@ -2617,10 +2683,14 @@ namespace System.Xml
             {
                 return false;
             }
+
+            Debug.Assert(_xmlResolver != null);
+
             if (_ps.baseUri == null && !string.IsNullOrEmpty(_ps.baseUriStr))
             {
                 _ps.baseUri = _xmlResolver.ResolveUri(null, _ps.baseUriStr);
             }
+
             PushExternalEntityOrSubset(publicId, systemId, _ps.baseUri, null);
 
             _ps.entity = null;
@@ -2679,90 +2749,108 @@ namespace System.Xml
         //
         // Throw methods: Sets the reader current position to pos, sets the error state and throws exception
         //
+        [DoesNotReturn]
         private void Throw(int pos, string res, string arg)
         {
             _ps.charPos = pos;
             Throw(res, arg);
         }
 
+        [DoesNotReturn]
         private void Throw(int pos, string res, string[] args)
         {
             _ps.charPos = pos;
             Throw(res, args);
         }
 
+        [DoesNotReturn]
         private void Throw(int pos, string res)
         {
             _ps.charPos = pos;
             Throw(res, string.Empty);
         }
 
+        [DoesNotReturn]
         private void Throw(string res)
         {
             Throw(res, string.Empty);
         }
 
+        [DoesNotReturn]
         private void Throw(string res, int lineNo, int linePos)
         {
             Throw(new XmlException(res, string.Empty, lineNo, linePos, _ps.baseUriStr));
         }
 
-        private void Throw(string res, string arg)
+        [DoesNotReturn]
+        private void Throw(string res, string? arg)
         {
             Throw(new XmlException(res, arg, _ps.LineNo, _ps.LinePos, _ps.baseUriStr));
         }
 
-        private void Throw(string res, string arg, int lineNo, int linePos)
+        [DoesNotReturn]
+        private void Throw(string res, string? arg, int lineNo, int linePos)
         {
             Throw(new XmlException(res, arg, lineNo, linePos, _ps.baseUriStr));
         }
 
-        private void Throw(string res, string[] args)
+        [DoesNotReturn]
+        private void Throw(string res, string?[] args)
         {
             Throw(new XmlException(res, args, _ps.LineNo, _ps.LinePos, _ps.baseUriStr));
         }
 
-        private void Throw(string res, string arg, Exception innerException)
+        [DoesNotReturn]
+        private void Throw(string res, string? arg, Exception innerException)
         {
-            Throw(res, new string[] { arg }, innerException);
+            Throw(res, new string?[] { arg }, innerException);
         }
 
-        private void Throw(string res, string[] args, Exception innerException)
+        [DoesNotReturn]
+        private void Throw(string res, string?[] args, Exception innerException)
         {
             Throw(new XmlException(res, args, innerException, _ps.LineNo, _ps.LinePos, _ps.baseUriStr));
         }
 
+        [DoesNotReturn]
         private void Throw(Exception e)
         {
             SetErrorState();
-            XmlException xmlEx = e as XmlException;
+            XmlException? xmlEx = e as XmlException;
+
             if (xmlEx != null)
             {
                 _curNode.SetLineInfo(xmlEx.LineNumber, xmlEx.LinePosition);
             }
+
             throw e;
         }
 
+        [DoesNotReturn]
         private void ReThrow(Exception e, int lineNo, int linePos)
         {
-            Throw(new XmlException(e.Message, (Exception)null, lineNo, linePos, _ps.baseUriStr));
+            Throw(new XmlException(e.Message, (Exception?)null, lineNo, linePos, _ps.baseUriStr));
         }
 
+        [DoesNotReturn]
         private void ThrowWithoutLineInfo(string res)
         {
             Throw(new XmlException(res, string.Empty, _ps.baseUriStr));
         }
 
+        [DoesNotReturn]
         private void ThrowWithoutLineInfo(string res, string arg)
         {
             Throw(new XmlException(res, arg, _ps.baseUriStr));
         }
 
-        private void ThrowWithoutLineInfo(string res, string[] args, Exception innerException)
+        [DoesNotReturn]
+        private void ThrowWithoutLineInfo(string res, string?[] args, Exception? innerException)
         {
             Throw(new XmlException(res, args, innerException, 0, 0, _ps.baseUriStr));
         }
 
+        [DoesNotReturn]
         private void ThrowInvalidChar(char[] data, int length, int invCharPos)
         {
             Throw(invCharPos, SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, length, invCharPos));
@@ -2774,7 +2862,7 @@ namespace System.Xml
             _readState = ReadState.Error;
         }
 
-        private void SendValidationEvent(XmlSeverityType severity, string code, string arg, int lineNo, int linePos)
+        private void SendValidationEvent(XmlSeverityType severity, string code, string? arg, int lineNo, int linePos)
         {
             SendValidationEvent(severity, new XmlSchemaException(code, arg, _ps.baseUriStr, lineNo, linePos));
         }
@@ -2809,6 +2897,7 @@ namespace System.Xml
             {
                 FinishReadContentAsBinary();
             }
+
             if (_parsingFunction == ParsingFunction.InReadAttributeValue)
             {
                 while (_ps.entityId != _attributeValueBaseEntityId)
@@ -2829,29 +2918,29 @@ namespace System.Xml
             }
         }
 
-        private void InitStreamInput(Stream stream, Encoding encoding)
+        private void InitStreamInput(Stream stream, Encoding? encoding)
         {
             InitStreamInput(null, string.Empty, stream, null, 0, encoding);
         }
 
-        private void InitStreamInput(string baseUriStr, Stream stream, Encoding encoding)
+        private void InitStreamInput(string baseUriStr, Stream stream, Encoding? encoding)
         {
             Debug.Assert(baseUriStr != null);
             InitStreamInput(null, baseUriStr, stream, null, 0, encoding);
         }
 
-        private void InitStreamInput(Uri baseUri, Stream stream, Encoding encoding)
+        private void InitStreamInput(Uri? baseUri, Stream stream, Encoding? encoding)
         {
             Debug.Assert(baseUri != null);
             InitStreamInput(baseUri, baseUri.ToString(), stream, null, 0, encoding);
         }
 
-        private void InitStreamInput(Uri baseUri, string baseUriStr, Stream stream, Encoding encoding)
+        private void InitStreamInput(Uri? baseUri, string baseUriStr, Stream stream, Encoding? encoding)
         {
             InitStreamInput(baseUri, baseUriStr, stream, null, 0, encoding);
         }
 
-        private void InitStreamInput(Uri baseUri, string baseUriStr, Stream stream, byte[] bytes, int byteCount, Encoding encoding)
+        private void InitStreamInput(Uri? baseUri, string baseUriStr, Stream stream, byte[]? bytes, int byteCount, Encoding? encoding)
         {
             Debug.Assert(_ps.charPos == 0 && _ps.charsUsed == 0 && _ps.textReader == null);
             Debug.Assert(baseUriStr != null);
@@ -2910,6 +2999,7 @@ namespace System.Xml
             {
                 encoding = DetectEncoding();
             }
+
             SetupEncoding(encoding);
 
             // eat preamble
@@ -2929,7 +3019,7 @@ namespace System.Xml
             InitTextReaderInput(baseUriStr, null, input);
         }
 
-        private void InitTextReaderInput(string baseUriStr, Uri baseUri, TextReader input)
+        private void InitTextReaderInput(string baseUriStr, Uri? baseUri, TextReader input)
         {
             Debug.Assert(_ps.charPos == 0 && _ps.charsUsed == 0 && _ps.stream == null);
             Debug.Assert(baseUriStr != null);
@@ -2958,7 +3048,7 @@ namespace System.Xml
             ReadData();
         }
 
-        private void InitStringInput(string baseUriStr, Encoding originalEncoding, string str)
+        private void InitStringInput(string baseUriStr, Encoding? originalEncoding, string str)
         {
             Debug.Assert(_ps.stream == null && _ps.textReader == null);
             Debug.Assert(_ps.charPos == 0 && _ps.charsUsed == 0);
@@ -2980,7 +3070,7 @@ namespace System.Xml
             _ps.isEof = true;
         }
 
-        private void InitFragmentReader(XmlNodeType fragmentType, XmlParserContext parserContext, bool allowXmlDeclFragment)
+        private void InitFragmentReader(XmlNodeType fragmentType, XmlParserContext? parserContext, bool allowXmlDeclFragment)
         {
             _fragmentParserContext = parserContext;
 
@@ -2989,7 +3079,7 @@ namespace System.Xml
                 if (parserContext.NamespaceManager != null)
                 {
                     _namespaceManager = parserContext.NamespaceManager;
-                    _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty);
+                    _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty)!;
                 }
                 else
                 {
@@ -3041,6 +3131,7 @@ namespace System.Xml
                     Throw(SR.Xml_PartialContentNodeTypeNotSupportedEx, fragmentType.ToString());
                     return;
             }
+
             _fragmentType = fragmentType;
             _fragment = true;
         }
@@ -3081,7 +3172,7 @@ namespace System.Xml
 
             try
             {
-                _ps.stream = (Stream)tmpResolver.GetEntity(_ps.baseUri, null, typeof(Stream));
+                _ps.stream = (Stream?)tmpResolver.GetEntity(_ps.baseUri, null, typeof(Stream));
             }
             catch
             {
@@ -3094,12 +3185,13 @@ namespace System.Xml
                 ThrowWithoutLineInfo(SR.Xml_CannotResolveUrl, _ps.baseUriStr);
             }
 
+            Debug.Assert(_ps.stream != null);
             InitStreamInput(_ps.baseUri, _ps.baseUriStr, _ps.stream, null);
             _reportedEncoding = _ps.encoding;
         }
 
         // Stream input only: detect encoding from the first 4 bytes of the byte buffer starting at ps.bytes[ps.bytePos]
-        private Encoding DetectEncoding()
+        private Encoding? DetectEncoding()
         {
             Debug.Assert(_ps.bytes != null);
             Debug.Assert(_ps.bytePos == 0);
@@ -3108,6 +3200,7 @@ namespace System.Xml
             {
                 return null;
             }
+
             int first2Bytes = _ps.bytes[0] << 8 | _ps.bytes[1];
             int next2Bytes = (_ps.bytesUsed >= 4) ? (_ps.bytes[2] << 8 | _ps.bytes[3]) : 0;
 
@@ -3183,7 +3276,7 @@ namespace System.Xml
             return null;
         }
 
-        private void SetupEncoding(Encoding encoding)
+        private void SetupEncoding(Encoding? encoding)
         {
             if (encoding == null)
             {
@@ -3205,6 +3298,8 @@ namespace System.Xml
 
         private void EatPreamble()
         {
+            Debug.Assert(_ps.encoding != null);
+            Debug.Assert(_ps.bytes != null);
             ReadOnlySpan<byte> preamble = _ps.encoding.Preamble;
             int preambleLen = preamble.Length;
             int i;
@@ -3224,6 +3319,7 @@ namespace System.Xml
         // Switches the reader's encoding
         private void SwitchEncoding(Encoding newEncoding)
         {
+            Debug.Assert(_ps.encoding != null);
             if ((newEncoding.WebName != _ps.encoding.WebName || _ps.decoder is SafeAsciiDecoder) && !_afterResetState)
             {
                 Debug.Assert(_ps.stream != null);
@@ -3238,6 +3334,8 @@ namespace System.Xml
         // Performs checks whether switching from current encoding to specified encoding is allowed.
         private Encoding CheckEncoding(string newEncodingName)
         {
+            Debug.Assert(_ps.encoding != null);
+
             // encoding can be switched on stream input only
             if (_ps.stream == null)
             {
@@ -3265,7 +3363,7 @@ namespace System.Xml
                 return _ps.encoding;
             }
 
-            Encoding newEncoding = null;
+            Encoding? newEncoding = null;
             if (string.Equals(newEncodingName, "utf-8", StringComparison.OrdinalIgnoreCase))
             {
                 newEncoding = UTF8BomThrowing;
@@ -3284,6 +3382,8 @@ namespace System.Xml
                 {
                     Throw(SR.Xml_UnknownEncoding, newEncodingName, innerEx);
                 }
+
+                Debug.Assert(newEncoding != null);
                 Debug.Assert(newEncoding.EncodingName != "UTF-8");
             }
 
@@ -3313,6 +3413,7 @@ namespace System.Xml
                     "We didn't correctly count some of the decoded characters against the MaxCharactersInDocument.");
                 _charactersInDocument -= _ps.charsUsed - _ps.charPos;
             }
+
             if (_maxCharactersFromEntities > 0)
             {
                 if (InEntity)
@@ -3326,8 +3427,11 @@ namespace System.Xml
             _ps.bytePos = _documentStartBytePos; // byte position after preamble
             if (_ps.charPos > 0)
             {
+                Debug.Assert(_ps.encoding != null);
+                Debug.Assert(_ps.chars != null);
                 _ps.bytePos += _ps.encoding.GetByteCount(_ps.chars, 0, _ps.charPos);
             }
+
             _ps.charsUsed = _ps.charPos;
             _ps.isEof = false;
         }
@@ -3350,6 +3454,7 @@ namespace System.Xml
                 return 0;
             }
 
+            Debug.Assert(_ps.chars != null);
             int charsRead;
             if (_ps.appendMode)
             {
@@ -3372,6 +3477,7 @@ namespace System.Xml
                     // the byte buffer is full -> allocate a new one
                     if (_ps.bytesUsed - _ps.bytePos < MaxByteSequenceLen)
                     {
+                        Debug.Assert(_ps.bytes != null);
                         if (_ps.bytes.Length - _ps.bytesUsed < MaxByteSequenceLen)
                         {
                             byte[] newBytes = new byte[_ps.bytes.Length * 2];
@@ -3430,9 +3536,11 @@ namespace System.Xml
                         }
                         else
                         {
+                            Debug.Assert(_ps.bytes != null);
                             BlockCopy(_ps.bytes, _ps.bytePos, _ps.bytes, 0, bytesLeft);
                             _ps.bytesUsed = bytesLeft;
                         }
+
                         _ps.bytePos = 0;
                     }
                 }
@@ -3443,6 +3551,8 @@ namespace System.Xml
             {
                 if (!_ps.isStreamEof)
                 {
+                    Debug.Assert(_ps.bytes != null);
+
                     // read new bytes
                     if (_ps.bytePos == _ps.bytesUsed && _ps.bytes.Length - _ps.bytesUsed > 0)
                     {
@@ -3483,6 +3593,7 @@ namespace System.Xml
                 Debug.Assert(_ps.charsUsed < _ps.chars.Length);
                 _ps.isEof = true;
             }
+
             _ps.chars[_ps.charsUsed] = (char)0;
             return charsRead;
         }
@@ -3491,6 +3602,7 @@ namespace System.Xml
         private int GetChars(int maxCharsCount)
         {
             Debug.Assert(_ps.stream != null && _ps.decoder != null && _ps.bytes != null);
+            Debug.Assert(_ps.chars != null);
             Debug.Assert(maxCharsCount <= _ps.chars.Length - _ps.charsUsed - 1);
 
             // determine the maximum number of bytes we can pass to the decoder
@@ -3530,10 +3642,14 @@ namespace System.Xml
                     int chDec;
                     int bDec;
                     bool completed;
+                    Debug.Assert(_ps.decoder != null);
+                    Debug.Assert(_ps.bytes != null);
+                    Debug.Assert(_ps.chars != null);
                     _ps.decoder.Convert(_ps.bytes, _ps.bytePos + bytesDecoded, 1, _ps.chars, _ps.charsUsed + charsDecoded, 2, false, out bDec, out chDec, out completed);
                     charsDecoded += chDec;
                     bytesDecoded += bDec;
                 }
+
                 Debug.Fail("We should get an exception again.");
             }
             catch (ArgumentException)
@@ -3544,6 +3660,7 @@ namespace System.Xml
             {
                 Throw(_ps.charsUsed, SR.Xml_InvalidCharInThisEncoding);
             }
+
             charsCount = charsDecoded;
             bytesCount = bytesDecoded;
         }
@@ -3575,6 +3692,7 @@ namespace System.Xml
 
         private void ShiftBuffer(int sourcePos, int destPos, int count)
         {
+            Debug.Assert(_ps.chars != null);
             BlockCopyChars(_ps.chars, sourcePos, _ps.chars, destPos, count);
         }
 
@@ -3590,7 +3708,7 @@ namespace System.Xml
             }
 
             if (!XmlConvert.StrEqual(_ps.chars, _ps.charPos, 5, XmlDeclarationBeginning) ||
-                 _xmlCharType.IsNameSingleChar(_ps.chars[_ps.charPos + 5])
+                 _xmlCharType.IsNameSingleChar(_ps.chars![_ps.charPos + 5])
 #if XML10_FIFTH_EDITION
                  || xmlCharType.IsNCNameHighSurrogateChar( ps.chars[ps.charPos + 5] )
 #endif
@@ -3604,6 +3722,7 @@ namespace System.Xml
                 _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos + 2);
                 _curNode.SetNamedNode(XmlNodeType.XmlDeclaration, _xml);
             }
+
             _ps.charPos += 5;
 
             // parsing of text declarations cannot change global stringBuidler or curNode as we may be in the middle of a text node
@@ -3612,7 +3731,7 @@ namespace System.Xml
 
             // parse version, encoding & standalone attributes
             int xmlDeclState = 0;   // <?xml (0) version='1.0' (1) encoding='__' (2) standalone='__' (3) ?>
-            Encoding encoding = null;
+            Encoding? encoding = null;
 
             while (true)
             {
@@ -3651,6 +3770,7 @@ namespace System.Xml
                             if (_afterResetState)
                             {
                                 // check for invalid encoding switches to default encoding
+                                Debug.Assert(_ps.encoding != null);
                                 string encodingName = _ps.encoding.WebName;
                                 if (encodingName != "utf-8" && encodingName != "utf-16" &&
                                      encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding))
@@ -3688,7 +3808,7 @@ namespace System.Xml
                 // read attribute name
                 int nameEndPos = ParseName();
 
-                NodeData attr = null;
+                NodeData? attr = null;
                 switch (_ps.chars[_ps.charPos])
                 {
                     case 'v':
@@ -3729,8 +3849,10 @@ namespace System.Xml
                         Throw(isTextDecl ? SR.Xml_InvalidTextDecl : SR.Xml_InvalidXmlDecl);
                         break;
                 }
+
                 if (!isTextDecl)
                 {
+                    Debug.Assert(attr != null);
                     attr.SetLineInfo(_ps.LineNo, _ps.LinePos);
                 }
                 sb.Append(_ps.chars, _ps.charPos, nameEndPos - _ps.charPos);
@@ -3762,6 +3884,7 @@ namespace System.Xml
                 _ps.charPos++;
                 if (!isTextDecl)
                 {
+                    Debug.Assert(attr != null);
                     attr.quoteChar = quoteChar;
                     attr.SetLineInfo2(_ps.LineNo, _ps.LinePos);
                 }
@@ -3796,6 +3919,7 @@ namespace System.Xml
 #endif
                                 if (!isTextDecl)
                                 {
+                                    Debug.Assert(attr != null);
                                     attr.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos);
                                 }
                                 xmlDeclState = 1;
@@ -3811,6 +3935,7 @@ namespace System.Xml
                             encoding = CheckEncoding(encName);
                             if (!isTextDecl)
                             {
+                                Debug.Assert(attr != null);
                                 attr.SetValue(encName);
                             }
                             xmlDeclState = 2;
@@ -3831,6 +3956,7 @@ namespace System.Xml
                             }
                             if (!isTextDecl)
                             {
+                                Debug.Assert(attr != null);
                                 attr.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos);
                             }
                             xmlDeclState = 3;
@@ -3876,6 +4002,7 @@ namespace System.Xml
             if (_afterResetState)
             {
                 // check for invalid encoding switches to default encoding
+                Debug.Assert(_ps.encoding != null);
                 string encodingName = _ps.encoding.WebName;
                 if (encodingName != "utf-8" && encodingName != "utf-16" &&
                     encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding))
@@ -3907,6 +4034,7 @@ namespace System.Xml
             {
                 bool needMoreChars = false;
                 int pos = _ps.charPos;
+                Debug.Assert(_ps.chars != null);
                 char[] chars = _ps.chars;
 
                 // some tag
@@ -4141,6 +4269,7 @@ namespace System.Xml
             while (true)
             {
                 int pos = _ps.charPos;
+                Debug.Assert(_ps.chars != null);
                 char[] chars = _ps.chars;
 
                 switch (chars[pos])
@@ -4305,6 +4434,7 @@ namespace System.Xml
                         _stringBuilder.Append('.');
                     }
                 }
+
                 Throw(_ps.charsUsed, SR.Xml_UnexpectedEOFInElementContent, _stringBuilder.ToString());
             }
         }
@@ -4313,6 +4443,7 @@ namespace System.Xml
         private void ParseElement()
         {
             int pos = _ps.charPos;
+            Debug.Assert(_ps.chars != null);
             char[] chars = _ps.chars;
             int colonPos = -1;
 
@@ -4390,6 +4521,7 @@ namespace System.Xml
 
         SetElement:
             // push namespace context
+            Debug.Assert(_namespaceManager != null);
             _namespaceManager.PushScope();
 
             // init the NodeData class
@@ -4482,8 +4614,9 @@ namespace System.Xml
         private void AddDefaultAttributesAndNormalize()
         {
             Debug.Assert(_curNode.type == XmlNodeType.Element);
+            Debug.Assert(_dtdInfo != null);
+            IDtdAttributeListInfo? attlistInfo = _dtdInfo.LookupAttributeList(_curNode.localName, _curNode.prefix);
 
-            IDtdAttributeListInfo attlistInfo = _dtdInfo.LookupAttributeList(_curNode.localName, _curNode.prefix);
             if (attlistInfo == null)
             {
                 return;
@@ -4525,7 +4658,7 @@ namespace System.Xml
             if (defaultAttributes != null)
             {
                 int originalAttrCount = _attrCount;
-                NodeData[] nameSortedAttributes = null;
+                NodeData[]? nameSortedAttributes = null;
 
                 if (_attrCount >= MaxAttrDuplWalkCount)
                 {
@@ -4573,6 +4706,7 @@ namespace System.Xml
             }
 
             int nameLen;
+            Debug.Assert(_ps.chars != null);
             char[] chars = _ps.chars;
             if (startTagNode.prefix.Length == 0)
             {
@@ -4688,6 +4822,7 @@ namespace System.Xml
                 int colonPos;
                 int endPos = ParseQName(out colonPos);
 
+                Debug.Assert(_ps.chars != null);
                 string[] args = new string[4];
                 args[0] = startTag.GetNameWPrefix(_nameTable);
                 args[1] = startTag.lineInfo.lineNo.ToString(CultureInfo.InvariantCulture);
@@ -4706,8 +4841,9 @@ namespace System.Xml
         private void ParseAttributes()
         {
             int pos = _ps.charPos;
+            Debug.Assert(_ps.chars != null);
             char[] chars = _ps.chars;
-            NodeData attr = null;
+            NodeData? attr = null;
 
             Debug.Assert(_attrCount == 0);
 
@@ -5085,6 +5221,7 @@ namespace System.Xml
             {
                 PushXmlContext();
             }
+
             _xmlContext.defaultNamespace = ns;
 
             AddNamespace(string.Empty, ns, attr);
@@ -5114,6 +5251,7 @@ namespace System.Xml
                     {
                         PushXmlContext();
                     }
+
                     switch (XmlConvert.TrimString(attr.StringValue))
                     {
                         case "preserve":
@@ -5133,6 +5271,7 @@ namespace System.Xml
                     {
                         PushXmlContext();
                     }
+
                     _xmlContext.xmlLang = attr.StringValue;
                     break;
             }
@@ -5141,11 +5280,12 @@ namespace System.Xml
         private void ParseAttributeValueSlow(int curPos, char quoteChar, NodeData attr)
         {
             int pos = curPos;
+            Debug.Assert(_ps.chars != null);
             char[] chars = _ps.chars;
             int attributeBaseEntityId = _ps.entityId;
             int valueChunkStartPos = 0;
             LineInfo valueChunkLineInfo = new LineInfo(_ps.lineNo, _ps.LinePos);
-            NodeData lastChunk = null;
+            NodeData? lastChunk = null;
 
             Debug.Assert(_stringBuilder.Length == 0);
 
@@ -5302,6 +5442,7 @@ namespace System.Xml
                                         NodeData entityChunk = new NodeData();
                                         entityChunk.lineInfo = entityLineInfo;
                                         entityChunk.depth = attr.depth + 1;
+                                        Debug.Assert(_ps.entity != null);
                                         entityChunk.SetNamedNode(XmlNodeType.EntityReference, _ps.entity.Name);
                                         AddAttributeChunkToList(attr, entityChunk, ref lastChunk);
 
@@ -5412,7 +5553,7 @@ namespace System.Xml
             _stringBuilder.Length = 0;
         }
 
-        private void AddAttributeChunkToList(NodeData attr, NodeData chunk, ref NodeData lastChunk)
+        private void AddAttributeChunkToList(NodeData attr, NodeData chunk, ref NodeData? lastChunk)
         {
             if (lastChunk == null)
             {
@@ -5454,12 +5595,15 @@ namespace System.Xml
                 {
                     goto IgnoredNode;
                 }
+
                 XmlNodeType nodeType = GetTextNodeType(orChars);
                 if (nodeType == XmlNodeType.None)
                 {
                     goto IgnoredNode;
                 }
+
                 Debug.Assert(endPos - startPos > 0);
+                Debug.Assert(_ps.chars != null);
                 _curNode.SetValueNode(nodeType, _ps.chars, startPos, endPos - startPos);
                 return true;
             }
@@ -5504,6 +5648,7 @@ namespace System.Xml
                     if (orChars > 0x20)
                     {
                         Debug.Assert(endPos - startPos > 0);
+                        Debug.Assert(_ps.chars != null);
                         _curNode.SetValueNode(XmlNodeType.Text, _ps.chars, startPos, endPos - startPos);
                         _nextParsingFunction = _parsingFunction;
                         _parsingFunction = ParsingFunction.PartialTextValue;
@@ -5536,6 +5681,7 @@ namespace System.Xml
                         }
                         goto IgnoredNode;
                     }
+
                     // set value to curNode
                     _curNode.SetValueNode(nodeType, _stringBuilder.ToString());
                     _stringBuilder.Length = 0;
@@ -5546,6 +5692,7 @@ namespace System.Xml
                         _nextParsingFunction = _parsingFunction;
                         _parsingFunction = ParsingFunction.PartialTextValue;
                     }
+
                     return true;
                 }
             }
@@ -5576,6 +5723,7 @@ namespace System.Xml
         // Returns true when the whole value has been parsed. Return false when it needs to be called again to get a next chunk of value.
         private bool ParseText(out int startPos, out int endPos, ref int outOrChars)
         {
+            Debug.Assert(_ps.chars != null);
             char[] chars = _ps.chars;
             int pos = _ps.charPos;
             int rcount = 0;
@@ -5943,6 +6091,7 @@ namespace System.Xml
 
             XmlNodeType nodeType = GetWhitespaceType();
 
+            Debug.Assert(_ps.chars != null);
             if (nodeType == XmlNodeType.None)
             {
                 EatWhitespaces(null);
@@ -5980,6 +6129,7 @@ namespace System.Xml
 
         private void ParseEntityReference()
         {
+            Debug.Assert(_ps.chars != null);
             Debug.Assert(_ps.chars[_ps.charPos] == '&');
             _ps.charPos++;
 
@@ -5989,6 +6139,7 @@ namespace System.Xml
 
         private EntityType HandleEntityReference(bool isInAttributeValue, EntityExpandType expandType, out int charRefEndPos)
         {
+            Debug.Assert(_ps.chars != null);
             Debug.Assert(_ps.chars[_ps.charPos] == '&');
 
             if (_ps.charPos + 1 == _ps.charsUsed)
@@ -6062,7 +6213,7 @@ namespace System.Xml
         // return false == unexpanded external entity, stop parsing and return
         private EntityType HandleGeneralEntityReference(string name, bool isInAttributeValue, bool pushFakeEntityIfNullResolver, int entityStartLinePos)
         {
-            IDtdEntityInfo entity = null;
+            IDtdEntityInfo? entity = null;
 
             if (_dtdInfo == null && _fragmentParserContext != null && _fragmentParserContext.HasDtdInfo && _dtdProcessing == DtdProcessing.Parse)
             {
@@ -6082,6 +6233,8 @@ namespace System.Xml
                     Throw(SR.Xml_UndeclaredEntity, name, _ps.LineNo, entityStartLinePos);
             }
 
+            Debug.Assert(entity != null);
+
             if (entity.IsUnparsedEntity)
             {
                 if (_disableUndeclaredEntityCheck)
@@ -6217,6 +6370,7 @@ namespace System.Xml
         {
             _curNode = _nodes[_index + _attrCount + 1];
             Debug.Assert(_curNode.type == XmlNodeType.EntityReference);
+            Debug.Assert(_lastEntity != null);
             Debug.Assert(Ref.Equal(_lastEntity.Name, _curNode.localName));
             _curNode.lineInfo.linePos += _curNode.localName.Length;
             _curNode.type = XmlNodeType.EndEntity;
@@ -6229,7 +6383,7 @@ namespace System.Xml
 
         // Parses processing instruction; if piInDtdStringBuilder != null, the processing instruction is in DTD and
         // it will be saved in the passed string builder (target, whitespace & value).
-        private bool ParsePI(StringBuilder piInDtdStringBuilder)
+        private bool ParsePI(StringBuilder? piInDtdStringBuilder)
         {
             if (_parsingMode == ParsingMode.Full)
             {
@@ -6240,6 +6394,7 @@ namespace System.Xml
 
             // parse target name
             int nameEndPos = ParseName();
+            Debug.Assert(_ps.chars != null);
             string target = _nameTable.Add(_ps.chars, _ps.charPos, nameEndPos - _ps.charPos);
 
             if (string.Equals(target, "xml", StringComparison.OrdinalIgnoreCase))
@@ -6325,6 +6480,7 @@ namespace System.Xml
                     _stringBuilder.Length = 0;
                 }
             }
+
             return true;
         }
 
@@ -6339,6 +6495,7 @@ namespace System.Xml
                 }
             }
 
+            Debug.Assert(_ps.chars != null);
             int pos = _ps.charPos;
             char[] chars = _ps.chars;
             int rcount = 0;
@@ -6510,6 +6667,7 @@ namespace System.Xml
                 Debug.Assert(_stringBuilder.Length == 0);
                 if (ParseCDataOrComment(type, out startPos, out endPos))
                 {
+                    Debug.Assert(_ps.chars != null);
                     _curNode.SetValueNode(type, _ps.chars, startPos, endPos - startPos);
                 }
                 else
@@ -6518,6 +6676,7 @@ namespace System.Xml
                     {
                         _stringBuilder.Append(_ps.chars, startPos, endPos - startPos);
                     } while (!ParseCDataOrComment(type, out startPos, out endPos));
+
                     _stringBuilder.Append(_ps.chars, startPos, endPos - startPos);
                     _curNode.SetValueNode(type, _stringBuilder.ToString());
                     _stringBuilder.Length = 0;
@@ -6541,6 +6700,7 @@ namespace System.Xml
                 }
             }
 
+            Debug.Assert(_ps.chars != null);
             int pos = _ps.charPos;
             char[] chars = _ps.chars;
             int rcount = 0;
@@ -6707,10 +6867,13 @@ namespace System.Xml
                     Throw(SR.Xml_UnexpectedEOF, "DOCTYPE");
                 }
             }
+
             if (!XmlConvert.StrEqual(_ps.chars, _ps.charPos, 7, "DOCTYPE"))
             {
                 ThrowUnexpectedToken((!_rootElementParsed && _dtdInfo == null) ? "DOCTYPE" : "<!--");
             }
+
+            Debug.Assert(_ps.chars != null);
             if (!_xmlCharType.IsWhiteSpace(_ps.chars[_ps.charPos + 7]))
             {
                 ThrowExpectingWhitespace(_ps.charPos + 7);
@@ -6720,6 +6883,7 @@ namespace System.Xml
             {
                 Throw(_ps.charPos - 2, SR.Xml_MultipleDTDsProvided);  // position just before <!DOCTYPE
             }
+
             if (_rootElementParsed)
             {
                 Throw(_ps.charPos - 2, SR.Xml_DtdAfterRootElement);
@@ -6776,6 +6940,7 @@ namespace System.Xml
             EatWhitespaces(null);
 
             // PUBLIC Id
+            Debug.Assert(_ps.chars != null);
             if (_ps.chars[_ps.charPos] == 'P')
             {
                 // make sure we have enough characters
@@ -6872,6 +7037,7 @@ namespace System.Xml
 
         private void SkipPublicOrSystemIdLiteral()
         {
+            Debug.Assert(_ps.chars != null);
             // check quote char
             char quoteChar = _ps.chars[_ps.charPos];
             if (quoteChar != '"' && quoteChar != '\'')
@@ -6890,6 +7056,7 @@ namespace System.Xml
             bool inPI = false;
             char literalQuote = '"';
 
+            Debug.Assert(_ps.chars != null);
             char[] chars = _ps.chars;
             int pos = _ps.charPos;
 
@@ -7082,10 +7249,11 @@ namespace System.Xml
             }
         }
 
-        private int EatWhitespaces(StringBuilder sb)
+        private int EatWhitespaces(StringBuilder? sb)
         {
             int pos = _ps.charPos;
             int wsCount = 0;
+            Debug.Assert(_ps.chars != null);
             char[] chars = _ps.chars;
 
             while (true)
@@ -7185,6 +7353,7 @@ namespace System.Xml
 
         private int ParseCharRefInline(int startPos, out int charCount, out EntityType entityType)
         {
+            Debug.Assert(_ps.chars != null);
             Debug.Assert(_ps.chars[startPos] == '&');
             if (_ps.chars[startPos + 1] == '#')
             {
@@ -7203,7 +7372,7 @@ namespace System.Xml
         //        character or surrogates pair (if expand == true)
         //      - returns position of the end of the character reference, that is of the character next to the original ';'
         //      - if (expand == true) then ps.charPos is changed to point to the replaced character
-        private int ParseNumericCharRef(bool expand, StringBuilder internalSubsetBuilder, out EntityType entityType)
+        private int ParseNumericCharRef(bool expand, StringBuilder? internalSubsetBuilder, out EntityType entityType)
         {
             while (true)
             {
@@ -7217,6 +7386,8 @@ namespace System.Xml
                         {
                             Throw(SR.Xml_UnexpectedEOF);
                         }
+
+                        Debug.Assert(_ps.chars != null);
                         Debug.Assert(_ps.chars[_ps.charPos] == '&');
                         continue;
                     default:
@@ -7235,8 +7406,9 @@ namespace System.Xml
         //      - replaces the last one or two character of the entity reference (';' and the character before) with the referenced
         //        character or surrogates pair (if expand == true)
         //      - returns position of the end of the character reference, that is of the character next to the original ';'
-        private int ParseNumericCharRefInline(int startPos, bool expand, StringBuilder internalSubsetBuilder, out int charCount, out EntityType entityType)
+        private int ParseNumericCharRefInline(int startPos, bool expand, StringBuilder? internalSubsetBuilder, out int charCount, out EntityType entityType)
         {
+            Debug.Assert(_ps.chars != null);
             Debug.Assert(_ps.chars[startPos] == '&' && _ps.chars[startPos + 1] == '#');
 
             int val;
@@ -7244,7 +7416,7 @@ namespace System.Xml
             char[] chars;
 
             val = 0;
-            string badDigitExceptionString = null;
+            string? badDigitExceptionString = null;
             chars = _ps.chars;
             pos = startPos + 2;
             charCount = 0;
@@ -7294,9 +7466,11 @@ namespace System.Xml
             {
                 _ps.charPos = pos;
                 entityType = EntityType.Skipped;
-                Throw(SR.Xml_CharEntityOverflow, (string)null, e);
+                Throw(SR.Xml_CharEntityOverflow, (string?)null, e);
             }
 
+            Debug.Assert(badDigitExceptionString != null);
+
             if (chars[pos] != ';' || digitPos == pos)
             {
                 if (pos == _ps.charsUsed)
@@ -7371,7 +7545,7 @@ namespace System.Xml
         //      - replaces the last character of the entity reference (';') with the referenced character (if expand == true)
         //      - returns position of the end of the character reference, that is of the character next to the original ';'
         //      - if (expand == true) then ps.charPos is changed to point to the replaced character
-        private int ParseNamedCharRef(bool expand, StringBuilder internalSubsetBuilder)
+        private int ParseNamedCharRef(bool expand, StringBuilder? internalSubsetBuilder)
         {
             while (true)
             {
@@ -7386,6 +7560,8 @@ namespace System.Xml
                         {
                             return -1;
                         }
+
+                        Debug.Assert(_ps.chars != null);
                         Debug.Assert(_ps.chars[_ps.charPos] == '&');
                         continue;
                     default:
@@ -7404,9 +7580,10 @@ namespace System.Xml
         // Otherwise
         //      - replaces the last character of the entity reference (';') with the referenced character (if expand == true)
         //      - returns position of the end of the character reference, that is of the character next to the original ';'
-        private int ParseNamedCharRefInline(int startPos, bool expand, StringBuilder internalSubsetBuilder)
+        private int ParseNamedCharRefInline(int startPos, bool expand, StringBuilder? internalSubsetBuilder)
         {
             Debug.Assert(startPos < _ps.charsUsed);
+            Debug.Assert(_ps.chars != null);
             Debug.Assert(_ps.chars[startPos] == '&');
             Debug.Assert(_ps.chars[startPos + 1] != '#');
 
@@ -7545,6 +7722,7 @@ namespace System.Xml
             int pos = _ps.charPos + startOffset;
 
         ContinueStartName:
+            Debug.Assert(_ps.chars != null);
             char[] chars = _ps.chars;
 
             // start name char
@@ -7622,6 +7800,7 @@ namespace System.Xml
             {
                 if (ReadDataInName(ref pos))
                 {
+                    Debug.Assert(_ps.chars != null);
                     chars = _ps.chars;
                     goto ContinueName;
                 }
@@ -7651,9 +7830,11 @@ namespace System.Xml
             catch (XmlException)
             {
                 Throw(SR.Xml_ErrorParsingEntityName);
-                return null;
+                return null!;
             }
 
+            Debug.Assert(_ps.chars != null);
+
             // check ';'
             if (_ps.chars[endPos] != ';')
             {
@@ -7710,6 +7891,8 @@ namespace System.Xml
 
         private NodeData AddAttribute(int endNamePos, int colonPos)
         {
+            Debug.Assert(_ps.chars != null);
+
             // setup attribute name
             if (colonPos == -1 || !_supportNamespaces)
             {
@@ -7738,7 +7921,7 @@ namespace System.Xml
             }
         }
 
-        private NodeData AddAttribute(string localName, string prefix, string nameWPrefix)
+        private NodeData AddAttribute(string localName, string prefix, string? nameWPrefix)
         {
             NodeData newAttr = AddNode(_index + _attrCount + 1, _index + 1);
 
@@ -7777,6 +7960,7 @@ namespace System.Xml
 
         private void PopElementContext()
         {
+            Debug.Assert(_namespaceManager != null);
             // pop namespace context
             _namespaceManager.PopScope();
 
@@ -7808,7 +7992,8 @@ namespace System.Xml
 
         private string LookupNamespace(NodeData node)
         {
-            string ns = _namespaceManager.LookupNamespace(node.prefix);
+            Debug.Assert(_namespaceManager != null);
+            string? ns = _namespaceManager.LookupNamespace(node.prefix);
             if (ns != null)
             {
                 return ns;
@@ -7845,6 +8030,8 @@ namespace System.Xml
                 Throw(SR.Xml_BadNamespaceDecl, (int)attr.lineInfo.lineNo, (int)attr.lineInfo.linePos);
             }
 
+            Debug.Assert(_namespaceManager != null);
+
             try
             {
                 _namespaceManager.AddNamespace(prefix, uri);
@@ -7867,6 +8054,7 @@ namespace System.Xml
             {
                 FullAttributeCleanup();
             }
+
             _curAttrIndex = -1;
             _attrCount = 0;
             _attrHashtable = 0;
@@ -7893,7 +8081,7 @@ namespace System.Xml
         private void PopXmlContext()
         {
             Debug.Assert(_curNode.xmlContextPushed);
-            _xmlContext = _xmlContext.previousContext;
+            _xmlContext = _xmlContext.previousContext!;
             _curNode.xmlContextPushed = false;
         }
 
@@ -7906,11 +8094,13 @@ namespace System.Xml
                 {
                     return XmlNodeType.SignificantWhitespace;
                 }
+
                 if (_whitespaceHandling == WhitespaceHandling.All)
                 {
                     return XmlNodeType.Whitespace;
                 }
             }
+
             return XmlNodeType.None;
         }
 
@@ -7928,10 +8118,12 @@ namespace System.Xml
 
         // This method resolves and opens an external DTD subset or an external entity based on its SYSTEM or PUBLIC ID.
         // SxS: This method may expose a name if a resource in baseUri (ref) parameter.
-        private void PushExternalEntityOrSubset(string publicId, string systemId, Uri baseUri, string entityName)
+        private void PushExternalEntityOrSubset(string? publicId, string? systemId, Uri? baseUri, string? entityName)
         {
             Uri uri;
 
+            Debug.Assert(_xmlResolver != null);
+
             // First try opening the external reference by PUBLIC Id
             if (!string.IsNullOrEmpty(publicId))
             {
@@ -7957,6 +8149,7 @@ namespace System.Xml
                 {
                     return;
                 }
+
                 // resolver returned null, throw exception outside this try-catch
             }
             catch (Exception e)
@@ -7965,13 +8158,14 @@ namespace System.Xml
                 {
                     throw;
                 }
+
                 string innerMessage = e.Message;
                 Throw(new XmlException(entityName == null ? SR.Xml_ErrorOpeningExternalDtd : SR.Xml_ErrorOpeningExternalEntity, new string[] { uri.ToString(), innerMessage }, e, 0, 0));
             }
 
             if (entityName == null)
             {
-                ThrowWithoutLineInfo(SR.Xml_CannotResolveExternalSubset, new string[] { (publicId != null ? publicId : string.Empty), systemId }, null);
+                ThrowWithoutLineInfo(SR.Xml_CannotResolveExternalSubset, new string?[] { (publicId != null ? publicId : string.Empty), systemId }, null);
             }
             else
             {
@@ -7991,7 +8185,7 @@ namespace System.Xml
             // First try to get the data as a TextReader
             if (_xmlResolver.SupportsType(uri, typeof(TextReader)))
             {
-                TextReader textReader = (TextReader)_xmlResolver.GetEntity(uri, null, typeof(TextReader));
+                TextReader? textReader = (TextReader?)_xmlResolver.GetEntity(uri, null, typeof(TextReader));
                 if (textReader == null)
                 {
                     return false;
@@ -8005,7 +8199,7 @@ namespace System.Xml
                 // Then try get it as a Stream
                 Debug.Assert(_xmlResolver.SupportsType(uri, typeof(Stream)), "Stream must always be a supported type in XmlResolver");
 
-                Stream stream = (Stream)_xmlResolver.GetEntity(uri, null, typeof(Stream));
+                Stream? stream = (Stream?)_xmlResolver.GetEntity(uri, null, typeof(Stream));
                 if (stream == null)
                 {
                     return false;
@@ -8014,6 +8208,7 @@ namespace System.Xml
                 PushParsingState();
                 InitStreamInput(uri, stream, null);
             }
+
             return true;
         }
 
@@ -8026,11 +8221,13 @@ namespace System.Xml
 
             if (!IsResolverNull)
             {
-                Uri entityBaseUri = null;
+                Debug.Assert(_xmlResolver != null);
+                Uri? entityBaseUri = null;
                 if (!string.IsNullOrEmpty(entity.BaseUriString))
                 {
                     entityBaseUri = _xmlResolver.ResolveUri(null, entity.BaseUriString);
                 }
+
                 PushExternalEntityOrSubset(entity.PublicId, entity.SystemId, entityBaseUri, entity.Name);
 
                 RegisterEntity(entity);
@@ -8041,15 +8238,17 @@ namespace System.Xml
                 {
                     EatWhitespaces(null);
                 }
+
                 if (!ParseXmlDeclaration(true))
                 {
                     _ps.charPos = initialPos;
                 }
+
                 return true;
             }
             else
             {
-                Encoding enc = _ps.encoding;
+                Encoding? enc = _ps.encoding;
 
                 PushParsingState();
                 InitStringInput(entity.SystemId, enc, string.Empty);
@@ -8066,11 +8265,11 @@ namespace System.Xml
         {
             Debug.Assert(!entity.IsExternal);
 
-            Encoding enc = _ps.encoding;
+            Encoding? enc = _ps.encoding;
 
             PushParsingState();
 
-            InitStringInput((entity.DeclaredUriString != null) ? entity.DeclaredUriString : string.Empty, enc, entity.Text ?? string.Empty);
+            InitStringInput(entity.DeclaredUriString ?? string.Empty, enc, entity.Text);
 
             RegisterEntity(entity);
 
@@ -8088,6 +8287,7 @@ namespace System.Xml
             {
                 _ps.stream.Dispose();
             }
+
             UnregisterEntity();
             PopParsingState();
             _curNode.entityId = _ps.entityId;
@@ -8101,7 +8301,7 @@ namespace System.Xml
                 if (_currentEntities.ContainsKey(entity))
                 {
                     Throw(entity.IsParameterEntity ? SR.Xml_RecursiveParEntity : SR.Xml_RecursiveGenEntity, entity.Name,
-                        _parsingStatesStack[_parsingStatesStackTop].LineNo, _parsingStatesStack[_parsingStatesStackTop].LinePos);
+                        _parsingStatesStack![_parsingStatesStackTop].LineNo, _parsingStatesStack[_parsingStatesStackTop].LinePos);
                 }
             }
 
@@ -8116,6 +8316,7 @@ namespace System.Xml
                 {
                     _currentEntities = new Dictionary<IDtdEntityInfo, IDtdEntityInfo>();
                 }
+
                 _currentEntities.Add(entity, entity);
             }
         }
@@ -8125,7 +8326,7 @@ namespace System.Xml
             // remove from recursion check registry
             if (_ps.entity != null)
             {
-                _currentEntities.Remove(_ps.entity);
+                _currentEntities!.Remove(_ps.entity);
             }
         }
 
@@ -8151,6 +8352,7 @@ namespace System.Xml
         private void PopParsingState()
         {
             Debug.Assert(_parsingStatesStackTop >= 0);
+            Debug.Assert(_parsingStatesStack != null);
             _ps.Close(true);
             _ps = _parsingStatesStack[_parsingStatesStackTop--];
         }
@@ -8176,14 +8378,17 @@ namespace System.Xml
             {
                 throw new ArgumentNullException((_incReadDecoder is IncrementalReadCharsDecoder) ? "buffer" : nameof(array));
             }
+
             if (count < 0)
             {
                 throw new ArgumentOutOfRangeException((_incReadDecoder is IncrementalReadCharsDecoder) ? nameof(count) : "len");
             }
+
             if (index < 0)
             {
                 throw new ArgumentOutOfRangeException((_incReadDecoder is IncrementalReadCharsDecoder) ? nameof(index) : "offset");
             }
+
             if (array.Length - index < count)
             {
                 throw new ArgumentException((_incReadDecoder is IncrementalReadCharsDecoder) ? nameof(count) : "len");
@@ -8194,6 +8399,7 @@ namespace System.Xml
                 return 0;
             }
 
+            Debug.Assert(_incReadDecoder != null);
             _curNode.lineInfo = _incReadLineInfo;
 
             _incReadDecoder.SetNextOutputBuffer(array, index, count);
@@ -8203,6 +8409,7 @@ namespace System.Xml
 
         private int IncrementalRead()
         {
+            Debug.Assert(_incReadDecoder != null);
             int charsDecoded = 0;
 
         OuterContinue:
@@ -8298,6 +8505,7 @@ namespace System.Xml
                               _incReadState == IncrementalReadState.Attributes ||
                               _incReadState == IncrementalReadState.AttributeValue);
 
+                Debug.Assert(_ps.chars != null);
                 char[] chars = _ps.chars;
                 startPos = _ps.charPos;
                 pos = startPos;
@@ -8541,6 +8749,7 @@ namespace System.Xml
                         ReThrow(e, (int)_incReadLineInfo.lineNo, (int)_incReadLineInfo.linePos);
                         return 0;
                     }
+
                     Debug.Assert(count == charsParsed || _incReadDecoder.IsFull, "Check if decoded consumed all characters unless it's full.");
                     charsDecoded += count;
                     if (_incReadDecoder.IsFull)
@@ -8594,6 +8803,8 @@ namespace System.Xml
 
         private bool ParseAttributeValueChunk()
         {
+            Debug.Assert(_ps.chars != null);
+
             char[] chars = _ps.chars;
             int pos = _ps.charPos;
 
@@ -8645,6 +8856,7 @@ namespace System.Xml
                         {
                             _stringBuilder.Append(chars, _ps.charPos, pos - _ps.charPos);
                         }
+
                         _ps.charPos = pos;
 
                         // expand char entities but not general entities
@@ -8693,6 +8905,7 @@ namespace System.Xml
                                 {
                                     goto ReadData;
                                 }
+
                                 pos++;
                                 if (XmlCharType.IsLowSurrogate(chars[pos]))
                                 {
@@ -8700,6 +8913,7 @@ namespace System.Xml
                                     continue;
                                 }
                             }
+
                             ThrowInvalidChar(chars, _ps.charsUsed, pos);
                             break;
                         }
@@ -8711,6 +8925,7 @@ namespace System.Xml
                     _stringBuilder.Append(chars, _ps.charPos, pos - _ps.charPos);
                     _ps.charPos = pos;
                 }
+
                 // read new characters into the buffer
                 if (ReadData() == 0)
                 {
@@ -8742,6 +8957,7 @@ namespace System.Xml
                 _stringBuilder.Append(chars, _ps.charPos, pos - _ps.charPos);
                 _ps.charPos = pos;
             }
+
             _curNode.SetValueNode(XmlNodeType.Text, _stringBuilder.ToString());
             _stringBuilder.Length = 0;
             return true;
@@ -8769,19 +8985,20 @@ namespace System.Xml
             ThrowUnexpectedToken(expectedToken1, null);
         }
 
-        private void ThrowUnexpectedToken(int pos, string expectedToken1, string expectedToken2)
+        private void ThrowUnexpectedToken(int pos, string expectedToken1, string? expectedToken2)
         {
             _ps.charPos = pos;
             ThrowUnexpectedToken(expectedToken1, expectedToken2);
         }
 
-        private void ThrowUnexpectedToken(string expectedToken1, string expectedToken2)
+        private void ThrowUnexpectedToken(string expectedToken1, string? expectedToken2)
         {
-            string unexpectedToken = ParseUnexpectedToken();
+            string? unexpectedToken = ParseUnexpectedToken();
             if (unexpectedToken == null)
             {
                 Throw(SR.Xml_UnexpectedEOF1);
             }
+
             if (expectedToken2 != null)
             {
                 Throw(SR.Xml_UnexpectedTokens2, new string[3] { unexpectedToken, expectedToken1, expectedToken2 });
@@ -8792,18 +9009,21 @@ namespace System.Xml
             }
         }
 
-        private string ParseUnexpectedToken(int pos)
+        private string? ParseUnexpectedToken(int pos)
         {
             _ps.charPos = pos;
             return ParseUnexpectedToken();
         }
 
-        private string ParseUnexpectedToken()
+        private string? ParseUnexpectedToken()
         {
             if (_ps.charPos == _ps.charsUsed)
             {
                 return null;
             }
+
+            Debug.Assert(_ps.chars != null);
+
             if (_xmlCharType.IsNCNameSingleChar(_ps.chars[_ps.charPos]))
             {
                 int pos = _ps.charPos + 1;
@@ -8822,7 +9042,8 @@ namespace System.Xml
 
         private void ThrowExpectingWhitespace(int pos)
         {
-            string unexpectedToken = ParseUnexpectedToken(pos);
+            string? unexpectedToken = ParseUnexpectedToken(pos);
+
             if (unexpectedToken == null)
             {
                 Throw(pos, SR.Xml_UnexpectedEOF1);
@@ -8835,28 +9056,32 @@ namespace System.Xml
 
         private int GetIndexOfAttributeWithoutPrefix(string name)
         {
-            name = _nameTable.Get(name);
-            if (name == null)
+            string? atomizedName = _nameTable.Get(name);
+            if (atomizedName == null)
             {
                 return -1;
             }
+
             for (int i = _index + 1; i < _index + _attrCount + 1; i++)
             {
-                if (Ref.Equal(_nodes[i].localName, name) && _nodes[i].prefix.Length == 0)
+                if (Ref.Equal(_nodes[i].localName, atomizedName) && _nodes[i].prefix.Length == 0)
                 {
                     return i;
                 }
             }
+
             return -1;
         }
 
         private int GetIndexOfAttributeWithPrefix(string name)
         {
             name = _nameTable.Add(name);
+
             if (name == null)
             {
                 return -1;
             }
+
             for (int i = _index + 1; i < _index + _attrCount + 1; i++)
             {
                 if (Ref.Equal(_nodes[i].GetNameWPrefix(_nameTable), name))
@@ -8864,6 +9089,7 @@ namespace System.Xml
                     return i;
                 }
             }
+
             return -1;
         }
 
@@ -8874,11 +9100,14 @@ namespace System.Xml
         // Note that this method calls ReadData() which may change the value of ps.chars and ps.charPos.
         private bool ZeroEndingStream(int pos)
         {
+            Debug.Assert(_ps.chars != null);
+
             if (_v1Compat && pos == _ps.charsUsed - 1 && _ps.chars[pos] == (char)0 && ReadData() == 0 && _ps.isStreamEof)
             {
                 _ps.charsUsed--;
                 return true;
             }
+
             return false;
         }
 
@@ -8906,6 +9135,7 @@ namespace System.Xml
             {
                 throw new InvalidOperationException(SR.Xml_MixingReadValueChunkWithBinary);
             }
+
             if (_parsingFunction == ParsingFunction.InIncrementalRead)
             {
                 throw new InvalidOperationException(SR.Xml_MixingV1StreamingWithV2Binary);
@@ -8933,6 +9163,7 @@ namespace System.Xml
 
             // move to content or off the empty element
             _outerReader.Read();
+
             if (isEmpty)
             {
                 return false;
@@ -8945,10 +9176,12 @@ namespace System.Xml
                 {
                     Throw(SR.Xml_InvalidNodeType, _curNode.type.ToString());
                 }
+
                 // move off end element
                 _outerReader.Read();
                 return false;
             }
+
             SetupReadContentAsBinaryState(ParsingFunction.InReadElementContentAsBinary);
             _incReadLineInfo.Set(_curNode.LineNo, _curNode.LinePos);
             return true;
@@ -8984,6 +9217,7 @@ namespace System.Xml
                 }
                 moveIfOnContentNode = false;
             } while (_outerReader.Read());
+
             return false;
         }
 
@@ -9003,12 +9237,13 @@ namespace System.Xml
             _parsingFunction = inReadBinaryFunction;
         }
 
+        [MemberNotNull(nameof(_nameTable))]
         private void SetupFromParserContext(XmlParserContext context, XmlReaderSettings settings)
         {
             Debug.Assert(context != null);
 
             // setup nameTable
-            XmlNameTable nt = settings.NameTable;
+            XmlNameTable? nt = settings.NameTable;
             _nameTableFromSettings = (nt != null);
 
             // get name table from namespace manager in XmlParserContext, if available;
@@ -9021,7 +9256,7 @@ namespace System.Xml
                 }
                 // get the namespace manager from context
                 _namespaceManager = context.NamespaceManager;
-                _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty);
+                _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty)!;
 
                 // get the nametable from ns manager
                 nt = _namespaceManager.NameTable;
@@ -9061,7 +9296,7 @@ namespace System.Xml
         //
         // DtdInfo
         //
-        internal override IDtdInfo DtdInfo
+        internal override IDtdInfo? DtdInfo
         {
             get
             {
@@ -9133,7 +9368,7 @@ namespace System.Xml
             _curNode.type = newNodeType;
         }
 
-        internal XmlResolver GetResolver()
+        internal XmlResolver? GetResolver()
         {
             if (IsResolverNull)
                 return null;
@@ -9141,7 +9376,7 @@ namespace System.Xml
                 return _xmlResolver;
         }
 
-        internal object InternalSchemaType
+        internal object? InternalSchemaType
         {
             get
             {
@@ -9153,7 +9388,7 @@ namespace System.Xml
             }
         }
 
-        internal object InternalTypedValue
+        internal object? InternalTypedValue
         {
             get
             {
@@ -9173,7 +9408,7 @@ namespace System.Xml
             }
         }
 
-        internal override XmlNamespaceManager NamespaceManager
+        internal override XmlNamespaceManager? NamespaceManager
         {
             get
             {
@@ -9197,7 +9432,7 @@ namespace System.Xml
             }
         }
 
-        private bool AddDefaultAttributeDtd(IDtdDefaultAttributeInfo defAttrInfo, bool definedInDtd, NodeData[] nameSortedNodeData)
+        private bool AddDefaultAttributeDtd(IDtdDefaultAttributeInfo defAttrInfo, bool definedInDtd, NodeData[]? nameSortedNodeData)
         {
             if (defAttrInfo.Prefix.Length > 0)
             {
@@ -9239,6 +9474,7 @@ namespace System.Xml
                 {
                     _onDefaultAttributeUse(defAttrInfo, this);
                 }
+
                 attr.typedValue = defAttrInfo.DefaultValueTyped;
             }
             return attr != null;
@@ -9248,12 +9484,13 @@ namespace System.Xml
         {
             // atomize names - Xsd Validator does not need to have the same nametable
             string localName = _nameTable.Add(attrDef.Name.Name);
-            string prefix = _nameTable.Add(attrDef.Prefix);
+            string? prefix = _nameTable.Add(attrDef.Prefix);
             string ns = _nameTable.Add(attrDef.Name.Namespace);
 
             // atomize namespace - Xsd Validator does not need to have the same nametable
             if (prefix.Length == 0 && ns.Length > 0)
             {
+                Debug.Assert(_namespaceManager != null);
                 prefix = _namespaceManager.LookupPrefix(ns);
 
                 Debug.Assert(prefix != null);
@@ -9267,7 +9504,7 @@ namespace System.Xml
             for (int i = _index + 1; i < _index + 1 + _attrCount; i++)
             {
                 if ((object)_nodes[i].localName == (object)localName &&
-                    (((object)_nodes[i].prefix == (object)prefix) || ((object)_nodes[i].ns == (object)ns && ns != null)))
+                    (((object?)_nodes[i].prefix == (object?)prefix) || ((object?)_nodes[i].ns == (object?)ns && ns != null)))
                 {
                     return false;
                 }
@@ -9284,7 +9521,7 @@ namespace System.Xml
             return true;
         }
 
-        private NodeData AddDefaultAttributeInternal(string localName, string ns, string prefix, string value,
+        private NodeData AddDefaultAttributeInternal(string localName, string? ns, string prefix, string value,
                                                      int lineNo, int linePos, int valueLineNo, int valueLinePos, bool isXmlAttribute)
         {
             // setup the attribute
@@ -9328,6 +9565,7 @@ namespace System.Xml
                         // change namespace of current element and attributes
                         string pref = attr.localName;
                         Debug.Assert(_nodes[_index].type == XmlNodeType.Element);
+                        Debug.Assert(_namespaceManager != null);
                         for (int i = _index; i < _index + _attrCount + 1; i++)
                         {
                             if (_nodes[i].prefix.Equals(pref))
@@ -9424,6 +9662,7 @@ namespace System.Xml
 
                     if (_incReadDecoder.IsFull)
                     {
+                        Debug.Assert(_ps.chars != null);
                         _curNode.SetValue(_ps.chars, startPos, endPos - startPos);
                         // adjust line info for the chunk that has been already decoded
                         AdjustLineInfo(_ps.chars, startPos - charsRead, startPos, _ps.eolNormalized, ref _incReadLineInfo);
@@ -9444,6 +9683,7 @@ namespace System.Xml
                     _incReadState = IncrementalReadState.ReadContentAsBinary_End;
                     return _incReadDecoder.DecodedCount;
                 }
+
                 SetupReadContentAsBinaryState(tmp);
                 _incReadLineInfo.Set(_curNode.LineNo, _curNode.LinePos);
             }
@@ -9455,6 +9695,7 @@ namespace System.Xml
             {
                 return 0;
             }
+
             int decoded = ReadContentAsBinary(buffer, index, count);
             if (decoded > 0)
             {
@@ -9504,16 +9745,18 @@ namespace System.Xml
         }
 
         // SxS: URIs are resolved only to be compared. No resource exposure. It's OK to suppress the SxS warning.
-        private bool UriEqual(Uri uri1, string uri1Str, string uri2Str, XmlResolver resolver)
+        private bool UriEqual(Uri? uri1, string uri1Str, string uri2Str, XmlResolver? resolver)
         {
             if (resolver == null)
             {
                 return uri1Str == uri2Str;
             }
+
             if (uri1 == null)
             {
                 uri1 = resolver.ResolveUri(null, uri1Str);
             }
+
             Uri uri2 = resolver.ResolveUri(null, uri2Str);
             return uri1.Equals(uri2);
         }
@@ -9633,7 +9876,7 @@ namespace System.Xml
             }
 
             int startPos = 0;
-            StringBuilder norValue = null;
+            StringBuilder? norValue = null;
 
             while (value[startPos] == 0x20)
             {
@@ -9752,6 +9995,6 @@ namespace System.Xml
             Buffer.BlockCopy(src, srcOffset, dst, dstOffset, count);
         }
 
-        static partial void ConvertAbsoluteUnixPathToAbsoluteUri(ref string url, XmlResolver resolver);
+        static partial void ConvertAbsoluteUnixPathToAbsoluteUri(ref string url, XmlResolver? resolver);
     }
 }
index 415dd15..cea09b3 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.
 
+#nullable enable
 using System;
 using System.IO;
 using System.Text;
@@ -12,6 +13,7 @@ using System.Diagnostics;
 using System.Globalization;
 using System.Collections.Generic;
 using System.Runtime.Versioning;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
@@ -24,21 +26,21 @@ namespace System.Xml
         private struct ParsingState
         {
             // character buffer
-            internal char[] chars;
+            internal char[]? chars;
             internal int charPos;
             internal int charsUsed;
-            internal Encoding encoding;
+            internal Encoding? encoding;
             internal bool appendMode;
 
             // input stream & byte buffer
-            internal Stream stream;
-            internal Decoder decoder;
-            internal byte[] bytes;
+            internal Stream? stream;
+            internal Decoder? decoder;
+            internal byte[]? bytes;
             internal int bytePos;
             internal int bytesUsed;
 
             // input text reader
-            internal TextReader textReader;
+            internal TextReader? textReader;
 
             // current line number & position
             internal int lineNo;
@@ -46,14 +48,14 @@ namespace System.Xml
 
             // base uri of the current entity
             internal string baseUriStr;
-            internal Uri baseUri;
+            internal Uri? baseUri;
 
             // eof flag of the entity
             internal bool isEof;
             internal bool isStreamEof;
 
             // entity type & id
-            internal IDtdEntityInfo entity;
+            internal IDtdEntityInfo? entity;
             internal int entityId;
 
             // normalization
@@ -124,7 +126,7 @@ namespace System.Xml
             internal XmlSpace xmlSpace;
             internal string xmlLang;
             internal string defaultNamespace;
-            internal XmlContext previousContext;
+            internal XmlContext? previousContext;
 
             internal XmlContext()
             {
@@ -154,10 +156,10 @@ namespace System.Xml
             public override bool PopScope() { return false; }
             public override void AddNamespace(string prefix, string uri) { }
             public override void RemoveNamespace(string prefix, string uri) { }
-            public override IEnumerator GetEnumerator() { return null; }
-            public override IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { return null; }
+            public override IEnumerator GetEnumerator() { return null!; }
+            public override IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { return null!; }
             public override string LookupNamespace(string prefix) { return string.Empty; }
-            public override string LookupPrefix(string uri) { return null; }
+            public override string? LookupPrefix(string uri) { return null; }
             public override bool HasNamespace(string prefix) { return false; }
         }
 
@@ -181,12 +183,12 @@ namespace System.Xml
                 get { return _reader.DtdParserProxy_NameTable; }
             }
 
-            IXmlNamespaceResolver IDtdParserAdapter.NamespaceResolver
+            IXmlNamespaceResolver? IDtdParserAdapter.NamespaceResolver
             {
                 get { return _reader.DtdParserProxy_NamespaceResolver; }
             }
 
-            Uri IDtdParserAdapter.BaseUri
+            Uri? IDtdParserAdapter.BaseUri
             {
                 // SxS: DtdParserProxy_BaseUri property on the reader may expose machine scope resources. This property
                 // is just returning the value of the other property, so it may expose machine scope resource as well.
@@ -198,7 +200,7 @@ namespace System.Xml
                 get { return _reader.DtdParserProxy_IsEof; }
             }
 
-            char[] IDtdParserAdapter.ParsingBuffer
+            char[]? IDtdParserAdapter.ParsingBuffer
             {
                 get { return _reader.DtdParserProxy_ParsingBuffer; }
             }
@@ -269,7 +271,7 @@ namespace System.Xml
                 return _reader.DtdParserProxy_PushEntity(entity, out entityId);
             }
 
-            bool IDtdParserAdapter.PopEntity(out IDtdEntityInfo oldEntity, out int newEntityId)
+            bool IDtdParserAdapter.PopEntity(out IDtdEntityInfo? oldEntity, out int newEntityId)
             {
                 return _reader.DtdParserProxy_PopEntity(out oldEntity, out newEntityId);
             }
@@ -305,7 +307,7 @@ namespace System.Xml
                 get { return _reader.DtdParserProxy_DtdValidation; }
             }
 
-            IValidationEventHandling IDtdParserAdapterWithValidation.ValidationEventHandling
+            IValidationEventHandling? IDtdParserAdapterWithValidation.ValidationEventHandling
             {
                 get { return _reader.DtdParserProxy_ValidationEventHandling; }
             }
@@ -332,7 +334,7 @@ namespace System.Xml
         private class NodeData : IComparable
         {
             // static instance with no data - is used when XmlTextReader is closed
-            private static volatile NodeData s_None;
+            private static volatile NodeData? s_None;
 
             // NOTE: Do not use this property for reference comparison. It may not be unique.
             internal static NodeData None
@@ -352,15 +354,15 @@ namespace System.Xml
             internal XmlNodeType type;
 
             // name
-            internal string localName;
-            internal string prefix;
-            internal string ns;
-            internal string nameWPrefix;
+            internal string localName = null!;
+            internal string prefix = null!;
+            internal string? ns;
+            internal string? nameWPrefix;
 
             // value:
             // value == null -> the value is kept in the 'chars' buffer starting at valueStartPos and valueLength long
-            private string _value;
-            private char[] _chars;
+            private string? _value;
+            private char[]? _chars;
             private int _valueStartPos;
             private int _valueLength;
 
@@ -386,11 +388,11 @@ namespace System.Xml
             internal bool xmlContextPushed;
 
             // attribute value chunks
-            internal NodeData nextAttrValueChunk;
+            internal NodeData? nextAttrValueChunk;
 
             // type info
-            internal object schemaType;
-            internal object typedValue;
+            internal object? schemaType;
+            internal object? typedValue;
 
             internal NodeData()
             {
@@ -456,6 +458,7 @@ namespace System.Xml
 
                     if (_value == null)
                     {
+                        Debug.Assert(_chars != null);
                         _value = new string(_chars, _valueStartPos, _valueLength);
                     }
                     return _value;
@@ -466,25 +469,35 @@ namespace System.Xml
             {
                 if (ValueBuffered)
                 {
+                    Debug.Assert(_chars != null);
                     XmlTextReaderImpl.StripSpaces(_chars, _valueStartPos, ref _valueLength);
                 }
                 else
                 {
+                    Debug.Assert(_value != null);
                     _value = XmlTextReaderImpl.StripSpaces(_value);
                 }
             }
 
+            [MemberNotNull("_value")]
+            [MemberNotNull("nameWPrefix")]
+            [MemberNotNull("localName")]
+            [MemberNotNull("prefix")]
+            [MemberNotNull("ns")]
             internal void Clear(XmlNodeType type)
             {
                 this.type = type;
                 ClearName();
                 _value = string.Empty;
                 _valueStartPos = -1;
-                nameWPrefix = string.Empty;
                 schemaType = null;
                 typedValue = null;
             }
 
+            [MemberNotNull("localName")]
+            [MemberNotNull("prefix")]
+            [MemberNotNull("ns")]
+            [MemberNotNull("nameWPrefix")]
             internal void ClearName()
             {
                 localName = string.Empty;
@@ -529,7 +542,7 @@ namespace System.Xml
                 SetNamedNode(type, localName, string.Empty, localName);
             }
 
-            internal void SetNamedNode(XmlNodeType type, string localName, string prefix, string nameWPrefix)
+            internal void SetNamedNode(XmlNodeType type, string localName, string prefix, string? nameWPrefix)
             {
                 Debug.Assert(localName != null);
                 Debug.Assert(localName.Length > 0);
@@ -637,10 +650,12 @@ namespace System.Xml
                 }
                 if (_valueStartPos != -1)
                 {
+                    Debug.Assert(_chars != null);
                     XmlTextReaderImpl.AdjustLineInfo(_chars, _valueStartPos, _valueStartPos + valueOffset, isNormalized, ref lineInfo);
                 }
                 else
                 {
+                    Debug.Assert(_value != null);
                     XmlTextReaderImpl.AdjustLineInfo(_value, 0, valueOffset, isNormalized, ref lineInfo);
                 }
             }
@@ -672,9 +687,9 @@ namespace System.Xml
                 return nameWPrefix;
             }
 
-            int IComparable.CompareTo(object obj)
+            int IComparable.CompareTo(object? obj)
             {
-                NodeData other = obj as NodeData;
+                NodeData? other = obj as NodeData;
                 if (other != null)
                 {
                     if (Ref.Equal(localName, other.localName))
@@ -715,7 +730,7 @@ namespace System.Xml
                 get { return s_instance; }
             }
 
-            public int Compare(object x, object y)
+            public int Compare(object? x, object? y)
             {
                 Debug.Assert(x == null || x is NodeData || x is IDtdDefaultAttributeInfo);
                 Debug.Assert(y == null || y is NodeData || y is IDtdDefaultAttributeInfo);
@@ -732,7 +747,7 @@ namespace System.Xml
                     return 1;
                 }
 
-                NodeData nodeData = x as NodeData;
+                NodeData? nodeData = x as NodeData;
                 if (nodeData != null)
                 {
                     localName = nodeData.localName;
@@ -740,8 +755,7 @@ namespace System.Xml
                 }
                 else
                 {
-                    IDtdDefaultAttributeInfo attrDef = x as IDtdDefaultAttributeInfo;
-                    if (attrDef != null)
+                    if (x is IDtdDefaultAttributeInfo attrDef)
                     {
                         localName = attrDef.LocalName;
                         prefix = attrDef.Prefix;
@@ -760,8 +774,7 @@ namespace System.Xml
                 }
                 else
                 {
-                    IDtdDefaultAttributeInfo attrDef = y as IDtdDefaultAttributeInfo;
-                    if (attrDef != null)
+                    if (y is IDtdDefaultAttributeInfo attrDef)
                     {
                         localName2 = attrDef.LocalName;
                         prefix2 = attrDef.Prefix;
index 1327eb9..d412522 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.
 
+#nullable enable
 using System;
 using System.IO;
 using System.Text;
@@ -44,13 +45,13 @@ namespace System.Xml
     public abstract partial class XmlWriter : IDisposable
     {
         // Helper buffer for WriteNode(XmlReader, bool)
-        private char[] _writeNodeBuffer;
+        private char[]? _writeNodeBuffer;
 
         // Constants
         private const int WriteNodeBufferSize = 1024;
 
         // Returns the settings describing the features of the writer. Returns null for V1 XmlWriters (XmlTextWriter).
-        public virtual XmlWriterSettings Settings
+        public virtual XmlWriterSettings? Settings
         {
             get
             {
@@ -73,22 +74,22 @@ namespace System.Xml
 
         // Writes out the DOCTYPE declaration with the specified name and optional attributes.
 
-        public abstract void WriteDocType(string name, string pubid, string sysid, string subset);
+        public abstract void WriteDocType(string name, string? pubid, string? sysid, string subset);
 
         // Writes out the specified start tag and associates it with the given namespace.
-        public void WriteStartElement(string localName, string ns)
+        public void WriteStartElement(string localName, string? ns)
         {
             WriteStartElement(null, localName, ns);
         }
 
         // Writes out the specified start tag and associates it with the given namespace and prefix.
 
-        public abstract void WriteStartElement(string prefix, string localName, string ns);
+        public abstract void WriteStartElement(string? prefix, string localName, string? ns);
 
         // Writes out a start tag with the specified local name with no namespace.
         public void WriteStartElement(string localName)
         {
-            WriteStartElement(null, localName, (string)null);
+            WriteStartElement(null, localName, (string?)null);
         }
 
         // Closes one element and pops the corresponding namespace scope.
@@ -100,7 +101,7 @@ namespace System.Xml
         public abstract void WriteFullEndElement();
 
         // Writes out the attribute with the specified LocalName, value, and NamespaceURI.
-        public void WriteAttributeString(string localName, string ns, string value)
+        public void WriteAttributeString(string localName, string? ns, string value)
         {
             WriteStartAttribute(null, localName, ns);
             WriteString(value);
@@ -110,13 +111,13 @@ namespace System.Xml
         // Writes out the attribute with the specified LocalName and value.
         public void WriteAttributeString(string localName, string value)
         {
-            WriteStartAttribute(null, localName, (string)null);
+            WriteStartAttribute(null, localName, (string?)null);
             WriteString(value);
             WriteEndAttribute();
         }
 
         // Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value.
-        public void WriteAttributeString(string prefix, string localName, string ns, string value)
+        public void WriteAttributeString(string? prefix, string localName, string? ns, string value)
         {
             WriteStartAttribute(prefix, localName, ns);
             WriteString(value);
@@ -124,19 +125,19 @@ namespace System.Xml
         }
 
         // Writes the start of an attribute.
-        public void WriteStartAttribute(string localName, string ns)
+        public void WriteStartAttribute(string localName, string? ns)
         {
             WriteStartAttribute(null, localName, ns);
         }
 
         // Writes the start of an attribute.
 
-        public abstract void WriteStartAttribute(string prefix, string localName, string ns);
+        public abstract void WriteStartAttribute(string? prefix, string localName, string? ns);
 
         // Writes the start of an attribute.
         public void WriteStartAttribute(string localName)
         {
-            WriteStartAttribute(null, localName, (string)null);
+            WriteStartAttribute(null, localName, (string?)null);
         }
 
         // Closes the attribute opened by WriteStartAttribute call.
@@ -208,7 +209,7 @@ namespace System.Xml
         public abstract void Flush();
 
         // Returns the closest prefix defined in the current namespace scope for the specified namespace URI.
-        public abstract string LookupPrefix(string ns);
+        public abstract string? LookupPrefix(string ns);
 
         // Gets an XmlSpace representing the current xml:space scope.
         public virtual XmlSpace XmlSpace
@@ -249,11 +250,11 @@ namespace System.Xml
         }
 
         // Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
-        public virtual void WriteQualifiedName(string localName, string ns)
+        public virtual void WriteQualifiedName(string localName, string? ns)
         {
             if (ns != null && ns.Length > 0)
             {
-                string prefix = LookupPrefix(ns);
+                string? prefix = LookupPrefix(ns);
                 if (prefix == null)
                 {
                     throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
@@ -275,7 +276,7 @@ namespace System.Xml
         }
 
         // Writes out the specified value.
-        public virtual void WriteValue(string value)
+        public virtual void WriteValue(string? value)
         {
             if (value == null)
             {
@@ -590,30 +591,32 @@ namespace System.Xml
         // Element Helper Methods
 
         // Writes out an element with the specified name containing the specified string value.
-        public void WriteElementString(string localName, string value)
+        public void WriteElementString(string localName, string? value)
         {
             WriteElementString(localName, null, value);
         }
 
         // Writes out an attribute with the specified name, namespace URI and string value.
-        public void WriteElementString(string localName, string ns, string value)
+        public void WriteElementString(string localName, string? ns, string? value)
         {
             WriteStartElement(localName, ns);
             if (null != value && 0 != value.Length)
             {
                 WriteString(value);
             }
+
             WriteEndElement();
         }
 
         // Writes out an attribute with the specified name, namespace URI, and string value.
-        public void WriteElementString(string prefix, string localName, string ns, string value)
+        public void WriteElementString(string? prefix, string localName, string? ns, string? value)
         {
             WriteStartElement(prefix, localName, ns);
             if (null != value && 0 != value.Length)
             {
                 WriteString(value);
             }
+
             WriteEndElement();
         }
 
@@ -681,7 +684,7 @@ namespace System.Xml
         }
 
         // Creates an XmlWriter for writing into the provided file with the specified settings.
-        public static XmlWriter Create(string outputFileName, XmlWriterSettings settings)
+        public static XmlWriter Create(string outputFileName, XmlWriterSettings? settings)
         {
             settings ??= XmlWriterSettings.s_defaultWriterSettings;
             return settings.CreateWriter(outputFileName);
@@ -703,7 +706,7 @@ namespace System.Xml
         }
 
         // Creates an XmlWriter for writing into the provided stream with the specified settings.
-        public static XmlWriter Create(Stream output, XmlWriterSettings settings)
+        public static XmlWriter Create(Stream output, XmlWriterSettings? settings)
         {
             settings ??= XmlWriterSettings.s_defaultWriterSettings;
             return settings.CreateWriter(output);
@@ -725,7 +728,7 @@ namespace System.Xml
         }
 
         // Creates an XmlWriter for writing into the provided TextWriter with the specified settings.
-        public static XmlWriter Create(TextWriter output, XmlWriterSettings settings)
+        public static XmlWriter Create(TextWriter output, XmlWriterSettings? settings)
         {
             settings ??= XmlWriterSettings.s_defaultWriterSettings;
             return settings.CreateWriter(output);
@@ -745,7 +748,7 @@ namespace System.Xml
         }
 
         // Creates an XmlWriter for writing into the provided StringBuilder with the specified settings.
-        public static XmlWriter Create(StringBuilder output, XmlWriterSettings settings)
+        public static XmlWriter Create(StringBuilder output, XmlWriterSettings? settings)
         {
             if (output == null)
             {
@@ -763,7 +766,7 @@ namespace System.Xml
         }
 
         // Creates an XmlWriter wrapped around the provided XmlWriter with the specified settings.
-        public static XmlWriter Create(XmlWriter output, XmlWriterSettings settings)
+        public static XmlWriter Create(XmlWriter output, XmlWriterSettings? settings)
         {
             settings ??= XmlWriterSettings.s_defaultWriterSettings;
             return settings.CreateWriter(output);
index 961be36..7e36a62 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.
 
+#nullable enable
 using System.Threading.Tasks;
 
 using System;
@@ -44,14 +45,14 @@ namespace System.Xml
 
         // Writes out the DOCTYPE declaration with the specified name and optional attributes.
 
-        public virtual Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset)
+        public virtual Task WriteDocTypeAsync(string name, string? pubid, string? sysid, string subset)
         {
             throw new NotImplementedException();
         }
 
         // Writes out the specified start tag and associates it with the given namespace and prefix.
 
-        public virtual Task WriteStartElementAsync(string prefix, string localName, string ns)
+        public virtual Task WriteStartElementAsync(string? prefix, string localName, string? ns)
         {
             throw new NotImplementedException();
         }
@@ -70,9 +71,8 @@ namespace System.Xml
             throw new NotImplementedException();
         }
 
-        // Writes out the attribute with the specified LocalName, value, and NamespaceURI.
         // Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value.
-        public Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value)
+        public Task WriteAttributeStringAsync(string? prefix, string localName, string? ns, string value)
         {
             Task task = WriteStartAttributeAsync(prefix, localName, ns);
             if (task.IsSuccess())
@@ -94,7 +94,7 @@ namespace System.Xml
 
         // Writes the start of an attribute.
 
-        protected internal virtual Task WriteStartAttributeAsync(string prefix, string localName, string ns)
+        protected internal virtual Task WriteStartAttributeAsync(string? prefix, string localName, string? ns)
         {
             throw new NotImplementedException();
         }
@@ -224,11 +224,11 @@ namespace System.Xml
         }
 
         // Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
-        public virtual async Task WriteQualifiedNameAsync(string localName, string ns)
+        public virtual async Task WriteQualifiedNameAsync(string localName, string? ns)
         {
             if (ns != null && ns.Length > 0)
             {
-                string prefix = LookupPrefix(ns);
+                string? prefix = LookupPrefix(ns);
                 if (prefix == null)
                 {
                     throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
@@ -568,7 +568,7 @@ namespace System.Xml
         // Element Helper Methods
 
         // Writes out an attribute with the specified name, namespace URI, and string value.
-        public async Task WriteElementStringAsync(string prefix, string localName, string ns, string value)
+        public async Task WriteElementStringAsync(string? prefix, string localName, string? ns, string value)
         {
             await WriteStartElementAsync(prefix, localName, ns).ConfigureAwait(false);
             if (null != value && 0 != value.Length)
index 3519ce4..d1e7e15 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.
 
+#nullable enable
 namespace System.Xml
 {
     public interface IXmlLineInfo
@@ -19,7 +20,7 @@ namespace System.Xml
 
         public static PositionInfo GetPositionInfo(object o)
         {
-            IXmlLineInfo li = o as IXmlLineInfo;
+            IXmlLineInfo? li = o as IXmlLineInfo;
             if (li != null)
             {
                 return new ReaderPositionInfo(li);
index 5b15ea7..83ff8c3 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.
 
+#nullable enable
 using System;
 using System.Collections;
 using System.Collections.Generic;
@@ -23,7 +24,7 @@ namespace System.Xml
         // The "xml" prefix is always mapped to the "http://www.w3.org/XML/1998/namespace" namespace.
         // The "xmlns" prefix is always mapped to the "http://www.w3.org/2000/xmlns/" namespace.
         // If the default namespace has not been defined, then the "" prefix is mapped to "" (the empty namespace).
-        string LookupNamespace(string prefix);
+        string? LookupNamespace(string prefix);
 
         // Return a prefix which is mapped to the specified namespace.  Multiple prefixes can be mapped to the
         // same namespace, and it is undefined which prefix will be returned.  Returns null if no prefixes are
@@ -31,6 +32,6 @@ namespace System.Xml
         // The "xml" prefix is always mapped to the "http://www.w3.org/XML/1998/namespace" namespace.
         // The "xmlns" prefix is always mapped to the "http://www.w3.org/2000/xmlns/" namespace.
         // If the default namespace has not been defined, then the "" prefix is mapped to "" (the empty namespace).
-        string LookupPrefix(string namespaceName);
+        string? LookupPrefix(string namespaceName);
     }
 }
index cd2d200..5bb3c73 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.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 namespace System.Xml
@@ -60,6 +61,7 @@ namespace System.Xml
             {
                 throw new ArgumentNullException(nameof(key));
             }
+
             int len = key.Length;
             if (len == 0)
             {
@@ -75,6 +77,7 @@ namespace System.Xml
                     return e.str;
                 }
             }
+
             return AddEntry(key, hashCode);
         }
 
@@ -112,18 +115,20 @@ namespace System.Xml
                     return e.str;
                 }
             }
+
             return AddEntry(new string(key, start, len), hashCode);
         }
 
         /// <devdoc>
         ///      Find the matching string in the NameTable.
         /// </devdoc>
-        public override string Get(string value)
+        public override string? Get(string value)
         {
             if (value == null)
             {
                 throw new ArgumentNullException(nameof(value));
             }
+
             if (value.Length == 0)
             {
                 return string.Empty;
@@ -138,6 +143,7 @@ namespace System.Xml
                     return e.str;
                 }
             }
+
             return null;
         }
 
@@ -145,7 +151,7 @@ namespace System.Xml
         ///      Find the matching string atom given a range of
         ///      characters.
         /// </devdoc>
-        public override string Get(char[] key, int start, int len)
+        public override string? Get(char[] key, int start, int len)
         {
             if (len == 0)
             {
@@ -172,6 +178,7 @@ namespace System.Xml
                     return e.str;
                 }
             }
+
             return null;
         }
 
@@ -203,10 +210,12 @@ namespace System.Xml
             int index = hashCode & _mask;
             Entry e = new Entry(str, hashCode, _entries[index]);
             _entries[index] = e;
+
             if (_count++ == _mask)
             {
                 Grow();
             }
+
             return e.str;
         }
 
@@ -240,6 +249,7 @@ namespace System.Xml
             {
                 return false;
             }
+
             // use array.Length to eliminate the range check
             for (int i = 0; i < str1.Length; i++)
             {
@@ -250,6 +260,7 @@ namespace System.Xml
             }
             return true;
         }
+
         private static int ComputeHash32(char[] key, int start, int len)
         {
             ReadOnlySpan<byte> bytes = MemoryMarshal.AsBytes(new ReadOnlySpan<char>(key, start, len));
index 8ee06b1..4cfd493 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.
 
+#nullable enable
 using System;
 using System.IO;
 using System.Net;
@@ -10,7 +11,7 @@ namespace System.Xml
 {
     internal partial class XmlDownloadManager
     {
-        internal Stream GetStream(Uri uri, ICredentials credentials, IWebProxy proxy)
+        internal Stream GetStream(Uri uri, ICredentials? credentials, IWebProxy? proxy)
         {
             if (uri.Scheme == "file")
             {
index 4c51ff1..694ae92 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.
 
+#nullable enable
 using System;
 using System.IO;
 using System.Net;
@@ -12,7 +13,7 @@ namespace System.Xml
 {
     internal partial class XmlDownloadManager
     {
-        internal Task<Stream> GetStreamAsync(Uri uri, ICredentials credentials, IWebProxy proxy)
+        internal Task<Stream> GetStreamAsync(Uri uri, ICredentials? credentials, IWebProxy? proxy)
         {
             if (uri.Scheme == "file")
             {
@@ -25,7 +26,7 @@ namespace System.Xml
             }
         }
 
-        private async Task<Stream> GetNonFileStreamAsync(Uri uri, ICredentials credentials, IWebProxy proxy)
+        private async Task<Stream> GetNonFileStreamAsync(Uri uri, ICredentials? credentials, IWebProxy? proxy)
         {
             var handler = new HttpClientHandler();
             using (var client = new HttpClient(handler))
index 96f0daf..7e098be 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.
 
+#nullable enable
 using System;
 using System.Resources;
 using System.Text;
@@ -21,35 +22,35 @@ namespace System.Xml
     public class XmlException : SystemException
     {
         private readonly string _res;
-        private readonly string[] _args; // this field is not used, it's here just V1.1 serialization compatibility
+        private readonly string?[]? _args; // this field is not used, it's here just V1.1 serialization compatibility
         private readonly int _lineNumber;
         private readonly int _linePosition;
 
-        private readonly string _sourceUri;
+        private readonly string? _sourceUri;
 
         // message != null for V1 exceptions deserialized in Whidbey
         // message == null for V2 or higher exceptions; the exception message is stored on the base class (Exception._message)
-        private readonly string _message;
+        private readonly string? _message;
 
         protected XmlException(SerializationInfo info, StreamingContext context) : base(info, context)
         {
-            _res = (string)info.GetValue("res", typeof(string));
-            _args = (string[])info.GetValue("args", typeof(string[]));
-            _lineNumber = (int)info.GetValue("lineNumber", typeof(int));
-            _linePosition = (int)info.GetValue("linePosition", typeof(int));
+            _res = (string)info.GetValue("res", typeof(string))!;
+            _args = (string?[])info.GetValue("args", typeof(string[]))!;
+            _lineNumber = (int)info.GetValue("lineNumber", typeof(int))!;
+            _linePosition = (int)info.GetValue("linePosition", typeof(int))!;
 
             // deserialize optional members
             _sourceUri = string.Empty;
-            string version = null;
+            string? version = null;
             foreach (SerializationEntry e in info)
             {
                 switch (e.Name)
                 {
                     case "sourceUri":
-                        _sourceUri = (string)e.Value;
+                        _sourceUri = (string?)e.Value;
                         break;
                     case "version":
-                        version = (string)e.Value;
+                        version = (string?)e.Value;
                         break;
                 }
             }
@@ -83,85 +84,83 @@ namespace System.Xml
         }
 
         //provided to meet the ECMA standards
-        public XmlException(string message) : this(message, ((Exception)null), 0, 0)
+        public XmlException(string? message) : this(message, ((Exception?)null), 0, 0)
         {
-#if DEBUG
             Debug.Assert(message == null || !message.StartsWith("Xml_", StringComparison.Ordinal), "Do not pass a resource here!");
-#endif
         }
 
         //provided to meet ECMA standards
-        public XmlException(string message, Exception innerException) : this(message, innerException, 0, 0)
+        public XmlException(string? message, Exception? innerException) : this(message, innerException, 0, 0)
         {
         }
 
         //provided to meet ECMA standards
-        public XmlException(string message, Exception innerException, int lineNumber, int linePosition) :
+        public XmlException(string? message, Exception? innerException, int lineNumber, int linePosition) :
             this(message, innerException, lineNumber, linePosition, null)
         {
         }
 
-        internal XmlException(string message, Exception innerException, int lineNumber, int linePosition, string sourceUri) :
+        internal XmlException(string? message, Exception? innerException, int lineNumber, int linePosition, string? sourceUri) :
             base(FormatUserMessage(message, lineNumber, linePosition), innerException)
         {
             HResult = HResults.Xml;
             _res = (message == null ? SR.Xml_DefaultException : SR.Xml_UserException);
-            _args = new string[] { message };
+            _args = new string?[] { message };
             _sourceUri = sourceUri;
             _lineNumber = lineNumber;
             _linePosition = linePosition;
         }
 
-        internal XmlException(string res, string[] args) :
+        internal XmlException(string res, string?[]? args) :
             this(res, args, null, 0, 0, null)
         { }
 
-        internal XmlException(string res, string arg) :
-            this(res, new string[] { arg }, null, 0, 0, null)
+        internal XmlException(string res, string? arg) :
+            this(res, new string?[] { arg }, null, 0, 0, null)
         { }
 
-        internal XmlException(string res, string arg, string sourceUri) :
-            this(res, new string[] { arg }, null, 0, 0, sourceUri)
+        internal XmlException(string res, string? arg, string? sourceUri) :
+            this(res, new string?[] { arg }, null, 0, 0, sourceUri)
         { }
 
-        internal XmlException(string res, string arg, IXmlLineInfo lineInfo) :
-            this(res, new string[] { arg }, lineInfo, null)
+        internal XmlException(string res, string? arg, IXmlLineInfo? lineInfo) :
+            this(res, new string?[] { arg }, lineInfo, null)
         { }
 
-        internal XmlException(string res, string arg, Exception innerException, IXmlLineInfo lineInfo) :
-            this(res, new string[] { arg }, innerException, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), null)
+        internal XmlException(string res, string? arg, Exception? innerException, IXmlLineInfo? lineInfo) :
+            this(res, new string?[] { arg }, innerException, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), null)
         { }
 
-        internal XmlException(string res, string[] args, IXmlLineInfo lineInfo) :
+        internal XmlException(string res, string?[]? args, IXmlLineInfo? lineInfo) :
             this(res, args, lineInfo, null)
         { }
 
-        internal XmlException(string res, string[] args, IXmlLineInfo lineInfo, string sourceUri) :
+        internal XmlException(string res, string?[]? args, IXmlLineInfo? lineInfo, string? sourceUri) :
             this(res, args, null, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), sourceUri)
         {
         }
 
-        internal XmlException(string res, string arg, int lineNumber, int linePosition) :
-            this(res, new string[] { arg }, null, lineNumber, linePosition, null)
+        internal XmlException(string res, string? arg, int lineNumber, int linePosition) :
+            this(res, new string?[] { arg }, null, lineNumber, linePosition, null)
         { }
 
-        internal XmlException(string res, string arg, int lineNumber, int linePosition, string sourceUri) :
-            this(res, new string[] { arg }, null, lineNumber, linePosition, sourceUri)
+        internal XmlException(string res, string? arg, int lineNumber, int linePosition, string? sourceUri) :
+            this(res, new string?[] { arg }, null, lineNumber, linePosition, sourceUri)
         { }
 
-        internal XmlException(string res, string[] args, int lineNumber, int linePosition) :
+        internal XmlException(string res, string?[]? args, int lineNumber, int linePosition) :
             this(res, args, null, lineNumber, linePosition, null)
         { }
 
-        internal XmlException(string res, string[] args, int lineNumber, int linePosition, string sourceUri) :
+        internal XmlException(string res, string?[]? args, int lineNumber, int linePosition, string? sourceUri) :
             this(res, args, null, lineNumber, linePosition, sourceUri)
         { }
 
-        internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition) :
+        internal XmlException(string res, string?[]? args, Exception? innerException, int lineNumber, int linePosition) :
             this(res, args, innerException, lineNumber, linePosition, null)
         { }
 
-        internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition, string sourceUri) :
+        internal XmlException(string res, string?[]? args, Exception? innerException, int lineNumber, int linePosition, string? sourceUri) :
             base(CreateMessage(res, args, lineNumber, linePosition), innerException)
         {
             HResult = HResults.Xml;
@@ -172,7 +171,7 @@ namespace System.Xml
             _linePosition = linePosition;
         }
 
-        private static string FormatUserMessage(string message, int lineNumber, int linePosition)
+        private static string FormatUserMessage(string? message, int lineNumber, int linePosition)
         {
             if (message == null)
             {
@@ -193,24 +192,18 @@ namespace System.Xml
             }
         }
 
-        private static string CreateMessage(string res, string[] args, int lineNumber, int linePosition)
+        private static string CreateMessage(string res, string?[]? args, int lineNumber, int linePosition)
         {
             try
             {
-                string message;
+                string message = (args == null) ? res : string.Format(res, args);
 
-                // No line information -> get resource string and return
-                if (lineNumber == 0)
-                {
-                    message = (args == null) ? res : string.Format(res, args);
-                }
                 // Line information is available -> we need to append it to the error message
-                else
+                if (lineNumber != 0)
                 {
                     string lineNumberStr = lineNumber.ToString(CultureInfo.InvariantCulture);
                     string linePositionStr = linePosition.ToString(CultureInfo.InvariantCulture);
 
-                    message = string.Format(res, args);
                     message = SR.Format(SR.Xml_MessageWithErrorPosition, new string[] { message, lineNumberStr, linePositionStr });
                 }
                 return message;
@@ -273,7 +266,7 @@ namespace System.Xml
             get { return _linePosition; }
         }
 
-        public string SourceUri
+        public string? SourceUri
         {
             get { return _sourceUri; }
         }
index 780707c..12a839e 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.
 
+#nullable enable
 namespace System.Xml
 {
     /// <devdoc>
@@ -17,7 +18,7 @@ namespace System.Xml
         ///    <para>Gets the atomized String object containing the same
         ///       chars as the specified range of chars in the given char array.</para>
         /// </devdoc>
-        public abstract string Get(char[] array, int offset, int length);
+        public abstract string? Get(char[] array, int offset, int length);
 
         /// <devdoc>
         ///    <para>
@@ -25,7 +26,7 @@ namespace System.Xml
         ///       value as the specified string.
         ///    </para>
         /// </devdoc>
-        public abstract string Get(string array);
+        public abstract string? Get(string array);
 
         /// <devdoc>
         ///    <para>Creates a new atom for the characters at the specified range
index 567bccc..3f1ff9f 100644 (file)
@@ -2,10 +2,12 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Collections;
 using System.Diagnostics;
 using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.Xml
 {
@@ -14,7 +16,7 @@ namespace System.Xml
         private struct NamespaceDeclaration
         {
             public string prefix;
-            public string uri;
+            public string? uri;
             public int scopeId;
             public int previousNsIndex;
 
@@ -28,24 +30,24 @@ namespace System.Xml
         }
 
         // array with namespace declarations
-        private NamespaceDeclaration[] _nsdecls;
+        private NamespaceDeclaration[]? _nsdecls;
 
         // index of last declaration
         private int _lastDecl = 0;
 
         // name table
-        private readonly XmlNameTable _nameTable;
+        private readonly XmlNameTable? _nameTable;
 
         // ID (depth) of the current scope
         private int _scopeId;
 
         // hash table for faster lookup when there is lots of namespaces
-        private Dictionary<string, int> _hashTable;
+        private Dictionary<string, int>? _hashTable;
         private bool _useHashtable;
 
         // atomized prefixes for "xml" and "xmlns"
-        private readonly string _xml;
-        private readonly string _xmlNs;
+        private readonly string? _xml;
+        private readonly string? _xmlNs;
 
         // Constants
         private const int MinDeclsCountForHashtable = 16;
@@ -69,7 +71,7 @@ namespace System.Xml
             _scopeId = 1;
         }
 
-        public virtual XmlNameTable NameTable
+        public virtual XmlNameTable? NameTable
         {
             get
             {
@@ -81,7 +83,7 @@ namespace System.Xml
         {
             get
             {
-                string defaultNs = LookupNamespace(string.Empty);
+                string? defaultNs = LookupNamespace(string.Empty);
                 return (defaultNs == null) ? string.Empty : defaultNs;
             }
         }
@@ -98,15 +100,21 @@ namespace System.Xml
             {
                 return false;
             }
+
+            Debug.Assert(_nsdecls != null);
+
             while (_nsdecls[decl].scopeId == _scopeId)
             {
                 if (_useHashtable)
                 {
+                    Debug.Assert(_hashTable != null);
                     _hashTable[_nsdecls[decl].prefix] = _nsdecls[decl].previousNsIndex;
                 }
+
                 decl--;
                 Debug.Assert(decl >= 2);
             }
+
             _lastDecl = decl;
             _scopeId--;
             return true;
@@ -120,6 +128,8 @@ namespace System.Xml
             if (prefix == null)
                 throw new ArgumentNullException(nameof(prefix));
 
+            Debug.Assert(_nameTable != null);
+            Debug.Assert(_nsdecls != null);
             prefix = _nameTable.Add(prefix);
             uri = _nameTable.Add(uri);
 
@@ -162,6 +172,7 @@ namespace System.Xml
             // add to hashTable
             if (_useHashtable)
             {
+                Debug.Assert(_hashTable != null);
                 _hashTable[prefix] = _lastDecl;
             }
             // or create a new hashTable if the threshold has been reached
@@ -174,6 +185,7 @@ namespace System.Xml
                 {
                     _hashTable[_nsdecls[i].prefix] = i;
                 }
+
                 _useHashtable = true;
             }
         }
@@ -189,6 +201,8 @@ namespace System.Xml
                 throw new ArgumentNullException(nameof(prefix));
             }
 
+            Debug.Assert(_nsdecls != null);
+
             int declIndex = LookupNamespaceDecl(prefix);
             while (declIndex != -1)
             {
@@ -202,6 +216,8 @@ namespace System.Xml
 
         public virtual IEnumerator GetEnumerator()
         {
+            Debug.Assert(_nsdecls != null);
+
             Dictionary<string, string> prefixes = new Dictionary<string, string>(_lastDecl + 1);
             for (int thisDecl = 0; thisDecl <= _lastDecl; thisDecl++)
             {
@@ -216,8 +232,10 @@ namespace System.Xml
         // This pragma disables a warning that the return type is not CLS-compliant, but generics are part of CLS in Whidbey.
 #pragma warning disable 3002
         public virtual IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
-        {
 #pragma warning restore 3002
+        {
+            Debug.Assert(_nsdecls != null);
+
             int i = 0;
             switch (scope)
             {
@@ -241,8 +259,8 @@ namespace System.Xml
             Dictionary<string, string> dict = new Dictionary<string, string>(_lastDecl - i + 1);
             for (; i <= _lastDecl; i++)
             {
-                string prefix = _nsdecls[i].prefix;
-                string uri = _nsdecls[i].uri;
+                string? prefix = _nsdecls[i].prefix;
+                string? uri = _nsdecls[i].uri;
                 Debug.Assert(prefix != null);
 
                 if (uri != null)
@@ -258,19 +276,24 @@ namespace System.Xml
                     }
                 }
             }
+
             return dict;
         }
 
-        public virtual string LookupNamespace(string prefix)
+        public virtual string? LookupNamespace(string prefix)
         {
+            Debug.Assert(_nsdecls != null);
             int declIndex = LookupNamespaceDecl(prefix);
             return (declIndex == -1) ? null : _nsdecls[declIndex].uri;
         }
 
         private int LookupNamespaceDecl(string prefix)
         {
+            Debug.Assert(_nsdecls != null);
+
             if (_useHashtable)
             {
+                Debug.Assert(_hashTable != null);
                 int declIndex;
                 if (_hashTable.TryGetValue(prefix, out declIndex))
                 {
@@ -305,8 +328,10 @@ namespace System.Xml
             return -1;
         }
 
-        public virtual string LookupPrefix(string uri)
+        public virtual string? LookupPrefix(string uri)
         {
+            Debug.Assert(_nsdecls != null);
+
             // Don't assume that prefix is atomized
             for (int thisDecl = _lastDecl; thisDecl >= 0; thisDecl--)
             {
@@ -324,12 +349,14 @@ namespace System.Xml
 
         public virtual bool HasNamespace(string prefix)
         {
+            Debug.Assert(_nsdecls != null);
+
             // Don't assume that prefix is atomized
             for (int thisDecl = _lastDecl; _nsdecls[thisDecl].scopeId == _scopeId; thisDecl--)
             {
                 if (string.Equals(_nsdecls[thisDecl].prefix, prefix) && _nsdecls[thisDecl].uri != null)
                 {
-                    if (prefix.Length > 0 || _nsdecls[thisDecl].uri.Length > 0)
+                    if (prefix.Length > 0 || _nsdecls[thisDecl].uri!.Length > 0)
                     {
                         return true;
                     }
@@ -339,7 +366,7 @@ namespace System.Xml
             return false;
         }
 
-        internal bool GetNamespaceDeclaration(int idx, out string prefix, out string uri)
+        internal bool GetNamespaceDeclaration(int idx, [NotNullWhen(true)] out string? prefix, out string? uri)
         {
             idx = _lastDecl - idx;
             if (idx < 0)
@@ -348,6 +375,7 @@ namespace System.Xml
                 return false;
             }
 
+            Debug.Assert(_nsdecls != null);
             prefix = _nsdecls[idx].prefix;
             uri = _nsdecls[idx].uri;
 
index 86e1c1a..c54d7e6 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.
 
+#nullable enable
 namespace System.Xml
 {
     using System;
@@ -11,6 +12,7 @@ namespace System.Xml
     using System.Net;
     using System.Threading.Tasks;
     using System.Runtime.Versioning;
+    using System.Diagnostics;
 
     /// <devdoc>
     ///    <para>Resolves external XML resources named by a Uniform
@@ -24,24 +26,25 @@ namespace System.Xml
         ///       URI to an Object containing the actual resource.</para>
         /// </devdoc>
 
-        public abstract object GetEntity(Uri absoluteUri,
-                                         string role,
-                                         Type ofObjectToReturn);
+        public abstract object? GetEntity(Uri absoluteUri,
+                                          string? role,
+                                          Type? ofObjectToReturn);
 
 
 
         /// <devdoc>
         ///    <para>[To be supplied.]</para>
         /// </devdoc>
-        public virtual Uri ResolveUri(Uri baseUri, string relativeUri)
+        public virtual Uri ResolveUri(Uri? baseUri, string? relativeUri)
         {
             if (baseUri == null || (!baseUri.IsAbsoluteUri && baseUri.OriginalString.Length == 0))
             {
-                Uri uri = new Uri(relativeUri, UriKind.RelativeOrAbsolute);
+                Uri uri = new Uri(relativeUri!, UriKind.RelativeOrAbsolute);
                 if (!uri.IsAbsoluteUri && uri.OriginalString.Length > 0)
                 {
-                    uri = new Uri(Path.GetFullPath(relativeUri));
+                    uri = new Uri(Path.GetFullPath(relativeUri!));
                 }
+
                 return uri;
             }
             else
@@ -50,11 +53,13 @@ namespace System.Xml
                 {
                     return baseUri;
                 }
+
                 // relative base Uri
                 if (!baseUri.IsAbsoluteUri)
                 {
                     throw new NotSupportedException(SR.Xml_RelativeUriNotSupported);
                 }
+
                 return new Uri(baseUri, relativeUri);
             }
         }
index d2537bd..83c8ecc 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.
 
+#nullable enable
 using System.Threading;
 using System.Net;
 using System.Net.Cache;
@@ -12,9 +13,9 @@ namespace System.Xml
     // Resolves external XML resources named by a Uniform Resource Identifier (URI).
     public partial class XmlUrlResolver : XmlResolver
     {
-        private static XmlDownloadManager s_downloadManager;
-        private ICredentials _credentials;
-        private IWebProxy _proxy;
+        private static XmlDownloadManager? s_downloadManager;
+        private ICredentials? _credentials;
+        private IWebProxy? _proxy;
 
         private static XmlDownloadManager DownloadManager =>
             s_downloadManager ??
@@ -23,12 +24,12 @@ namespace System.Xml
 
         public XmlUrlResolver() { }
 
-        public override ICredentials Credentials
+        public override ICredentials? Credentials
         {
             set { _credentials = value; }
         }
 
-        public IWebProxy Proxy
+        public IWebProxy? Proxy
         {
             set { _proxy = value; }
         }
@@ -39,7 +40,7 @@ namespace System.Xml
         }
 
         // Maps a URI to an Object containing the actual resource.
-        public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
+        public override object? GetEntity(Uri absoluteUri, string? role, Type? ofObjectToReturn)
         {
             if (ofObjectToReturn is null || ofObjectToReturn == typeof(System.IO.Stream) || ofObjectToReturn == typeof(object))
             {
@@ -49,7 +50,7 @@ namespace System.Xml
             throw new XmlException(SR.Xml_UnsupportedClass, string.Empty);
         }
 
-        public override Uri ResolveUri(Uri baseUri, string relativeUri) =>
+        public override Uri ResolveUri(Uri? baseUri, string? relativeUri) =>
             base.ResolveUri(baseUri, relativeUri);
     }
 }
index 53e3c97..290825d 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.
 
+#nullable enable
 using System.Runtime.Versioning;
 using System.Threading.Tasks;
 
@@ -10,7 +11,7 @@ namespace System.Xml
     public partial class XmlUrlResolver : XmlResolver
     {
         // Maps a URI to an Object containing the actual resource.
-        public override async Task<object> GetEntityAsync(Uri absoluteUri, string role, Type ofObjectToReturn)
+        public override async Task<object> GetEntityAsync(Uri absoluteUri, string role, Type? ofObjectToReturn)
         {
             if (ofObjectToReturn == null || ofObjectToReturn == typeof(System.IO.Stream) || ofObjectToReturn == typeof(object))
             {