Annotate System.Net.Primitives for nullable (#31794)
authorIlya <darpa@yandex.ru>
Fri, 21 Feb 2020 17:59:19 +0000 (22:59 +0500)
committerGitHub <noreply@github.com>
Fri, 21 Feb 2020 17:59:19 +0000 (17:59 +0000)
* Annotate System.Net.Primitives for nullable

* Fix build breaks in other libraries due to new annotations

Co-authored-by: Stephen Toub <stoub@microsoft.com>
22 files changed:
src/libraries/Common/src/Interop/Unix/System.Native/Interop.GetDomainName.cs
src/libraries/Common/src/System/Net/CookieParser.cs
src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs
src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs
src/libraries/System.Net.Primitives/ref/System.Net.Primitives.cs
src/libraries/System.Net.Primitives/ref/System.Net.Primitives.csproj
src/libraries/System.Net.Primitives/src/System.Net.Primitives.csproj
src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs
src/libraries/System.Net.Primitives/src/System/Net/CookieCollection.cs
src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs
src/libraries/System.Net.Primitives/src/System/Net/CookieException.cs
src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs
src/libraries/System.Net.Primitives/src/System/Net/DnsEndPoint.cs
src/libraries/System.Net.Primitives/src/System/Net/ICredentials.cs
src/libraries/System.Net.Primitives/src/System/Net/ICredentialsByHost.cs
src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs
src/libraries/System.Net.Primitives/src/System/Net/IPAddressParser.cs
src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs
src/libraries/System.Net.Primitives/src/System/Net/IWebProxy.cs
src/libraries/System.Net.Primitives/src/System/Net/NetworkCredential.cs
src/libraries/System.Net.Primitives/src/System/Net/TransportContext.cs
src/libraries/System.Net.ServicePoint/src/System/Net/ServicePointManager.cs

index 4466d63..a0f8494 100644 (file)
@@ -33,7 +33,7 @@ internal static partial class Interop
             }
 
             // Marshal.PtrToStringAnsi uses UTF8 on Unix.
-            return Marshal.PtrToStringAnsi((IntPtr)name);
+            return Marshal.PtrToStringAnsi((IntPtr)name)!;
         }
     }
 }
index d602ffe..c16c3fd 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.Diagnostics;
 using System.Globalization;
 using System.Reflection;
@@ -45,7 +46,7 @@ namespace System.Net
         private bool _eofCookie;
         private int _index;
         private readonly int _length;
-        private string _name;
+        private string? _name;
         private bool _quoted;
         private int _start;
         private CookieToken _token;
@@ -81,7 +82,7 @@ namespace System.Net
             }
         }
 
-        internal string Name
+        internal string? Name
         {
             get
             {
@@ -449,7 +450,7 @@ namespace System.Net
                 }
             }
 
-            internal bool IsEqualTo(string value)
+            internal bool IsEqualTo(string? value)
             {
                 return string.Equals(_name, value, StringComparison.OrdinalIgnoreCase);
             }
@@ -510,7 +511,7 @@ namespace System.Net
     internal struct CookieParser
     {
         private CookieTokenizer _tokenizer;
-        private Cookie _savedCookie;
+        private Cookie? _savedCookie;
 
         internal CookieParser(string cookieString)
         {
@@ -519,13 +520,13 @@ namespace System.Net
         }
 
 #if SYSTEM_NET_PRIMITIVES_DLL
-        private static bool InternalSetNameMethod(Cookie cookie, string value)
+        private static bool InternalSetNameMethod(Cookie cookie, string? value)
         {
             return cookie.InternalSetName(value);
         }
 #else
-        private static Func<Cookie, string, bool> s_internalSetNameMethod;
-        private static Func<Cookie, string, bool> InternalSetNameMethod
+        private static Func<Cookie, string?, bool>? s_internalSetNameMethod = null;
+        private static Func<Cookie, string?, bool> InternalSetNameMethod
         {
             get
             {
@@ -535,9 +536,9 @@ namespace System.Net
                     // We need to use Cookie.InternalSetName instead of the Cookie.set_Name wrapped in a try catch block, as
                     // Cookie.set_Name keeps the original name if the string is empty or null.
                     // Unfortunately this API is internal so we use reflection to access it. The method is cached for performance reasons.
-                    MethodInfo method = typeof(Cookie).GetMethod("InternalSetName", BindingFlags.Instance | BindingFlags.NonPublic);
+                    MethodInfo? method = typeof(Cookie).GetMethod("InternalSetName", BindingFlags.Instance | BindingFlags.NonPublic);
                     Debug.Assert(method != null, "We need to use an internal method named InternalSetName that is declared on Cookie.");
-                    s_internalSetNameMethod = (Func<Cookie, string, bool>)Delegate.CreateDelegate(typeof(Func<Cookie, string, bool>), method);
+                    s_internalSetNameMethod = (Func<Cookie, string?, bool>)Delegate.CreateDelegate(typeof(Func<Cookie, string?, bool>), method);
                 }
 
                 return s_internalSetNameMethod;
@@ -545,7 +546,7 @@ namespace System.Net
         }
 #endif
 
-        private static FieldInfo s_isQuotedDomainField = null;
+        private static FieldInfo? s_isQuotedDomainField = null;
         private static FieldInfo IsQuotedDomainField
         {
             get
@@ -553,7 +554,7 @@ namespace System.Net
                 if (s_isQuotedDomainField == null)
                 {
                     // TODO https://github.com/dotnet/runtime/issues/19348:
-                    FieldInfo field = typeof(Cookie).GetField("IsQuotedDomain", BindingFlags.Instance | BindingFlags.NonPublic);
+                    FieldInfo? field = typeof(Cookie).GetField("IsQuotedDomain", BindingFlags.Instance | BindingFlags.NonPublic);
                     Debug.Assert(field != null, "We need to use an internal field named IsQuotedDomain that is declared on Cookie.");
                     s_isQuotedDomainField = field;
                 }
@@ -562,7 +563,7 @@ namespace System.Net
             }
         }
 
-        private static FieldInfo s_isQuotedVersionField = null;
+        private static FieldInfo? s_isQuotedVersionField;
         private static FieldInfo IsQuotedVersionField
         {
             get
@@ -570,7 +571,7 @@ namespace System.Net
                 if (s_isQuotedVersionField == null)
                 {
                     // TODO https://github.com/dotnet/runtime/issues/19348:
-                    FieldInfo field = typeof(Cookie).GetField("IsQuotedVersion", BindingFlags.Instance | BindingFlags.NonPublic);
+                    FieldInfo? field = typeof(Cookie).GetField("IsQuotedVersion", BindingFlags.Instance | BindingFlags.NonPublic);
                     Debug.Assert(field != null, "We need to use an internal field named IsQuotedVersion that is declared on Cookie.");
                     s_isQuotedVersionField = field;
                 }
@@ -582,9 +583,9 @@ namespace System.Net
         // Get
         //
         // Gets the next cookie or null if there are no more cookies.
-        internal Cookie Get()
+        internal Cookie? Get()
         {
-            Cookie cookie = null;
+            Cookie? cookie = null;
 
             // Only the first occurrence of an attribute value must be counted.
             bool commentSet = false;
@@ -617,7 +618,7 @@ namespace System.Net
                                     if (!commentSet)
                                     {
                                         commentSet = true;
-                                        cookie.Comment = _tokenizer.Value;
+                                        cookie!.Comment = _tokenizer.Value;
                                     }
                                     break;
 
@@ -625,9 +626,9 @@ namespace System.Net
                                     if (!commentUriSet)
                                     {
                                         commentUriSet = true;
-                                        if (Uri.TryCreate(CheckQuoted(_tokenizer.Value), UriKind.Absolute, out Uri parsed))
+                                        if (Uri.TryCreate(CheckQuoted(_tokenizer.Value), UriKind.Absolute, out Uri? parsed))
                                         {
-                                            cookie.CommentUri = parsed;
+                                            cookie!.CommentUri = parsed;
                                         }
                                     }
                                     break;
@@ -636,7 +637,7 @@ namespace System.Net
                                     if (!domainSet)
                                     {
                                         domainSet = true;
-                                        cookie.Domain = CheckQuoted(_tokenizer.Value);
+                                        cookie!.Domain = CheckQuoted(_tokenizer.Value);
                                         IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted);
                                     }
                                     break;
@@ -649,12 +650,12 @@ namespace System.Net
                                         if (DateTime.TryParse(CheckQuoted(_tokenizer.Value),
                                             CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTime expires))
                                         {
-                                            cookie.Expires = expires;
+                                            cookie!.Expires = expires;
                                         }
                                         else
                                         {
                                             // This cookie will be rejected
-                                            InternalSetNameMethod(cookie, string.Empty);
+                                            InternalSetNameMethod(cookie!, string.Empty);
                                         }
                                     }
                                     break;
@@ -665,12 +666,12 @@ namespace System.Net
                                         expiresSet = true;
                                         if (int.TryParse(CheckQuoted(_tokenizer.Value), out int parsed))
                                         {
-                                            cookie.Expires = DateTime.Now.AddSeconds(parsed);
+                                            cookie!.Expires = DateTime.Now.AddSeconds(parsed);
                                         }
                                         else
                                         {
                                             // This cookie will be rejected
-                                            InternalSetNameMethod(cookie, string.Empty);
+                                            InternalSetNameMethod(cookie!, string.Empty);
                                         }
                                     }
                                     break;
@@ -679,7 +680,7 @@ namespace System.Net
                                     if (!pathSet)
                                     {
                                         pathSet = true;
-                                        cookie.Path = _tokenizer.Value;
+                                        cookie!.Path = _tokenizer.Value;
                                     }
                                     break;
 
@@ -689,12 +690,12 @@ namespace System.Net
                                         portSet = true;
                                         try
                                         {
-                                            cookie.Port = _tokenizer.Value;
+                                            cookie!.Port = _tokenizer.Value;
                                         }
                                         catch
                                         {
                                             // This cookie will be rejected
-                                            InternalSetNameMethod(cookie, string.Empty);
+                                            InternalSetNameMethod(cookie!, string.Empty);
                                         }
                                     }
                                     break;
@@ -706,13 +707,13 @@ namespace System.Net
                                         int parsed;
                                         if (int.TryParse(CheckQuoted(_tokenizer.Value), out parsed))
                                         {
-                                            cookie.Version = parsed;
+                                            cookie!.Version = parsed;
                                             IsQuotedVersionField.SetValue(cookie, _tokenizer.Quoted);
                                         }
                                         else
                                         {
                                             // This cookie will be rejected
-                                            InternalSetNameMethod(cookie, string.Empty);
+                                            InternalSetNameMethod(cookie!, string.Empty);
                                         }
                                     }
                                     break;
@@ -726,7 +727,7 @@ namespace System.Net
                                     if (!discardSet)
                                     {
                                         discardSet = true;
-                                        cookie.Discard = true;
+                                        cookie!.Discard = true;
                                     }
                                     break;
 
@@ -734,19 +735,19 @@ namespace System.Net
                                     if (!secureSet)
                                     {
                                         secureSet = true;
-                                        cookie.Secure = true;
+                                        cookie!.Secure = true;
                                     }
                                     break;
 
                                 case CookieToken.HttpOnly:
-                                    cookie.HttpOnly = true;
+                                    cookie!.HttpOnly = true;
                                     break;
 
                                 case CookieToken.Port:
                                     if (!portSet)
                                     {
                                         portSet = true;
-                                        cookie.Port = string.Empty;
+                                        cookie!.Port = string.Empty;
                                     }
                                     break;
                             }
@@ -758,9 +759,9 @@ namespace System.Net
             return cookie;
         }
 
-        internal Cookie GetServer()
+        internal Cookie? GetServer()
         {
-            Cookie cookie = _savedCookie;
+            Cookie? cookie = _savedCookie;
             _savedCookie = null;
 
             // Only the first occurrence of an attribute value must be counted.
@@ -793,7 +794,7 @@ namespace System.Net
                                     if (!domainSet)
                                     {
                                         domainSet = true;
-                                        cookie.Domain = CheckQuoted(_tokenizer.Value);
+                                        cookie!.Domain = CheckQuoted(_tokenizer.Value);
                                         IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted);
                                     }
                                     break;
@@ -802,7 +803,7 @@ namespace System.Net
                                     if (!pathSet)
                                     {
                                         pathSet = true;
-                                        cookie.Path = _tokenizer.Value;
+                                        cookie!.Path = _tokenizer.Value;
                                     }
                                     break;
 
@@ -812,12 +813,12 @@ namespace System.Net
                                         portSet = true;
                                         try
                                         {
-                                            cookie.Port = _tokenizer.Value;
+                                            cookie!.Port = _tokenizer.Value;
                                         }
                                         catch (CookieException)
                                         {
                                             // This cookie will be rejected
-                                            InternalSetNameMethod(cookie, string.Empty);
+                                            InternalSetNameMethod(cookie!, string.Empty);
                                         }
                                     }
                                     break;
@@ -844,7 +845,7 @@ namespace System.Net
                             if (_tokenizer.Token == CookieToken.Port && !portSet)
                             {
                                 portSet = true;
-                                cookie.Port = string.Empty;
+                                cookie!.Port = string.Empty;
                             }
                             break;
                     }
index 512f195..5a18dd6 100644 (file)
@@ -57,7 +57,7 @@ namespace System.Net
 
             // See if it's an IP Address.
             IPHostEntry ipHostEntry;
-            if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address))
+            if (IPAddress.TryParse(hostNameOrAddress, out IPAddress? address))
             {
                 if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
                 {
@@ -158,7 +158,7 @@ namespace System.Net
 
             // See if it's an IP Address.
             IPAddress[] addresses;
-            if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address))
+            if (IPAddress.TryParse(hostNameOrAddress, out IPAddress? address))
             {
                 if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
                 {
@@ -210,7 +210,7 @@ namespace System.Net
                 throw new ArgumentNullException(nameof(hostName));
             }
 
-            if (IPAddress.TryParse(hostName, out IPAddress address))
+            if (IPAddress.TryParse(hostName, out IPAddress? address))
             {
                 return CreateHostEntryForAddress(address);
             }
@@ -287,7 +287,7 @@ namespace System.Net
 
             // See if it's an IP Address.
             IPHostEntry ipHostEntry;
-            if (IPAddress.TryParse(hostName, out IPAddress address) &&
+            if (IPAddress.TryParse(hostName, out IPAddress? address) &&
                 (address.AddressFamily != AddressFamily.InterNetworkV6 || SocketProtocolSupportPal.OSSupportsIPv6))
             {
                 try
@@ -441,7 +441,7 @@ namespace System.Net
             }
 
             // See if it's an IP Address.
-            if (IPAddress.TryParse(hostName, out IPAddress ipAddress))
+            if (IPAddress.TryParse(hostName, out IPAddress? ipAddress))
             {
                 if (throwOnIIPAny && (ipAddress.Equals(IPAddress.Any) || ipAddress.Equals(IPAddress.IPv6Any)))
                 {
index 1388a8b..5567e60 100644 (file)
@@ -208,7 +208,7 @@ namespace System.Net.NetworkInformation
                 throw new ArgumentNullException(nameof(hostNameOrAddress));
             }
 
-            if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address))
+            if (IPAddress.TryParse(hostNameOrAddress, out IPAddress? address))
             {
                 return Send(address, timeout, buffer, options);
             }
@@ -357,7 +357,7 @@ namespace System.Net.NetworkInformation
                 throw new ArgumentNullException(nameof(hostNameOrAddress));
             }
 
-            if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address))
+            if (IPAddress.TryParse(hostNameOrAddress, out IPAddress? address))
             {
                 return SendPingAsync(address, timeout, buffer, options);
             }
index 2bcad4d..b763e41 100644 (file)
@@ -21,24 +21,30 @@ namespace System.Net
     public sealed partial class Cookie
     {
         public Cookie() { }
-        public Cookie(string name, string value) { }
-        public Cookie(string name, string value, string path) { }
-        public Cookie(string name, string value, string path, string domain) { }
+        public Cookie(string name, string? value) { }
+        public Cookie(string name, string? value, string? path) { }
+        public Cookie(string name, string? value, string? path, string? domain) { }
+        [System.Diagnostics.CodeAnalysis.AllowNullAttribute]
         public string Comment { get { throw null; } set { } }
-        public System.Uri CommentUri { get { throw null; } set { } }
+        public System.Uri? CommentUri { get { throw null; } set { } }
         public bool Discard { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.AllowNullAttribute]
         public string Domain { get { throw null; } set { } }
         public bool Expired { get { throw null; } set { } }
         public System.DateTime Expires { get { throw null; } set { } }
         public bool HttpOnly { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.AllowNullAttribute]
         public string Name { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.AllowNullAttribute]
         public string Path { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.AllowNullAttribute]
         public string Port { get { throw null; } set { } }
         public bool Secure { get { throw null; } set { } }
         public System.DateTime TimeStamp { get { throw null; } }
+        [System.Diagnostics.CodeAnalysis.AllowNullAttribute]
         public string Value { get { throw null; } set { } }
         public int Version { get { throw null; } set { } }
-        public override bool Equals(object comparand) { throw null; }
+        public override bool Equals(object? comparand) { throw null; }
         public override int GetHashCode() { throw null; }
         public override string ToString() { throw null; }
     }
@@ -49,7 +55,7 @@ namespace System.Net
         public bool IsReadOnly { get { throw null; } }
         public bool IsSynchronized { get { throw null; } }
         public System.Net.Cookie this[int index] { get { throw null; } }
-        public System.Net.Cookie this[string name] { get { throw null; } }
+        public System.Net.Cookie? this[string name] { get { throw null; } }
         public object SyncRoot { get { throw null; } }
         public void Add(System.Net.Cookie cookie) { }
         public void Add(System.Net.CookieCollection cookies) { }
@@ -95,11 +101,11 @@ namespace System.Net
         public static System.Net.NetworkCredential DefaultNetworkCredentials { get { throw null; } }
         public void Add(string host, int port, string authenticationType, System.Net.NetworkCredential credential) { }
         public void Add(System.Uri uriPrefix, string authType, System.Net.NetworkCredential cred) { }
-        public System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType) { throw null; }
-        public System.Net.NetworkCredential GetCredential(System.Uri uriPrefix, string authType) { throw null; }
+        public System.Net.NetworkCredential? GetCredential(string host, int port, string authenticationType) { throw null; }
+        public System.Net.NetworkCredential? GetCredential(System.Uri uriPrefix, string authType) { throw null; }
         public System.Collections.IEnumerator GetEnumerator() { throw null; }
-        public void Remove(string host, int port, string authenticationType) { }
-        public void Remove(System.Uri uriPrefix, string authType) { }
+        public void Remove(string? host, int port, string? authenticationType) { }
+        public void Remove(System.Uri? uriPrefix, string? authType) { }
     }
     [System.FlagsAttribute]
     public enum DecompressionMethods
@@ -117,7 +123,7 @@ namespace System.Net
         public override System.Net.Sockets.AddressFamily AddressFamily { get { throw null; } }
         public string Host { get { throw null; } }
         public int Port { get { throw null; } }
-        public override bool Equals(object comparand) { throw null; }
+        public override bool Equals(object? comparand) { throw null; }
         public override int GetHashCode() { throw null; }
         public override string ToString() { throw null; }
     }
@@ -207,11 +213,11 @@ namespace System.Net
     }
     public partial interface ICredentials
     {
-        System.Net.NetworkCredential GetCredential(System.Uri uri, string authType);
+        System.Net.NetworkCredential? GetCredential(System.Uri uri, string authType);
     }
     public partial interface ICredentialsByHost
     {
-        System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType);
+        System.Net.NetworkCredential? GetCredential(string host, int port, string authenticationType);
     }
     public partial class IPAddress
     {
@@ -236,7 +242,7 @@ namespace System.Net
         public bool IsIPv6SiteLocal { get { throw null; } }
         public bool IsIPv6Teredo { get { throw null; } }
         public long ScopeId { get { throw null; } set { } }
-        public override bool Equals(object comparand) { throw null; }
+        public override bool Equals(object? comparand) { throw null; }
         public byte[] GetAddressBytes() { throw null; }
         public override int GetHashCode() { throw null; }
         public static short HostToNetworkOrder(short host) { throw null; }
@@ -252,8 +258,8 @@ namespace System.Net
         public static System.Net.IPAddress Parse(string ipString) { throw null; }
         public override string ToString() { throw null; }
         public bool TryFormat(System.Span<char> destination, out int charsWritten) { throw null; }
-        public static bool TryParse(System.ReadOnlySpan<char> ipString, out System.Net.IPAddress address) { throw null; }
-        public static bool TryParse(string ipString, out System.Net.IPAddress address) { throw null; }
+        public static bool TryParse(System.ReadOnlySpan<char> ipString, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out System.Net.IPAddress? address) { throw null; }
+        public static bool TryParse(string? ipString, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out System.Net.IPAddress? address) { throw null; }
         public bool TryWriteBytes(System.Span<byte> destination, out int bytesWritten) { throw null; }
     }
     public partial class IPEndPoint : System.Net.EndPoint
@@ -266,18 +272,18 @@ namespace System.Net
         public override System.Net.Sockets.AddressFamily AddressFamily { get { throw null; } }
         public int Port { get { throw null; } set { } }
         public override System.Net.EndPoint Create(System.Net.SocketAddress socketAddress) { throw null; }
-        public override bool Equals(object comparand) { throw null; }
+        public override bool Equals(object? comparand) { throw null; }
         public override int GetHashCode() { throw null; }
         public static System.Net.IPEndPoint Parse(System.ReadOnlySpan<char> s) { throw null; }
         public static System.Net.IPEndPoint Parse(string s) { throw null; }
         public override System.Net.SocketAddress Serialize() { throw null; }
         public override string ToString() { throw null; }
-        public static bool TryParse(System.ReadOnlySpan<char> s, out System.Net.IPEndPoint result) { throw null; }
-        public static bool TryParse(string s, out System.Net.IPEndPoint result) { throw null; }
+        public static bool TryParse(System.ReadOnlySpan<char> s, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out System.Net.IPEndPoint result) { throw null; }
+        public static bool TryParse(string s, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out System.Net.IPEndPoint? result) { throw null; }
     }
     public partial interface IWebProxy
     {
-        System.Net.ICredentials Credentials { get; set; }
+        System.Net.ICredentials? Credentials { get; set; }
         System.Uri GetProxy(System.Uri destination);
         bool IsBypassed(System.Uri host);
     }
@@ -285,18 +291,22 @@ namespace System.Net
     {
         public NetworkCredential() { }
         [System.CLSCompliantAttribute(false)]
-        public NetworkCredential(string userName, System.Security.SecureString password) { }
+        public NetworkCredential(string? userName, System.Security.SecureString? password) { }
         [System.CLSCompliantAttribute(false)]
-        public NetworkCredential(string userName, System.Security.SecureString password, string domain) { }
-        public NetworkCredential(string userName, string password) { }
-        public NetworkCredential(string userName, string password, string domain) { }
+        public NetworkCredential(string? userName, System.Security.SecureString? password, string? domain) { }
+        public NetworkCredential(string? userName, string? password) { }
+        public NetworkCredential(string? userName, string? password, string? domain) { }
+        [System.Diagnostics.CodeAnalysis.AllowNullAttribute]
         public string Domain { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.AllowNullAttribute]
         public string Password { get { throw null; } set { } }
         [System.CLSCompliantAttribute(false)]
+        [System.Diagnostics.CodeAnalysis.AllowNullAttribute]
         public System.Security.SecureString SecurePassword { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.AllowNullAttribute]
         public string UserName { get { throw null; } set { } }
-        public System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType) { throw null; }
-        public System.Net.NetworkCredential GetCredential(System.Uri uri, string authType) { throw null; }
+        public System.Net.NetworkCredential GetCredential(string? host, int port, string? authenticationType) { throw null; }
+        public System.Net.NetworkCredential GetCredential(System.Uri? uri, string? authType) { throw null; }
     }
     public partial class SocketAddress
     {
@@ -305,14 +315,14 @@ namespace System.Net
         public System.Net.Sockets.AddressFamily Family { get { throw null; } }
         public byte this[int offset] { get { throw null; } set { } }
         public int Size { get { throw null; } }
-        public override bool Equals(object comparand) { throw null; }
+        public override bool Equals(object? comparand) { throw null; }
         public override int GetHashCode() { throw null; }
         public override string ToString() { throw null; }
     }
     public abstract partial class TransportContext
     {
         protected TransportContext() { }
-        public abstract System.Security.Authentication.ExtendedProtection.ChannelBinding GetChannelBinding(System.Security.Authentication.ExtendedProtection.ChannelBindingKind kind);
+        public abstract System.Security.Authentication.ExtendedProtection.ChannelBinding? GetChannelBinding(System.Security.Authentication.ExtendedProtection.ChannelBindingKind kind);
     }
 }
 namespace System.Net.Cache
index 71067fb..da2cdd8 100644 (file)
@@ -1,6 +1,7 @@
 <Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="System.Net.Primitives.cs" />
index 48e6f77..4d6d641 100644 (file)
@@ -5,6 +5,7 @@
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <ILLinkKeepDepAttributes>false</ILLinkKeepDepAttributes> <!-- See comments in Cookie.cs -->
     <TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix</TargetFrameworks>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <PropertyGroup>
     <!-- SYSTEM_NET_PRIMITIVES_DLL is required to allow source-level code sharing for types defined within the
     <Reference Include="System.Security.Cryptography.Algorithms" />
     <Reference Include="System.Threading" />
   </ItemGroup>
-</Project>
\ No newline at end of file
+</Project>
index 1e080c0..87a5db6 100644 (file)
@@ -2,8 +2,10 @@
 // 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.Generic;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Globalization;
 using System.Runtime.CompilerServices;
 using System.Text;
@@ -46,7 +48,7 @@ namespace System.Net
         internal static readonly char[] ReservedToValue = new char[] { ';', ',' };
 
         private string m_comment = string.Empty; // Do not rename (binary serialization)
-        private Uri m_commentUri = null; // Do not rename (binary serialization)
+        private Uri? m_commentUri = null; // Do not rename (binary serialization)
         private CookieVariant m_cookieVariant = CookieVariant.Plain; // Do not rename (binary serialization)
         private bool m_discard = false; // Do not rename (binary serialization)
         private string m_domain = string.Empty; // Do not rename (binary serialization)
@@ -57,7 +59,7 @@ namespace System.Net
         private bool m_path_implicit = true; // Do not rename (binary serialization)
         private string m_port = string.Empty; // Do not rename (binary serialization)
         private bool m_port_implicit = true; // Do not rename (binary serialization)
-        private int[] m_port_list = null; // Do not rename (binary serialization)
+        private int[]? m_port_list = null; // Do not rename (binary serialization)
         private bool m_secure = false; // Do not rename (binary serialization)
         [System.Runtime.Serialization.OptionalField]
         private bool m_httpOnly = false; // Do not rename (binary serialization)
@@ -96,24 +98,25 @@ namespace System.Net
         }
 
         [PreserveDependency("ToServerString")] // Workaround for https://github.com/dotnet/runtime/issues/19348
-        public Cookie(string name, string value)
+        public Cookie(string name, string? value)
         {
             Name = name;
             Value = value;
         }
 
-        public Cookie(string name, string value, string path)
+        public Cookie(string name, string? value, string? path)
             : this(name, value)
         {
             Path = path;
         }
 
-        public Cookie(string name, string value, string path, string domain)
+        public Cookie(string name, string? value, string? path, string? domain)
             : this(name, value, path)
         {
             Domain = domain;
         }
 
+        [AllowNull]
         public string Comment
         {
             get
@@ -126,7 +129,7 @@ namespace System.Net
             }
         }
 
-        public Uri CommentUri
+        public Uri? CommentUri
         {
             get
             {
@@ -164,6 +167,7 @@ namespace System.Net
             }
         }
 
+        [AllowNull]
         public string Domain
         {
             get
@@ -231,7 +235,7 @@ namespace System.Net
                 }
             }
         }
-        internal bool InternalSetName(string value)
+        internal bool InternalSetName(string? value)
         {
             if (string.IsNullOrEmpty(value) || value[0] == '$' || value.IndexOfAny(ReservedToName) != -1 || value[0] == ' ' || value[value.Length - 1] == ' ')
             {
@@ -242,6 +246,7 @@ namespace System.Net
             return true;
         }
 
+        [AllowNull]
         public string Path
         {
             get
@@ -530,7 +535,7 @@ namespace System.Net
             {
                 // Port must match against the one from the uri.
                 valid = false;
-                foreach (int p in m_port_list)
+                foreach (int p in m_port_list!)
                 {
                     if (p == port)
                     {
@@ -573,6 +578,7 @@ namespace System.Net
             return true;
         }
 
+        [AllowNull]
         public string Port
         {
             get
@@ -627,7 +633,7 @@ namespace System.Net
         }
 
 
-        internal int[] PortList
+        internal int[]? PortList
         {
             get
             {
@@ -656,6 +662,7 @@ namespace System.Net
             }
         }
 
+        [AllowNull]
         public string Value
         {
             get
@@ -707,9 +714,9 @@ namespace System.Net
             }
         }
 
-        public override bool Equals(object comparand)
+        public override bool Equals(object? comparand)
         {
-            Cookie other = comparand as Cookie;
+            Cookie? other = comparand as Cookie;
 
             return other != null
                     && string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
@@ -787,7 +794,7 @@ namespace System.Net
             }
         }
 
-        internal string ToServerString()
+        internal string? ToServerString()
         {
             string result = Name + EqualsLiteral + Value;
             if (m_comment != null && m_comment.Length > 0)
index 71c580f..a82c271 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.Collections.Generic;
 using System.Runtime.Serialization;
@@ -41,17 +42,17 @@ namespace System.Net
                 {
                     throw new ArgumentOutOfRangeException(nameof(index));
                 }
-                return m_list[index] as Cookie;
+                return (m_list[index] as Cookie)!;
             }
         }
 
-        public Cookie this[string name]
+        public Cookie? this[string name]
         {
             get
             {
-                foreach (Cookie c in m_list)
+                foreach (Cookie? c in m_list)
                 {
-                    if (string.Equals(c.Name, name, StringComparison.OrdinalIgnoreCase))
+                    if (string.Equals(c!.Name, name, StringComparison.OrdinalIgnoreCase))
                     {
                         return c;
                     }
@@ -89,9 +90,9 @@ namespace System.Net
             {
                 throw new ArgumentNullException(nameof(cookies));
             }
-            foreach (Cookie cookie in cookies.m_list)
+            foreach (Cookie? cookie in cookies.m_list)
             {
-                Add(cookie);
+                Add(cookie!);
             }
         }
 
@@ -203,13 +204,13 @@ namespace System.Net
                 int listCount = m_list.Count;
                 for (int i = 0; i < listCount; i++)
                 {
-                    Cookie c = (Cookie)m_list[i];
+                    Cookie c = (Cookie)m_list[i]!;
                     if (CookieComparer.Compare(cookie, c) == 0)
                     {
                         ret = 0; // Will replace or reject
 
                         // Cookie2 spec requires that new Variant cookie overwrite the old one.
-                        if (c.Variant <= cookie.Variant)
+                        if (c!.Variant <= cookie.Variant)
                         {
                             m_list[idx] = cookie;
                         }
@@ -236,9 +237,9 @@ namespace System.Net
         internal int IndexOf(Cookie cookie)
         {
             int idx = 0;
-            foreach (Cookie c in m_list)
+            foreach (Cookie? c in m_list)
             {
-                if (CookieComparer.Compare(cookie, c) == 0)
+                if (CookieComparer.Compare(cookie, c!) == 0)
                 {
                     return idx;
                 }
@@ -254,9 +255,9 @@ namespace System.Net
 
         IEnumerator<Cookie> IEnumerable<Cookie>.GetEnumerator()
         {
-            foreach (Cookie cookie in m_list)
+            foreach (Cookie? cookie in m_list)
             {
-                yield return cookie;
+                yield return cookie!;
             }
         }
 
index c04d15a..75f68bb 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.Collections.Generic;
 using System.Diagnostics;
@@ -232,7 +233,7 @@ namespace System.Net
                     nameof(cookie) + "." + nameof(cookie.Domain));
             }
 
-            Uri uri;
+            Uri? uri;
             var uriSb = new StringBuilder();
 
             // We cannot add an invalid cookie into the container.
@@ -273,7 +274,7 @@ namespace System.Net
         // Add(Cookie cookie) the cookie is in a reasonable condition.
         internal void Add(Cookie cookie, bool throwOnError)
         {
-            PathList pathList;
+            PathList? pathList;
 
             if (cookie.Value.Length > m_maxCookieSize)
             {
@@ -288,7 +289,7 @@ namespace System.Net
             {
                 lock (m_domainTable.SyncRoot)
                 {
-                    pathList = (PathList)m_domainTable[cookie.DomainKey];
+                    pathList = (PathList?)m_domainTable[cookie.DomainKey];
                     if (pathList == null)
                     {
                         m_domainTable[cookie.DomainKey] = (pathList = new PathList());
@@ -296,10 +297,10 @@ namespace System.Net
                 }
                 int domain_count = pathList.GetCookiesCount();
 
-                CookieCollection cookies;
+                CookieCollection? cookies;
                 lock (pathList.SyncRoot)
                 {
-                    cookies = (CookieCollection)pathList[cookie.Path];
+                    cookies = (CookieCollection?)pathList[cookie.Path]!;
 
                     if (cookies == null)
                     {
@@ -368,7 +369,7 @@ namespace System.Net
         // (this.GetCookies method).
         //
         // Param. 'domain' == null means to age in the whole container.
-        private bool AgeCookies(string domain)
+        private bool AgeCookies(string? domain)
         {
             Debug.Assert(m_maxCookies != 0);
             Debug.Assert(m_maxCookiesPerDomain != 0);
@@ -377,9 +378,9 @@ namespace System.Net
             DateTime oldUsed = DateTime.MaxValue;
             DateTime tempUsed;
 
-            CookieCollection lruCc = null;
-            string lruDomain = null;
-            string tempDomain = null;
+            CookieCollection? lruCc = null;
+            string? lruDomain = null;
+            string tempDomain;
 
             PathList pathList;
             int domain_count = 0;
@@ -395,24 +396,26 @@ namespace System.Net
             }
             lock (m_domainTable.SyncRoot)
             {
-                foreach (DictionaryEntry entry in m_domainTable)
+                foreach (object? item in m_domainTable)
                 {
+                    DictionaryEntry entry = (DictionaryEntry)item!;
                     if (domain == null)
                     {
                         tempDomain = (string)entry.Key;
-                        pathList = (PathList)entry.Value; // Aliasing to trick foreach
+                        pathList = (PathList)entry.Value!; // Aliasing to trick foreach
                     }
                     else
                     {
                         tempDomain = domain;
-                        pathList = (PathList)m_domainTable[domain];
+                        pathList = (PathList)m_domainTable[domain]!;
                     }
 
                     domain_count = 0; // Cookies in the domain
                     lock (pathList.SyncRoot)
                     {
-                        foreach (CookieCollection cc in pathList.Values)
+                        foreach (CookieCollection? cc in pathList.Values)
                         {
+                            Debug.Assert(cc != null);
                             itemp = ExpireCollection(cc);
                             removed += itemp;
                             m_count -= itemp; // Update this container's count
@@ -440,9 +443,9 @@ namespace System.Net
                         {
                             cookies = Array.CreateInstance(typeof(CookieCollection), pathList.Count);
                             stamps = Array.CreateInstance(typeof(DateTime), pathList.Count);
-                            foreach (CookieCollection cc in pathList.Values)
+                            foreach (CookieCollection? cc in pathList.Values)
                             {
-                                stamps.SetValue(cc.TimeStamp(CookieCollection.Stamp.Check), itemp);
+                                stamps.SetValue(cc!.TimeStamp(CookieCollection.Stamp.Check), itemp);
                                 cookies.SetValue(cc, itemp);
                                 ++itemp;
                             }
@@ -452,7 +455,7 @@ namespace System.Net
                         itemp = 0;
                         for (int i = 0; i < cookies.Length; ++i)
                         {
-                            CookieCollection cc = (CookieCollection)cookies.GetValue(i);
+                            CookieCollection cc = (CookieCollection)cookies.GetValue(i)!;
 
                             lock (cc)
                             {
@@ -501,7 +504,7 @@ namespace System.Net
             }
 
             // Remove oldest cookies from the least used collection.
-            lock (lruCc)
+            lock (lruCc!)
             {
                 while (m_count >= m_maxCookies && lruCc.Count > 0)
                 {
@@ -527,14 +530,14 @@ namespace System.Net
                 while (enumerator.MoveNext())
                 {
                     currentDomain = (string)enumerator.Key;
-                    pathList = (PathList)enumerator.Value;
+                    pathList = (PathList)enumerator.Value!;
 
                     lock (pathList.SyncRoot)
                     {
                         IDictionaryEnumerator e = pathList.GetEnumerator();
                         while (e.MoveNext())
                         {
-                            CookieCollection cc = (CookieCollection)e.Value;
+                            CookieCollection cc = (CookieCollection)e.Value!;
                             if (cc.Count == 0)
                             {
                                 removePathList.Add(e.Key);
@@ -586,7 +589,7 @@ namespace System.Net
             {
                 throw new ArgumentNullException(nameof(cookies));
             }
-            foreach (Cookie c in cookies)
+            foreach (Cookie c in (ICollection<Cookie>)cookies)
             {
                 Add(c);
             }
@@ -688,15 +691,15 @@ namespace System.Net
             }
 
             bool isLocalDomain = IsLocalDomain(uri.Host);
-            foreach (Cookie c in cookies)
+            foreach (Cookie? c in cookies)
             {
-                Cookie new_cookie = c.Clone();
+                Cookie new_cookie = c!.Clone();
                 new_cookie.VerifySetDefaults(new_cookie.Variant, uri, isLocalDomain, m_fqdnMyDomain, true, true);
                 Add(new_cookie, true);
             }
         }
 
-        internal CookieCollection CookieCutter(Uri uri, string headerName, string setCookieHeader, bool isThrow)
+        internal CookieCollection CookieCutter(Uri uri, string? headerName, string setCookieHeader, bool isThrow)
         {
             if (NetEventSource.IsEnabled)
             {
@@ -726,7 +729,7 @@ namespace System.Net
                 CookieParser parser = new CookieParser(setCookieHeader);
                 do
                 {
-                    Cookie cookie = parser.Get();
+                    Cookie? cookie = parser.Get();
                     if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CookieParser returned cookie:{cookie}");
 
                     if (cookie == null)
@@ -790,7 +793,7 @@ namespace System.Net
             return InternalGetCookies(uri) ?? new CookieCollection();
         }
 
-        internal CookieCollection InternalGetCookies(Uri uri)
+        internal CookieCollection? InternalGetCookies(Uri uri)
         {
             if (m_count == 0)
             {
@@ -799,10 +802,10 @@ namespace System.Net
 
             bool isSecure = (uri.Scheme == UriScheme.Https || uri.Scheme == UriScheme.Wss);
             int port = uri.Port;
-            CookieCollection cookies = null;
+            CookieCollection? cookies = null;
 
             var domainAttributeMatchAnyCookieVariant = new System.Collections.Generic.List<string>();
-            System.Collections.Generic.List<string> domainAttributeMatchOnlyCookieVariantPlain = null;
+            System.Collections.Generic.List<string>? domainAttributeMatchOnlyCookieVariantPlain = null;
 
             string fqdnRemote = uri.Host;
 
@@ -865,14 +868,14 @@ namespace System.Net
             return cookies;
         }
 
-        private void BuildCookieCollectionFromDomainMatches(Uri uri, bool isSecure, int port, ref CookieCollection cookies, System.Collections.Generic.List<string> domainAttribute, bool matchOnlyPlainCookie)
+        private void BuildCookieCollectionFromDomainMatches(Uri uri, bool isSecure, int port, ref CookieCollection? cookies, System.Collections.Generic.List<string> domainAttribute, bool matchOnlyPlainCookie)
         {
             for (int i = 0; i < domainAttribute.Count; i++)
             {
                 PathList pathList;
                 lock (m_domainTable.SyncRoot)
                 {
-                    pathList = (PathList)m_domainTable[domainAttribute[i]];
+                    pathList = (PathList)m_domainTable[domainAttribute[i]]!;
                     if (pathList == null)
                     {
                         continue;
@@ -888,7 +891,7 @@ namespace System.Net
                         string path = (string)list.GetKey(e);
                         if (uri.AbsolutePath.StartsWith(CookieParser.CheckQuoted(path), StringComparison.Ordinal))
                         {
-                            CookieCollection cc = (CookieCollection)list.GetByIndex(e);
+                            CookieCollection cc = (CookieCollection)list.GetByIndex(e)!;
                             cc.TimeStamp(CookieCollection.Stamp.Set);
                             MergeUpdateCollections(ref cookies, cc, port, isSecure, matchOnlyPlainCookie);
                         }
@@ -906,7 +909,7 @@ namespace System.Net
             }
         }
 
-        private void MergeUpdateCollections(ref CookieCollection destination, CookieCollection source, int port, bool isSecure, bool isPlainOnly)
+        private void MergeUpdateCollections(ref CookieCollection? destination, CookieCollection source, int port, bool isSecure, bool isPlainOnly)
         {
             lock (source)
             {
@@ -984,7 +987,7 @@ namespace System.Net
 
         internal string GetCookieHeader(Uri uri, out string optCookie2)
         {
-            CookieCollection cookies = InternalGetCookies(uri);
+            CookieCollection? cookies = InternalGetCookies(uri);
             if (cookies == null)
             {
                 optCookie2 = string.Empty;
@@ -1046,7 +1049,7 @@ namespace System.Net
                 int listCount = list.Count;
                 for (int i = 0; i < listCount; i++)
                 {
-                    count += ((CookieCollection)list[i]).Count;
+                    count += ((CookieCollection)list[i]!).Count;
                 }
             }
             return count;
@@ -1060,7 +1063,7 @@ namespace System.Net
             }
         }
 
-        internal object this[string s]
+        internal object? this[string s]
         {
             get
             {
@@ -1105,10 +1108,10 @@ namespace System.Net
         {
             internal static readonly PathListComparer StaticInstance = new PathListComparer();
 
-            int IComparer.Compare(object ol, object or)
+            int IComparer.Compare(object? ol, object? or)
             {
-                string pathLeft = CookieParser.CheckQuoted((string)ol);
-                string pathRight = CookieParser.CheckQuoted((string)or);
+                string pathLeft = CookieParser.CheckQuoted((string)ol!);
+                string pathRight = CookieParser.CheckQuoted((string)or!);
                 int ll = pathLeft.Length;
                 int lr = pathRight.Length;
                 int length = Math.Min(ll, lr);
index bd2b906..fb464f7 100644 (file)
@@ -14,11 +14,11 @@ namespace System.Net
         {
         }
 
-        internal CookieException(string message) : base(message)
+        internal CookieException(string? message) : base(message)
         {
         }
 
-        internal CookieException(string message, Exception inner) : base(message, inner)
+        internal CookieException(string? message, Exception? inner) : base(message, inner)
         {
         }
 
index 707131b..aeee904 100644 (file)
@@ -13,8 +13,8 @@ namespace System.Net
     // name-password pairs and associates these with host/realm.
     public class CredentialCache : ICredentials, ICredentialsByHost, IEnumerable
     {
-        private Dictionary<CredentialKey, NetworkCredential> _cache;
-        private Dictionary<CredentialHostKey, NetworkCredential> _cacheForHosts;
+        private Dictionary<CredentialKey, NetworkCredential>? _cache;
+        private Dictionary<CredentialHostKey, NetworkCredential>? _cacheForHosts;
         private int _version;
 
         public CredentialCache()
@@ -100,7 +100,7 @@ namespace System.Net
             _cacheForHosts.Add(key, credential);
         }
 
-        public void Remove(Uri uriPrefix, string authType)
+        public void Remove(Uri? uriPrefix, string? authType)
         {
             if (uriPrefix == null || authType == null)
             {
@@ -124,7 +124,7 @@ namespace System.Net
             _cache.Remove(key);
         }
 
-        public void Remove(string host, int port, string authenticationType)
+        public void Remove(string? host, int port, string? authenticationType)
         {
             if (host == null || authenticationType == null)
             {
@@ -153,7 +153,7 @@ namespace System.Net
             _cacheForHosts.Remove(key);
         }
 
-        public NetworkCredential GetCredential(Uri uriPrefix, string authType)
+        public NetworkCredential? GetCredential(Uri uriPrefix, string authType)
         {
             if (uriPrefix == null)
             {
@@ -173,7 +173,7 @@ namespace System.Net
             }
 
             int longestMatchPrefix = -1;
-            NetworkCredential mostSpecificMatch = null;
+            NetworkCredential? mostSpecificMatch = null;
 
             // Enumerate through every credential in the cache
             foreach (KeyValuePair<CredentialKey, NetworkCredential> pair in _cache)
@@ -200,7 +200,7 @@ namespace System.Net
             return mostSpecificMatch;
         }
 
-        public NetworkCredential GetCredential(string host, int port, string authenticationType)
+        public NetworkCredential? GetCredential(string host, int port, string authenticationType)
         {
             if (host == null)
             {
@@ -229,7 +229,7 @@ namespace System.Net
 
             var key = new CredentialHostKey(host, port, authenticationType);
 
-            NetworkCredential match = null;
+            NetworkCredential? match = null;
             _cacheForHosts.TryGetValue(key, out match);
 
             if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Returning {((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")")}");
@@ -266,7 +266,7 @@ namespace System.Net
             private readonly CredentialCache _cache;
             private readonly int _version;
             private bool _enumerating;
-            private NetworkCredential _current;
+            private NetworkCredential? _current;
 
             private CredentialEnumerator(CredentialCache cache)
             {
@@ -289,7 +289,7 @@ namespace System.Net
                         throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
                     }
 
-                    return _current;
+                    return _current!;
                 }
             }
 
@@ -303,7 +303,7 @@ namespace System.Net
                 return _enumerating = MoveNext(out _current);
             }
 
-            protected virtual bool MoveNext(out NetworkCredential current)
+            protected virtual bool MoveNext(out NetworkCredential? current)
             {
                 current = null;
                 return false;
@@ -314,7 +314,7 @@ namespace System.Net
                 _enumerating = false;
             }
 
-            private class SingleTableCredentialEnumerator<TKey> : CredentialEnumerator
+            private class SingleTableCredentialEnumerator<TKey> : CredentialEnumerator where TKey : notnull
             {
                 private Dictionary<TKey, NetworkCredential>.ValueCollection.Enumerator _enumerator; // mutable struct field deliberately not readonly.
 
@@ -343,7 +343,7 @@ namespace System.Net
                 private Dictionary<CredentialHostKey, NetworkCredential>.ValueCollection.Enumerator _enumerator; // mutable struct field deliberately not readonly.
                 private bool _onThisEnumerator;
 
-                public DoubleTableCredentialEnumerator(CredentialCache cache) : base(cache, cache._cache)
+                public DoubleTableCredentialEnumerator(CredentialCache cache) : base(cache, cache._cache!)
                 {
                     Debug.Assert(cache._cacheForHosts != null);
 
@@ -380,7 +380,7 @@ namespace System.Net
 
             private static class DictionaryEnumeratorHelper
             {
-                internal static bool MoveNext<TKey, TValue>(ref Dictionary<TKey, TValue>.ValueCollection.Enumerator enumerator, out TValue current)
+                internal static bool MoveNext<TKey, TValue>(ref Dictionary<TKey, TValue>.ValueCollection.Enumerator enumerator, out TValue current) where TKey : notnull
                 {
                     bool result = enumerator.MoveNext();
                     current = enumerator.Current;
@@ -452,14 +452,14 @@ namespace System.Net
             return equals;
         }
 
-        public override bool Equals(object obj) =>
+        public override bool Equals(object? obj) =>
             obj is CredentialHostKey && Equals((CredentialHostKey)obj);
 
         public override string ToString() =>
             Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + AuthenticationType;
     }
 
-    internal sealed class CredentialKey : IEquatable<CredentialKey>
+    internal sealed class CredentialKey : IEquatable<CredentialKey?>
     {
         public readonly Uri UriPrefix;
         public readonly int UriPrefixLength = -1;
@@ -528,7 +528,7 @@ namespace System.Net
             StringComparer.OrdinalIgnoreCase.GetHashCode(AuthenticationType) ^
             UriPrefix.GetHashCode();
 
-        public bool Equals(CredentialKey other)
+        public bool Equals(CredentialKey? other)
         {
             if (other == null)
             {
@@ -544,7 +544,7 @@ namespace System.Net
             return equals;
         }
 
-        public override bool Equals(object obj) => Equals(obj as CredentialKey);
+        public override bool Equals(object? obj) => Equals(obj as CredentialKey);
 
         public override string ToString() =>
             "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + UriPrefix + ":" + AuthenticationType;
index 36df633..581a585 100644 (file)
@@ -43,9 +43,9 @@ namespace System.Net
             _family = addressFamily;
         }
 
-        public override bool Equals(object comparand)
+        public override bool Equals(object? comparand)
         {
-            DnsEndPoint dnsComparand = comparand as DnsEndPoint;
+            DnsEndPoint? dnsComparand = comparand as DnsEndPoint;
 
             if (dnsComparand == null)
             {
index 76fc759..8bdbf70 100644 (file)
@@ -20,6 +20,6 @@ namespace System.Net
         ///     is available for the specified host and realm.
         ///   </para>
         /// </devdoc>
-        NetworkCredential GetCredential(Uri uri, string authType);
+        NetworkCredential? GetCredential(Uri uri, string authType);
     }
 }
index 2cd04cc..04da831 100644 (file)
@@ -20,6 +20,6 @@ namespace System.Net
         ///     is available for the specified host and realm.
         ///   </para>
         /// </devdoc>
-        NetworkCredential GetCredential(string host, int port, string authenticationType);
+        NetworkCredential? GetCredential(string host, int port, string authenticationType);
     }
 }
index 083128a..1d70c5e 100644 (file)
@@ -2,8 +2,10 @@
 // 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.Buffers.Binary;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Net.Sockets;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
@@ -40,12 +42,12 @@ namespace System.Net
         /// <summary>
         /// This field is only used for IPv6 addresses. A null value indicates that this instance is an IPv4 address.
         /// </summary>
-        private readonly ushort[] _numbers;
+        private readonly ushort[]? _numbers;
 
         /// <summary>
         /// A lazily initialized cache of the result of calling <see cref="ToString"/>.
         /// </summary>
-        private string _toString;
+        private string? _toString;
 
         /// <summary>
         /// A lazily initialized cache of the <see cref="GetHashCode"/> value.
@@ -213,7 +215,7 @@ namespace System.Net
         ///     Converts an IP address string to an <see cref='System.Net.IPAddress'/> instance.
         ///   </para>
         /// </devdoc>
-        public static bool TryParse(string ipString, out IPAddress address)
+        public static bool TryParse(string? ipString, [NotNullWhen(true)] out IPAddress? address)
         {
             if (ipString == null)
             {
@@ -225,7 +227,7 @@ namespace System.Net
             return (address != null);
         }
 
-        public static bool TryParse(ReadOnlySpan<char> ipSpan, out IPAddress address)
+        public static bool TryParse(ReadOnlySpan<char> ipSpan, [NotNullWhen(true)] out IPAddress? address)
         {
             address = IPAddressParser.Parse(ipSpan, tryParse: true);
             return (address != null);
@@ -238,12 +240,12 @@ namespace System.Net
                 throw new ArgumentNullException(nameof(ipString));
             }
 
-            return IPAddressParser.Parse(ipString.AsSpan(), tryParse: false);
+            return IPAddressParser.Parse(ipString.AsSpan(), tryParse: false)!;
         }
 
         public static IPAddress Parse(ReadOnlySpan<char> ipSpan)
         {
-            return IPAddressParser.Parse(ipSpan, tryParse: false);
+            return IPAddressParser.Parse(ipSpan, tryParse: false)!;
         }
 
         public bool TryWriteBytes(Span<byte> destination, out int bytesWritten)
@@ -374,7 +376,7 @@ namespace System.Net
             {
                 _toString = IsIPv4 ?
                     IPAddressParser.IPv4AddressToString(PrivateAddress) :
-                    IPAddressParser.IPv6AddressToString(_numbers, PrivateScopeId);
+                    IPAddressParser.IPv6AddressToString(_numbers!, PrivateScopeId);
             }
 
             return _toString;
@@ -384,7 +386,7 @@ namespace System.Net
         {
             return IsIPv4 ?
                 IPAddressParser.IPv4AddressToString(PrivateAddress, destination, out charsWritten) :
-                IPAddressParser.IPv6AddressToString(_numbers, PrivateScopeId, destination, out charsWritten);
+                IPAddressParser.IPv6AddressToString(_numbers!, PrivateScopeId, destination, out charsWritten);
         }
 
         public static long HostToNetworkOrder(long host)
@@ -444,7 +446,7 @@ namespace System.Net
         {
             get
             {
-                return IsIPv6 && ((_numbers[0] & 0xFF00) == 0xFF00);
+                return IsIPv6 && ((_numbers![0] & 0xFF00) == 0xFF00);
             }
         }
 
@@ -457,7 +459,7 @@ namespace System.Net
         {
             get
             {
-                return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFE80);
+                return IsIPv6 && ((_numbers![0] & 0xFFC0) == 0xFE80);
             }
         }
 
@@ -470,7 +472,7 @@ namespace System.Net
         {
             get
             {
-                return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFEC0);
+                return IsIPv6 && ((_numbers![0] & 0xFFC0) == 0xFEC0);
             }
         }
 
@@ -479,8 +481,8 @@ namespace System.Net
             get
             {
                 return IsIPv6 &&
-                       (_numbers[0] == 0x2001) &&
-                       (_numbers[1] == 0);
+                       (_numbers![0] == 0x2001) &&
+                       (_numbers![1] == 0);
             }
         }
 
@@ -495,12 +497,12 @@ namespace System.Net
                 }
                 for (int i = 0; i < 5; i++)
                 {
-                    if (_numbers[i] != 0)
+                    if (_numbers![i] != 0)
                     {
                         return false;
                     }
                 }
-                return (_numbers[5] == 0xFFFF);
+                return (_numbers![5] == 0xFFFF);
             }
         }
 
@@ -545,7 +547,7 @@ namespace System.Net
         }
 
         /// <summary>Compares two IP addresses.</summary>
-        public override bool Equals(object comparand)
+        public override bool Equals(object? comparand)
         {
             return comparand is IPAddress address && Equals(address);
         }
@@ -642,12 +644,13 @@ namespace System.Net
             // Cast the ushort values to a uint and mask with unsigned literal before bit shifting.
             // Otherwise, we can end up getting a negative value for any IPv4 address that ends with
             // a byte higher than 127 due to sign extension of the most significant 1 bit.
-            long address = ((((uint)_numbers[6] & 0x0000FF00u) >> 8) | (((uint)_numbers[6] & 0x000000FFu) << 8)) |
+            long address = ((((uint)_numbers![6] & 0x0000FF00u) >> 8) | (((uint)_numbers[6] & 0x000000FFu) << 8)) |
                     (((((uint)_numbers[7] & 0x0000FF00u) >> 8) | (((uint)_numbers[7] & 0x000000FFu) << 8)) << 16);
 
             return new IPAddress(address);
         }
 
+        [DoesNotReturn]
         private static byte[] ThrowAddressNullException() => throw new ArgumentNullException("address");
 
         private sealed class ReadOnlyIPAddress : IPAddress
index 2e53dfa..78b0032 100644 (file)
@@ -2,7 +2,9 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.IO;
 using System.Net.Sockets;
 using System.Runtime.InteropServices;
@@ -16,7 +18,7 @@ namespace System.Net
     {
         private const int MaxIPv4StringLength = 15; // 4 numbers separated by 3 periods, with up to 3 digits per number
 
-        internal static IPAddress Parse(ReadOnlySpan<char> ipSpan, bool tryParse)
+        internal static IPAddress? Parse(ReadOnlySpan<char> ipSpan, bool tryParse)
         {
             if (ipSpan.Contains(':'))
             {
@@ -209,7 +211,7 @@ namespace System.Net
             }
             if (isValid || (end != ipSpan.Length))
             {
-                string scopeId = null;
+                string? scopeId = null;
                 IPv6AddressHelper.Parse(ipSpan, numbers, 0, ref scopeId);
 
                 if (scopeId?.Length > 1)
index eb43fb4..2e52b1a 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
+using System.Diagnostics.CodeAnalysis;
 using System.Globalization;
 using System.Net.Sockets;
 
@@ -85,12 +87,12 @@ namespace System.Net
             }
         }
 
-        public static bool TryParse(string s, out IPEndPoint result)
+        public static bool TryParse(string s, [NotNullWhen(true)] out IPEndPoint? result)
         {
             return TryParse(s.AsSpan(), out result);
         }
 
-        public static bool TryParse(ReadOnlySpan<char> s, out IPEndPoint result)
+        public static bool TryParse(ReadOnlySpan<char> s, [NotNullWhen(true)] out IPEndPoint? result)
         {
             int addressLength = s.Length;  // If there's no port then send the entire string to the address parser
             int lastColonPos = s.LastIndexOf(':');
@@ -109,7 +111,7 @@ namespace System.Net
                 }
             }
 
-            if (IPAddress.TryParse(s.Slice(0, addressLength), out IPAddress address))
+            if (IPAddress.TryParse(s.Slice(0, addressLength), out IPAddress? address))
             {
                 uint port = 0;
                 if (addressLength == s.Length ||
@@ -137,7 +139,7 @@ namespace System.Net
 
         public static IPEndPoint Parse(ReadOnlySpan<char> s)
         {
-            if (TryParse(s, out IPEndPoint result))
+            if (TryParse(s, out IPEndPoint? result))
             {
                 return result;
             }
@@ -173,7 +175,7 @@ namespace System.Net
             return socketAddress.GetIPEndPoint();
         }
 
-        public override bool Equals(object comparand)
+        public override bool Equals(object? comparand)
         {
             return comparand is IPEndPoint other && other._address.Equals(_address) && other._port == _port;
         }
index eace53a..e9bc4d9 100644 (file)
@@ -14,6 +14,6 @@ namespace System.Net
     {
         Uri GetProxy(Uri destination);
         bool IsBypassed(Uri host);
-        ICredentials Credentials { get; set; }
+        ICredentials? Credentials { get; set; }
     }
 }
index 2ea800c..04186f2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Diagnostics.CodeAnalysis;
 using System.Runtime.InteropServices;
 using System.Security;
 
@@ -15,9 +16,9 @@ namespace System.Net
     /// </devdoc>
     public class NetworkCredential : ICredentials, ICredentialsByHost
     {
-        private string _domain;
-        private string _userName;
-        private object _password;
+        private string _domain = null!;
+        private string _userName = string.Empty;
+        private object? _password;
 
         public NetworkCredential()
             : this(string.Empty, string.Empty, string.Empty)
@@ -30,7 +31,7 @@ namespace System.Net
         ///       class with name and password set as specified.
         ///    </para>
         /// </devdoc>
-        public NetworkCredential(string userName, string password)
+        public NetworkCredential(string? userName, string? password)
         : this(userName, password, string.Empty)
         {
         }
@@ -41,7 +42,7 @@ namespace System.Net
         ///       class with name, password and domain set as specified.
         ///    </para>
         /// </devdoc>
-        public NetworkCredential(string userName, string password, string domain)
+        public NetworkCredential(string? userName, string? password, string? domain)
         {
             UserName = userName;
             Password = password;
@@ -49,13 +50,13 @@ namespace System.Net
         }
 
         [CLSCompliant(false)]
-        public NetworkCredential(string userName, SecureString password)
+        public NetworkCredential(string? userName, SecureString? password)
         : this(userName, password, string.Empty)
         {
         }
 
         [CLSCompliant(false)]
-        public NetworkCredential(string userName, SecureString password, string domain)
+        public NetworkCredential(string? userName, SecureString? password, string? domain)
         {
             UserName = userName;
             SecurePassword = password;
@@ -67,6 +68,7 @@ namespace System.Net
         ///       The user name associated with this credential.
         ///    </para>
         /// </devdoc>
+        [AllowNull]
         public string UserName
         {
             get { return _userName; }
@@ -78,41 +80,43 @@ namespace System.Net
         ///       The password for the user name.
         ///    </para>
         /// </devdoc>
+        [AllowNull]
         public string Password
         {
             get
             {
-                SecureString sstr = _password as SecureString;
+                SecureString? sstr = _password as SecureString;
                 if (sstr != null)
                 {
                     return MarshalToString(sstr);
                 }
-                return (string)_password ?? string.Empty;
+                return (string?)_password ?? string.Empty;
             }
             set
             {
-                SecureString old = _password as SecureString;
+                SecureString? old = _password as SecureString;
                 _password = value;
                 old?.Dispose();
             }
         }
 
         [CLSCompliant(false)]
+        [AllowNull]
         public SecureString SecurePassword
         {
             get
             {
-                string str = _password as string;
+                string? str = _password as string;
                 if (str != null)
                 {
                     return MarshalToSecureString(str);
                 }
-                SecureString sstr = _password as SecureString;
+                SecureString? sstr = _password as SecureString;
                 return sstr != null ? sstr.Copy() : new SecureString();
             }
             set
             {
-                SecureString old = _password as SecureString;
+                SecureString? old = _password as SecureString;
                 _password = value?.Copy();
                 old?.Dispose();
             }
@@ -124,6 +128,7 @@ namespace System.Net
         ///       the credentials. Usually this is the host machine.
         ///    </para>
         /// </devdoc>
+        [AllowNull]
         public string Domain
         {
             get { return _domain; }
@@ -136,12 +141,12 @@ namespace System.Net
         ///       authentication type.
         ///    </para>
         /// </devdoc>
-        public NetworkCredential GetCredential(Uri uri, string authenticationType)
+        public NetworkCredential GetCredential(Uri? uri, string? authenticationType)
         {
             return this;
         }
 
-        public NetworkCredential GetCredential(string host, int port, string authenticationType)
+        public NetworkCredential GetCredential(string? host, int port, string? authenticationType)
         {
             return this;
         }
@@ -158,7 +163,7 @@ namespace System.Net
             try
             {
                 ptr = Marshal.SecureStringToGlobalAllocUnicode(sstr);
-                result = Marshal.PtrToStringUni(ptr);
+                result = Marshal.PtrToStringUni(ptr)!;
             }
             finally
             {
index bbe6c79..affb12a 100644 (file)
@@ -8,6 +8,6 @@ namespace System.Net
 {
     public abstract class TransportContext
     {
-        public abstract ChannelBinding GetChannelBinding(ChannelBindingKind kind);
+        public abstract ChannelBinding? GetChannelBinding(ChannelBindingKind kind);
     }
 }
index ae7f2ac..1cdc4f7 100644 (file)
@@ -176,7 +176,7 @@ namespace System.Net
             {
                 try
                 {
-                    Uri proxyAddress = proxy.GetProxy(address);
+                    Uri? proxyAddress = proxy.GetProxy(address);
                     if (proxyAddress != null)
                     {
                         if (proxyAddress.Scheme != Uri.UriSchemeHttp)