Annotate System.Net.Sockets for nullable reference types (#32675)
authorEric Erhardt <eric.erhardt@microsoft.com>
Thu, 27 Feb 2020 03:19:18 +0000 (21:19 -0600)
committerGitHub <noreply@github.com>
Thu, 27 Feb 2020 03:19:18 +0000 (21:19 -0600)
* All AsyncResult classes have nullable enable.

* Most ancillary files annotated.

* UdpClient annotated

* Annotate TcpClient

* Annotate TcpListener, SafeSocketHandle, SocketTaskExtensions

* Annotate NetworkStream and SendPacketsElement

* Annotate SocketPal.

* Annotate SocketAsyncEventArgs

* Annotate SocketAsyncEngine and Context on Unix

* Annotate Socket.Tasks

* Finish annotating the Socket class.

* Remove inline #nullable lines

* Annotate all public methods.

* Sync up to latest code and cleanup.

* Fix .NET Framework build for WinHttpHandler.

58 files changed:
src/libraries/Common/src/Interop/Windows/WinSock/Interop.TransmitFile.cs
src/libraries/Common/src/Interop/Windows/WinSock/Interop.WSAIoctl.cs
src/libraries/Common/src/Interop/Windows/WinSock/Interop.setsockopt.cs
src/libraries/Common/src/Interop/Windows/WinSock/SafeNativeOverlapped.cs
src/libraries/Common/src/System/Net/ContextAwareResult.Windows.cs
src/libraries/Common/src/System/Net/ContextAwareResult.cs
src/libraries/Common/src/System/Net/DebugSafeHandleMinusOneIsInvalid.cs
src/libraries/Common/src/System/Net/Internals/SocketExceptionFactory.cs
src/libraries/Common/src/System/Net/LazyAsyncResult.cs
src/libraries/Common/src/System/Net/Logging/NetEventSource.Common.cs
src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Unix.cs
src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs
src/libraries/System.Net.Sockets/ref/System.Net.Sockets.cs
src/libraries/System.Net.Sockets/ref/System.Net.Sockets.csproj
src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj
src/libraries/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Unix.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/AcceptOverlappedAsyncResult.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Unix.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/ConnectOverlappedAsyncResult.Unix.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/ConnectOverlappedAsyncResult.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/ConnectOverlappedAsyncResult.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/DisconnectOverlappedAsyncResult.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/DynamicWinsockMethods.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/IOControlKeepAlive.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/IPPacketInformation.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/MulticastOption.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/MultipleConnectAsync.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetEventSource.Sockets.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Unix.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/OverlappedAsyncResult.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/ReceiveMessageOverlappedAsyncResult.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Unix.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Unix.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEngine.Unix.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketTaskExtensions.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/TransmitFileAsyncResult.Windows.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/UdpReceiveResult.cs
src/libraries/System.Net.Sockets/tests/FunctionalTests/DisconnectTest.cs

index e9cffa9..d11bdfb 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.Net.Sockets;
 using System.Runtime.InteropServices;
@@ -14,7 +15,7 @@ internal static partial class Interop
         [DllImport(Interop.Libraries.Mswsock, SetLastError = true)]
         internal static extern unsafe bool TransmitFile(
             SafeHandle socket,
-            SafeHandle fileHandle,
+            SafeHandle? fileHandle,
             int numberOfBytesToWrite,
             int numberOfBytesPerSend,
             NativeOverlapped* overlapped,
index cb319d9..634091a 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.Net.Sockets;
 using System.Runtime.InteropServices;
@@ -27,9 +28,9 @@ internal static partial class Interop
         internal static extern SocketError WSAIoctl_Blocking(
             SafeSocketHandle socketHandle,
             [In] int ioControlCode,
-            [In] byte[] inBuffer,
+            [In] byte[]? inBuffer,
             [In] int inBufferSize,
-            [Out] byte[] outBuffer,
+            [Out] byte[]? outBuffer,
             [In] int outBufferSize,
             [Out] out int bytesTransferred,
             [In] IntPtr overlapped,
index df3c9db..9bd2533 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.Net.Sockets;
 using System.Runtime.InteropServices;
@@ -31,7 +32,7 @@ internal static partial class Interop
             [In] SafeSocketHandle socketHandle,
             [In] SocketOptionLevel optionLevel,
             [In] SocketOptionName optionName,
-            [In] byte[] optionValue,
+            [In] byte[]? optionValue,
             [In] int optionLength);
 
         [DllImport(Interop.Libraries.Ws2_32, SetLastError = true)]
index 32e395f..b1bf965 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.Runtime.InteropServices;
 using System.Threading;
@@ -12,7 +13,7 @@ namespace System.Net.Sockets
 {
     internal sealed class SafeNativeOverlapped : SafeHandle
     {
-        private readonly SafeSocketHandle _socketHandle;
+        private readonly SafeSocketHandle? _socketHandle;
 
         private SafeNativeOverlapped()
             : this(IntPtr.Zero)
@@ -59,7 +60,7 @@ namespace System.Net.Sockets
                 {
                     Debug.Assert(_socketHandle != null, "_socketHandle is null.");
 
-                    ThreadPoolBoundHandle boundHandle = _socketHandle.IOCPBoundHandle;
+                    ThreadPoolBoundHandle? boundHandle = _socketHandle.IOCPBoundHandle;
                     Debug.Assert(boundHandle != null, "SafeNativeOverlapped::FreeNativeOverlapped - boundHandle is null");
 
                     // FreeNativeOverlapped will be called even if boundHandle was previously disposed.
index acbdfe5..2dc2c65 100644 (file)
@@ -2,13 +2,14 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Security.Principal;
 
 namespace System.Net
 {
     internal partial class ContextAwareResult
     {
-        private WindowsIdentity _windowsIdentity;
+        private WindowsIdentity? _windowsIdentity;
 
         // Security: We need an assert for a call into WindowsIdentity.GetCurrent.
         private void SafeCaptureIdentity()
index f17b985..b143be3 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;
 
 namespace System.Net
@@ -20,8 +21,8 @@ namespace System.Net
     // to have several pending IOs differentiated by their state object.  We don't want that pattern to break the cache.
     internal class CallbackClosure
     {
-        private readonly AsyncCallback _savedCallback;
-        private readonly ExecutionContext _savedContext;
+        private readonly AsyncCallback? _savedCallback;
+        private readonly ExecutionContext? _savedContext;
 
         internal CallbackClosure(ExecutionContext context, AsyncCallback callback)
         {
@@ -32,7 +33,7 @@ namespace System.Net
             }
         }
 
-        internal bool IsCompatible(AsyncCallback callback)
+        internal bool IsCompatible(AsyncCallback? callback)
         {
             if (callback == null || _savedCallback == null)
             {
@@ -49,7 +50,7 @@ namespace System.Net
             return true;
         }
 
-        internal AsyncCallback AsyncCallback
+        internal AsyncCallback? AsyncCallback
         {
             get
             {
@@ -57,7 +58,7 @@ namespace System.Net
             }
         }
 
-        internal ExecutionContext Context
+        internal ExecutionContext? Context
         {
             get
             {
@@ -82,12 +83,12 @@ namespace System.Net
         }
 
         // This needs to be volatile so it's sure to make it over to the completion thread in time.
-        private volatile ExecutionContext _context;
-        private object _lock;
+        private volatile ExecutionContext? _context;
+        private object? _lock;
         private StateFlags _flags;
 
 
-        internal ContextAwareResult(object myObject, object myState, AsyncCallback myCallBack) :
+        internal ContextAwareResult(object myObject, object? myState, AsyncCallback? myCallBack) :
             this(false, false, myObject, myState, myCallBack)
         { }
 
@@ -97,11 +98,11 @@ namespace System.Net
         //
         // Setting forceCaptureContext enables the ContextCopy property even when a null callback is specified.  (The context is
         // always captured if a callback is given.)
-        internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, object myObject, object myState, AsyncCallback myCallBack) :
+        internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, object myObject, object? myState, AsyncCallback? myCallBack) :
             this(captureIdentity, forceCaptureContext, false, myObject, myState, myCallBack)
         { }
 
-        internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object myObject, object myState, AsyncCallback myCallBack) :
+        internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object myObject, object? myState, AsyncCallback? myCallBack) :
             base(myObject, myState, myCallBack)
         {
             if (forceCaptureContext)
@@ -124,7 +125,7 @@ namespace System.Net
         // May block briefly if the context is still being produced.
         //
         // Returns null if called from the posting thread.
-        internal ExecutionContext ContextCopy
+        internal ExecutionContext? ContextCopy
         {
             get
             {
@@ -138,7 +139,7 @@ namespace System.Net
                     throw new InvalidOperationException(SR.net_completed_result);
                 }
 
-                ExecutionContext context = _context;
+                ExecutionContext? context = _context;
                 if (context != null)
                 {
                     return context; // No need to copy on CoreCLR; ExecutionContext is immutable
@@ -189,13 +190,13 @@ namespace System.Net
 
         internal object StartPostingAsyncOp()
         {
-            return StartPostingAsyncOp(true);
+            return StartPostingAsyncOp(true)!;
         }
 
         // If ContextCopy or Identity will be used, the return value should be locked until FinishPostingAsyncOp() is called
         // or the operation has been aborted (e.g. by BeginXxx throwing).  Otherwise, this can be called with false to prevent the lock
         // object from being created.
-        internal object StartPostingAsyncOp(bool lockCapture)
+        internal object? StartPostingAsyncOp(bool lockCapture)
         {
             if (InternalPeekCompleted)
             {
@@ -220,13 +221,13 @@ namespace System.Net
 
             _flags |= StateFlags.PostBlockFinished;
 
-            ExecutionContext cachedContext = null;
+            ExecutionContext? cachedContext = null;
             return CaptureOrComplete(ref cachedContext, false);
         }
 
         // Call this when returning control to the user.  Allows a cached Callback Closure to be supplied and used
         // as appropriate, and replaced with a new one.
-        internal bool FinishPostingAsyncOp(ref CallbackClosure closure)
+        internal bool FinishPostingAsyncOp(ref CallbackClosure? closure)
         {
             // Ignore this call if StartPostingAsyncOp() failed or wasn't called, or this has already been called.
             if ((_flags & (StateFlags.PostBlockStarted | StateFlags.PostBlockFinished)) != StateFlags.PostBlockStarted)
@@ -237,8 +238,8 @@ namespace System.Net
             _flags |= StateFlags.PostBlockFinished;
 
             // Need a copy of this ref argument since it can be used in many of these calls simultaneously.
-            CallbackClosure closureCopy = closure;
-            ExecutionContext cachedContext;
+            CallbackClosure? closureCopy = closure;
+            ExecutionContext? cachedContext;
             if (closureCopy == null)
             {
                 cachedContext = null;
@@ -283,7 +284,7 @@ namespace System.Net
         // called.
         //
         // Returns whether the operation completed sync or not.
-        private bool CaptureOrComplete(ref ExecutionContext cachedContext, bool returnContext)
+        private bool CaptureOrComplete(ref ExecutionContext? cachedContext, bool returnContext)
         {
             if ((_flags & StateFlags.PostBlockStarted) == 0)
             {
@@ -374,7 +375,7 @@ namespace System.Net
                 return;
             }
 
-            ExecutionContext context = _context;
+            ExecutionContext? context = _context;
 
             // If the context is being abandoned or wasn't captured (SuppressFlow, null AsyncCallback), just
             // complete regularly, as long as CaptureOrComplete() has finished.
@@ -385,7 +386,7 @@ namespace System.Net
                 return;
             }
 
-            ExecutionContext.Run(context, s => ((ContextAwareResult)s).CompleteCallback(), this);
+            ExecutionContext.Run(context, s => ((ContextAwareResult)s!).CompleteCallback(), this);
         }
 
         private void CompleteCallback()
@@ -394,6 +395,6 @@ namespace System.Net
             base.Complete(IntPtr.Zero);
         }
 
-        internal virtual EndPoint RemoteEndPoint => null;
+        internal virtual EndPoint? RemoteEndPoint => null;
     }
 }
index f56a08b..5cf3352 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 Microsoft.Win32.SafeHandles;
 
 namespace System.Net
@@ -13,7 +14,7 @@ namespace System.Net
     //
     internal abstract class DebugSafeHandleMinusOneIsInvalid : SafeHandleMinusOneIsInvalid
     {
-        private string _trace;
+        private string _trace = null!; // initialized by helper called from ctor
 
         protected DebugSafeHandleMinusOneIsInvalid(bool ownsHandle) : base(ownsHandle)
         {
index 217ff1a..fab19ad 100644 (file)
@@ -13,7 +13,7 @@ namespace System.Net.Internals
         {
             private readonly EndPoint? _endPoint;
 
-            public ExtendedSocketException(int errorCode, EndPoint endPoint)
+            public ExtendedSocketException(int errorCode, EndPoint? endPoint)
                 : base(errorCode)
             {
                 _endPoint = endPoint;
@@ -29,7 +29,7 @@ namespace System.Net.Internals
                 (_endPoint == null) ? base.Message : base.Message + " " + _endPoint.ToString();
         }
 
-        public static SocketException CreateSocketException(int socketError, EndPoint endPoint)
+        public static SocketException CreateSocketException(int socketError, EndPoint? endPoint)
         {
             return new ExtendedSocketException(socketError, endPoint);
         }
index 54847f7..20d9557 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.Threading;
 using System.Threading.Tasks;
@@ -17,13 +18,13 @@ namespace System.Net
 
         // This is to avoid user mistakes when they queue another async op from a callback the completes sync.
         [ThreadStatic]
-        private static ThreadContext t_threadContext;
+        private static ThreadContext? t_threadContext;
 
         private static ThreadContext CurrentThreadContext
         {
             get
             {
-                ThreadContext threadContext = t_threadContext;
+                ThreadContext? threadContext = t_threadContext;
                 if (threadContext == null)
                 {
                     threadContext = new ThreadContext();
@@ -40,14 +41,14 @@ namespace System.Net
         }
 
 #if DEBUG
-        internal object _debugAsyncChain = null;    // Optionally used to track chains of async calls.
+        internal object? _debugAsyncChain = null;    // Optionally used to track chains of async calls.
         private bool _protectState;                 // Used by ContextAwareResult to prevent some calls.
 #endif
 
         private readonly object _asyncObject;               // Caller's async object.
-        private readonly object _asyncState;                // Caller's state object.
-        private AsyncCallback _asyncCallback;      // Caller's callback method.
-        private object _result;                    // Final IO result to be returned byt the End*() method.
+        private readonly object? _asyncState;               // Caller's state object.
+        private AsyncCallback? _asyncCallback;     // Caller's callback method.
+        private object? _result;                   // Final IO result to be returned byt the End*() method.
         private int _errorCode;                    // Win32 error code for Win32 IO async calls (that want to throw).
         private int _intCompleted;                 // Sign bit indicates synchronous completion if set.
                                                    // Remaining bits count the number of InvokeCallbak() calls.
@@ -55,9 +56,9 @@ namespace System.Net
         private bool _endCalled;                   // True if the user called the End*() method.
         private bool _userEvent;                   // True if the event has been (or is about to be) handed to the user
 
-        private object _event;                     // Lazy allocated event to be returned in the IAsyncResult for the client to wait on.
+        private object? _event;                    // Lazy allocated event to be returned in the IAsyncResult for the client to wait on.
 
-        internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack)
+        internal LazyAsyncResult(object myObject, object? myState, AsyncCallback? myCallBack)
         {
             _asyncObject = myObject;
             _asyncState = myState;
@@ -76,7 +77,7 @@ namespace System.Net
         }
 
         // Interface method to return the caller's state object.
-        public object AsyncState
+        public object? AsyncState
         {
             get
             {
@@ -84,7 +85,7 @@ namespace System.Net
             }
         }
 
-        protected AsyncCallback AsyncCallback
+        protected AsyncCallback? AsyncCallback
         {
             get
             {
@@ -117,8 +118,6 @@ namespace System.Net
                 }
 #endif
 
-                ManualResetEvent asyncEvent;
-
                 // Indicates that the user has seen the event; it can't be disposed.
                 _userEvent = true;
 
@@ -132,7 +131,7 @@ namespace System.Net
                 // possible for _event to become null immediately after being set, but only if
                 // IsCompleted has become true.  Therefore it's possible for this property
                 // to give different (set) events to different callers when IsCompleted is true.
-                asyncEvent = (ManualResetEvent)_event;
+                ManualResetEvent? asyncEvent = (ManualResetEvent?)_event;
                 while (asyncEvent == null)
                 {
                     LazilyCreateEvent(out asyncEvent);
@@ -253,7 +252,7 @@ namespace System.Net
         }
 
         // Internal property for setting the IO result.
-        internal object Result
+        internal object? Result
         {
             get
             {
@@ -310,7 +309,7 @@ namespace System.Net
         // Used by derived classes to pass context into an overridden Complete().  Useful
         // for determining the 'winning' thread in case several may simultaneously call
         // the equivalent of InvokeCallback().
-        protected void ProtectedInvokeCallback(object result, IntPtr userToken)
+        protected void ProtectedInvokeCallback(object? result, IntPtr userToken)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, result, userToken);
 
@@ -334,7 +333,7 @@ namespace System.Net
                     _result = result;
                 }
 
-                ManualResetEvent asyncEvent = (ManualResetEvent)_event;
+                ManualResetEvent? asyncEvent = (ManualResetEvent?)_event;
                 if (asyncEvent != null)
                 {
                     try
@@ -353,7 +352,7 @@ namespace System.Net
         }
 
         // Completes the IO with a result and invoking the user's callback.
-        internal void InvokeCallback(object result)
+        internal void InvokeCallback(object? result)
         {
             ProtectedInvokeCallback(result, IntPtr.Zero);
         }
@@ -384,7 +383,7 @@ namespace System.Net
                         if (NetEventSource.IsEnabled) NetEventSource.Info(this, "*** OFFLOADED the user callback ****");
 
                         Task.Factory.StartNew(
-                            s => WorkerThreadComplete(s),
+                            s => WorkerThreadComplete(s!),
                             this,
                             CancellationToken.None,
                             TaskCreationOptions.DenyChildAttach,
@@ -422,7 +421,7 @@ namespace System.Net
 
             try
             {
-                thisPtr._asyncCallback(thisPtr);
+                thisPtr._asyncCallback!(thisPtr);
             }
             finally
             {
@@ -437,21 +436,21 @@ namespace System.Net
         {
         }
 
-        internal object InternalWaitForCompletion()
+        internal object? InternalWaitForCompletion()
         {
             return WaitForCompletion(true);
         }
 
-        private object WaitForCompletion(bool snap)
+        private object? WaitForCompletion(bool snap)
         {
-            ManualResetEvent waitHandle = null;
+            ManualResetEvent? waitHandle = null;
             bool createdByMe = false;
             bool complete = snap ? IsCompleted : InternalPeekCompleted;
 
             if (!complete)
             {
                 // Not done yet, so wait:
-                waitHandle = (ManualResetEvent)_event;
+                waitHandle = (ManualResetEvent?)_event;
                 if (waitHandle == null)
                 {
                     createdByMe = LazilyCreateEvent(out waitHandle);
@@ -477,11 +476,11 @@ namespace System.Net
                     {
                         // Does _userEvent need to be volatile (or _event set via Interlocked) in order
                         // to avoid giving a user a disposed event?
-                        ManualResetEvent oldEvent = (ManualResetEvent)_event;
+                        ManualResetEvent? oldEvent = (ManualResetEvent?)_event;
                         _event = null;
                         if (!_userEvent)
                         {
-                            oldEvent.Dispose();
+                            oldEvent?.Dispose();
                         }
                     }
                 }
index 46cd2ee..5d8d579 100644 (file)
@@ -11,6 +11,7 @@
 #nullable enable
 using System.Collections;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Diagnostics.Tracing;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
@@ -125,7 +126,7 @@ namespace System.Net
         /// <param name="arg1">The second object to log.</param>
         /// <param name="memberName">The calling member.</param>
         [NonEvent]
-        public static void Enter(object? thisOrContextObject, object arg0, object arg1, [CallerMemberName] string? memberName = null)
+        public static void Enter(object? thisOrContextObject, object? arg0, object arg1, [CallerMemberName] string? memberName = null)
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(arg0);
@@ -172,7 +173,7 @@ namespace System.Net
         /// <param name="arg0">A return value from the member.</param>
         /// <param name="memberName">The calling member.</param>
         [NonEvent]
-        public static void Exit(object? thisOrContextObject, object arg0, [CallerMemberName] string? memberName = null)
+        public static void Exit(object? thisOrContextObject, object? arg0, [CallerMemberName] string? memberName = null)
         {
             DebugValidateArg(thisOrContextObject);
             DebugValidateArg(arg0);
@@ -264,6 +265,9 @@ namespace System.Net
         /// <param name="formattableString">The message to be logged.</param>
         /// <param name="memberName">The calling member.</param>
         [NonEvent]
+#if NETCOREAPP
+        [DoesNotReturn]
+#endif
         public static void Fail(object? thisOrContextObject, FormattableString formattableString, [CallerMemberName] string? memberName = null)
         {
             // Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
@@ -278,6 +282,9 @@ namespace System.Net
         /// <param name="message">The message to be logged.</param>
         /// <param name="memberName">The calling member.</param>
         [NonEvent]
+#if NETCOREAPP
+        [DoesNotReturn]
+#endif
         public static void Fail(object? thisOrContextObject, object message, [CallerMemberName] string? memberName = null)
         {
             // Don't call DebugValidateArg on args, as we expect Fail to be used in assert/failure situations
index 3025ee6..1176cd8 100644 (file)
@@ -28,7 +28,7 @@ namespace System.IO.Pipes
             SafePipeHandle? clientHandle = null;
             try
             {
-                socket.Connect(new UnixDomainSocketEndPoint(_normalizedPipePath));
+                socket.Connect(new UnixDomainSocketEndPoint(_normalizedPipePath!));
                 clientHandle = new SafePipeHandle(socket);
                 ConfigureSocket(socket, clientHandle, _direction, 0, 0, _inheritability);
             }
index fdd1d92..9da3770 100644 (file)
@@ -183,7 +183,7 @@ namespace System.IO.Pipes
 
             try
             {
-                return await InternalHandle!.NamedPipeSocket.ReceiveAsync(destination, SocketFlags.None, cancellationToken).ConfigureAwait(false);
+                return await InternalHandle!.NamedPipeSocket!.ReceiveAsync(destination, SocketFlags.None, cancellationToken).ConfigureAwait(false);
             }
             catch (SocketException e)
             {
@@ -199,7 +199,7 @@ namespace System.IO.Pipes
             {
                 while (source.Length > 0)
                 {
-                    int bytesWritten = await _handle!.NamedPipeSocket.SendAsync(source, SocketFlags.None, cancellationToken).ConfigureAwait(false);
+                    int bytesWritten = await _handle!.NamedPipeSocket!.SendAsync(source, SocketFlags.None, cancellationToken).ConfigureAwait(false);
                     Debug.Assert(bytesWritten > 0 && bytesWritten <= source.Length);
                     source = source.Slice(bytesWritten);
                 }
index 965e990..f2535d4 100644 (file)
@@ -50,7 +50,7 @@ namespace System.Net.Sockets
         private int _dummyPrimitive;
         public System.Net.IPAddress Address { get { throw null; } }
         public int Interface { 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 static bool operator ==(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; }
         public static bool operator !=(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; }
@@ -82,7 +82,7 @@ namespace System.Net.Sockets
         public MulticastOption(System.Net.IPAddress group, System.Net.IPAddress mcint) { }
         public System.Net.IPAddress Group { get { throw null; } set { } }
         public int InterfaceIndex { get { throw null; } set { } }
-        public System.Net.IPAddress LocalAddress { get { throw null; } set { } }
+        public System.Net.IPAddress? LocalAddress { get { throw null; } set { } }
     }
     public partial class NetworkStream : System.IO.Stream
     {
@@ -102,8 +102,8 @@ namespace System.Net.Sockets
         public System.Net.Sockets.Socket Socket { get { throw null; } }
         protected bool Writeable { get { throw null; } set { } }
         public override int WriteTimeout { get { throw null; } set { } }
-        public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int size, System.AsyncCallback callback, object state) { throw null; }
-        public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int size, System.AsyncCallback callback, object state) { throw null; }
+        public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int size, System.AsyncCallback? callback, object? state) { throw null; }
+        public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int size, System.AsyncCallback? callback, object? state) { throw null; }
         public void Close(int timeout) { }
         protected override void Dispose(bool disposing) { }
         public override int EndRead(System.IAsyncResult asyncResult) { throw null; }
@@ -212,11 +212,11 @@ namespace System.Net.Sockets
         public SendPacketsElement(string filepath, int offset, int count, bool endOfPacket) { }
         public SendPacketsElement(string filepath, long offset, int count) { }
         public SendPacketsElement(string filepath, long offset, int count, bool endOfPacket) { }
-        public byte[] Buffer { get { throw null; } }
+        public byte[]? Buffer { get { throw null; } }
         public int Count { get { throw null; } }
         public bool EndOfPacket { get { throw null; } }
-        public string FilePath { get { throw null; } }
-        public System.IO.FileStream FileStream { get { throw null; } }
+        public string? FilePath { get { throw null; } }
+        public System.IO.FileStream? FileStream { get { throw null; } }
         public int Offset { get { throw null; } }
         public long OffsetLong { get { throw null; } }
     }
@@ -235,8 +235,9 @@ namespace System.Net.Sockets
         public bool ExclusiveAddressUse { get { throw null; } set { } }
         public System.IntPtr Handle { get { throw null; } }
         public bool IsBound { get { throw null; } }
-        public System.Net.Sockets.LingerOption LingerState { get { throw null; } set { } }
-        public System.Net.EndPoint LocalEndPoint { get { throw null; } }
+        [System.Diagnostics.CodeAnalysis.DisallowNullAttribute]
+        public System.Net.Sockets.LingerOption? LingerState { get { throw null; } set { } }
+        public System.Net.EndPoint? LocalEndPoint { get { throw null; } }
         public bool MulticastLoopback { get { throw null; } set { } }
         public bool NoDelay { get { throw null; } set { } }
         public static bool OSSupportsIPv4 { get { throw null; } }
@@ -245,7 +246,7 @@ namespace System.Net.Sockets
         public System.Net.Sockets.ProtocolType ProtocolType { get { throw null; } }
         public int ReceiveBufferSize { get { throw null; } set { } }
         public int ReceiveTimeout { get { throw null; } set { } }
-        public System.Net.EndPoint RemoteEndPoint { get { throw null; } }
+        public System.Net.EndPoint? RemoteEndPoint { get { throw null; } }
         public System.Net.Sockets.SafeSocketHandle SafeHandle { get { throw null; } }
         public int SendBufferSize { get { throw null; } set { } }
         public int SendTimeout { get { throw null; } set { } }
@@ -258,27 +259,27 @@ namespace System.Net.Sockets
         public bool UseOnlyOverlappedIO { get { throw null; } set { } }
         public System.Net.Sockets.Socket Accept() { throw null; }
         public bool AcceptAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
-        public System.IAsyncResult BeginAccept(System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginAccept(int receiveSize, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginAccept(System.Net.Sockets.Socket acceptSocket, int receiveSize, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginConnect(System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback requestCallback, object state) { throw null; }
-        public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback requestCallback, object state) { throw null; }
-        public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback requestCallback, object state) { throw null; }
-        public System.IAsyncResult BeginDisconnect(bool reuseSocket, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginSendFile(string fileName, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, System.Net.Sockets.TransmitFileOptions flags, System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state) { throw null; }
+        public System.IAsyncResult BeginAccept(System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginAccept(int receiveSize, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginAccept(System.Net.Sockets.Socket? acceptSocket, int receiveSize, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginConnect(System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
+        public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
+        public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
+        public System.IAsyncResult BeginDisconnect(bool reuseSocket, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult? BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult? BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult? BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult? BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginSendFile(string fileName, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginSendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, System.Net.Sockets.TransmitFileOptions flags, System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; }
         public void Bind(System.Net.EndPoint localEP) { }
         public static void CancelConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { }
         public void Close() { }
@@ -294,8 +295,8 @@ namespace System.Net.Sockets
         public void Dispose() { }
         protected virtual void Dispose(bool disposing) { }
         public System.Net.Sockets.SocketInformation DuplicateAndClose(int targetProcessId) { throw null; }
-        public System.Net.Sockets.Socket EndAccept(out byte[] buffer, System.IAsyncResult asyncResult) { throw null; }
-        public System.Net.Sockets.Socket EndAccept(out byte[] buffer, out int bytesTransferred, System.IAsyncResult asyncResult) { throw null; }
+        public System.Net.Sockets.Socket EndAccept(out byte[]? buffer, System.IAsyncResult asyncResult) { throw null; }
+        public System.Net.Sockets.Socket EndAccept(out byte[]? buffer, out int bytesTransferred, System.IAsyncResult asyncResult) { throw null; }
         public System.Net.Sockets.Socket EndAccept(System.IAsyncResult asyncResult) { throw null; }
         public void EndConnect(System.IAsyncResult asyncResult) { }
         public void EndDisconnect(System.IAsyncResult asyncResult) { }
@@ -308,11 +309,11 @@ namespace System.Net.Sockets
         public void EndSendFile(System.IAsyncResult asyncResult) { }
         public int EndSendTo(System.IAsyncResult asyncResult) { throw null; }
         ~Socket() { }
-        public object GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName) { throw null; }
+        public object? GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName) { throw null; }
         public void GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { }
         public byte[] GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionLength) { throw null; }
-        public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue) { throw null; }
-        public int IOControl(System.Net.Sockets.IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue) { throw null; }
+        public int IOControl(int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue) { throw null; }
+        public int IOControl(System.Net.Sockets.IOControlCode ioControlCode, byte[]? optionInValue, byte[]? optionOutValue) { throw null; }
         public void Listen() { }
         public void Listen(int backlog) { }
         public bool Poll(int microSeconds, System.Net.Sockets.SelectMode mode) { throw null; }
@@ -335,7 +336,7 @@ namespace System.Net.Sockets
         public bool ReceiveFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
         public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { throw null; }
         public bool ReceiveMessageFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
-        public static void Select(System.Collections.IList checkRead, System.Collections.IList checkWrite, System.Collections.IList checkError, int microSeconds) { }
+        public static void Select(System.Collections.IList? checkRead, System.Collections.IList? checkWrite, System.Collections.IList? checkError, int microSeconds) { }
         public int Send(byte[] buffer) { throw null; }
         public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; }
         public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; }
@@ -349,7 +350,7 @@ namespace System.Net.Sockets
         public int Send(System.ReadOnlySpan<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; }
         public bool SendAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
         public void SendFile(string fileName) { }
-        public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, System.Net.Sockets.TransmitFileOptions flags) { }
+        public void SendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, System.Net.Sockets.TransmitFileOptions flags) { }
         public bool SendPacketsAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; }
         public int SendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; }
         public int SendTo(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; }
@@ -367,30 +368,30 @@ namespace System.Net.Sockets
     {
         public SocketAsyncEventArgs() { }
         public SocketAsyncEventArgs(bool unsafeSuppressExecutionContextFlow) { }
-        public System.Net.Sockets.Socket AcceptSocket { get { throw null; } set { } }
-        public byte[] Buffer { get { throw null; } }
-        public System.Collections.Generic.IList<System.ArraySegment<byte>> BufferList { get { throw null; } set { } }
+        public System.Net.Sockets.Socket? AcceptSocket { get { throw null; } set { } }
+        public byte[]? Buffer { get { throw null; } }
+        public System.Collections.Generic.IList<System.ArraySegment<byte>>? BufferList { get { throw null; } set { } }
         public int BytesTransferred { get { throw null; } }
-        public System.Exception ConnectByNameError { get { throw null; } }
-        public System.Net.Sockets.Socket ConnectSocket { get { throw null; } }
+        public System.Exception? ConnectByNameError { get { throw null; } }
+        public System.Net.Sockets.Socket? ConnectSocket { get { throw null; } }
         public int Count { get { throw null; } }
         public bool DisconnectReuseSocket { get { throw null; } set { } }
         public System.Net.Sockets.SocketAsyncOperation LastOperation { get { throw null; } }
         public System.Memory<byte> MemoryBuffer { get { throw null; } }
         public int Offset { get { throw null; } }
         public System.Net.Sockets.IPPacketInformation ReceiveMessageFromPacketInfo { get { throw null; } }
-        public System.Net.EndPoint RemoteEndPoint { get { throw null; } set { } }
-        public System.Net.Sockets.SendPacketsElement[] SendPacketsElements { get { throw null; } set { } }
+        public System.Net.EndPoint? RemoteEndPoint { get { throw null; } set { } }
+        public System.Net.Sockets.SendPacketsElement[]? SendPacketsElements { get { throw null; } set { } }
         public System.Net.Sockets.TransmitFileOptions SendPacketsFlags { get { throw null; } set { } }
         public int SendPacketsSendSize { get { throw null; } set { } }
         public System.Net.Sockets.SocketError SocketError { get { throw null; } set { } }
         public System.Net.Sockets.SocketFlags SocketFlags { get { throw null; } set { } }
-        public object UserToken { get { throw null; } set { } }
-        public event System.EventHandler<System.Net.Sockets.SocketAsyncEventArgs> Completed { add { } remove { } }
+        public object? UserToken { get { throw null; } set { } }
+        public event System.EventHandler<System.Net.Sockets.SocketAsyncEventArgs>? Completed { add { } remove { } }
         public void Dispose() { }
         ~SocketAsyncEventArgs() { }
         protected virtual void OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e) { }
-        public void SetBuffer(byte[] buffer, int offset, int count) { }
+        public void SetBuffer(byte[]? buffer, int offset, int count) { }
         public void SetBuffer(int offset, int count) { }
         public void SetBuffer(System.Memory<byte> buffer) { }
     }
@@ -516,7 +517,7 @@ namespace System.Net.Sockets
     public static partial class SocketTaskExtensions
     {
         public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket) { throw null; }
-        public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket, System.Net.Sockets.Socket acceptSocket) { throw null; }
+        public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket, System.Net.Sockets.Socket? acceptSocket) { throw null; }
         public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.EndPoint remoteEP) { throw null; }
         public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress address, int port) { throw null; }
         public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress[] addresses, int port) { throw null; }
@@ -551,15 +552,16 @@ namespace System.Net.Sockets
         public System.Net.Sockets.Socket Client { get { throw null; } set { } }
         public bool Connected { get { throw null; } }
         public bool ExclusiveAddressUse { get { throw null; } set { } }
-        public System.Net.Sockets.LingerOption LingerState { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.DisallowNullAttribute]
+        public System.Net.Sockets.LingerOption? LingerState { get { throw null; } set { } }
         public bool NoDelay { get { throw null; } set { } }
         public int ReceiveBufferSize { get { throw null; } set { } }
         public int ReceiveTimeout { get { throw null; } set { } }
         public int SendBufferSize { get { throw null; } set { } }
         public int SendTimeout { get { throw null; } set { } }
-        public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback requestCallback, object state) { throw null; }
-        public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback requestCallback, object state) { throw null; }
-        public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback requestCallback, object state) { throw null; }
+        public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
+        public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
+        public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
         public void Close() { }
         public void Connect(System.Net.IPAddress address, int port) { }
         public void Connect(System.Net.IPAddress[] ipAddresses, int port) { }
@@ -589,8 +591,8 @@ namespace System.Net.Sockets
         public System.Net.Sockets.TcpClient AcceptTcpClient() { throw null; }
         public System.Threading.Tasks.Task<System.Net.Sockets.TcpClient> AcceptTcpClientAsync() { throw null; }
         public void AllowNatTraversal(bool allowed) { }
-        public System.IAsyncResult BeginAcceptSocket(System.AsyncCallback callback, object state) { throw null; }
-        public System.IAsyncResult BeginAcceptTcpClient(System.AsyncCallback callback, object state) { throw null; }
+        public System.IAsyncResult BeginAcceptSocket(System.AsyncCallback? callback, object? state) { throw null; }
+        public System.IAsyncResult BeginAcceptTcpClient(System.AsyncCallback? callback, object? state) { throw null; }
         public static System.Net.Sockets.TcpListener Create(int port) { throw null; }
         public System.Net.Sockets.Socket EndAcceptSocket(System.IAsyncResult asyncResult) { throw null; }
         public System.Net.Sockets.TcpClient EndAcceptTcpClient(System.IAsyncResult asyncResult) { throw null; }
@@ -626,10 +628,10 @@ namespace System.Net.Sockets
         public bool MulticastLoopback { get { throw null; } set { } }
         public short Ttl { get { throw null; } set { } }
         public void AllowNatTraversal(bool allowed) { }
-        public System.IAsyncResult BeginReceive(System.AsyncCallback requestCallback, object state) { throw null; }
-        public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.AsyncCallback requestCallback, object state) { throw null; }
-        public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.Net.IPEndPoint endPoint, System.AsyncCallback requestCallback, object state) { throw null; }
-        public System.IAsyncResult BeginSend(byte[] datagram, int bytes, string hostname, int port, System.AsyncCallback requestCallback, object state) { throw null; }
+        public System.IAsyncResult BeginReceive(System.AsyncCallback? requestCallback, object? state) { throw null; }
+        public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.AsyncCallback? requestCallback, object? state) { throw null; }
+        public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.Net.IPEndPoint? endPoint, System.AsyncCallback? requestCallback, object? state) { throw null; }
+        public System.IAsyncResult BeginSend(byte[] datagram, int bytes, string? hostname, int port, System.AsyncCallback? requestCallback, object? state) { throw null; }
         public void Close() { }
         public void Connect(System.Net.IPAddress addr, int port) { }
         public void Connect(System.Net.IPEndPoint endPoint) { }
@@ -644,14 +646,14 @@ namespace System.Net.Sockets
         public void JoinMulticastGroup(System.Net.IPAddress multicastAddr) { }
         public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, int timeToLive) { }
         public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, System.Net.IPAddress localAddress) { }
-        public byte[] Receive(ref System.Net.IPEndPoint remoteEP) { throw null; }
+        public byte[] Receive([System.Diagnostics.CodeAnalysis.NotNullAttribute] ref System.Net.IPEndPoint? remoteEP) { throw null; }
         public System.Threading.Tasks.Task<System.Net.Sockets.UdpReceiveResult> ReceiveAsync() { throw null; }
         public int Send(byte[] dgram, int bytes) { throw null; }
-        public int Send(byte[] dgram, int bytes, System.Net.IPEndPoint endPoint) { throw null; }
-        public int Send(byte[] dgram, int bytes, string hostname, int port) { throw null; }
+        public int Send(byte[] dgram, int bytes, System.Net.IPEndPoint? endPoint) { throw null; }
+        public int Send(byte[] dgram, int bytes, string? hostname, int port) { throw null; }
         public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes) { throw null; }
-        public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, System.Net.IPEndPoint endPoint) { throw null; }
-        public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port) { throw null; }
+        public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, System.Net.IPEndPoint? endPoint) { throw null; }
+        public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, string? hostname, int port) { throw null; }
     }
     public partial struct UdpReceiveResult : System.IEquatable<System.Net.Sockets.UdpReceiveResult>
     {
@@ -661,7 +663,7 @@ namespace System.Net.Sockets
         public byte[] Buffer { get { throw null; } }
         public System.Net.IPEndPoint RemoteEndPoint { get { throw null; } }
         public bool Equals(System.Net.Sockets.UdpReceiveResult other) { throw null; }
-        public override bool Equals(object obj) { throw null; }
+        public override bool Equals(object? obj) { throw null; }
         public override int GetHashCode() { throw null; }
         public static bool operator ==(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; }
         public static bool operator !=(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; }
index b565b96..7229303 100644 (file)
@@ -1,6 +1,7 @@
 <Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="System.Net.Sockets.cs" />
index f105c12..f1941c2 100644 (file)
@@ -3,6 +3,7 @@
     <AssemblyName>System.Net.Sockets</AssemblyName>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix</TargetFrameworks>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <PropertyGroup>
     <!-- SYSTEM_NET_SOCKETS_DLL is required to allow source-level code sharing for types defined within the
     <Reference Include="System.Threading.Overlapped" />
     <Reference Include="System.Threading.ThreadPool" />
   </ItemGroup>
-  <ItemGroup Condition="'$(TargetsUnix)' == 'true'">
-    <Reference Include="System.Threading.ThreadPool" />
-  </ItemGroup>
 </Project>
\ No newline at end of file
index a995ed3..1bc58e4 100644 (file)
@@ -14,9 +14,9 @@ namespace System.Net.Sockets
     // AcceptOverlappedAsyncResult - used to take care of storage for async Socket BeginAccept call.
     internal sealed partial class AcceptOverlappedAsyncResult : BaseOverlappedAsyncResult
     {
-        private Socket _acceptedSocket;
+        private Socket? _acceptedSocket;
 
-        internal Socket AcceptSocket
+        internal Socket? AcceptSocket
         {
             set
             {
@@ -33,6 +33,8 @@ namespace System.Net.Sockets
 
             if (errorCode == SocketError.Success)
             {
+                Debug.Assert(_listenSocket._rightEndPoint != null);
+
                 Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_listenSocket._rightEndPoint);
                 System.Buffer.BlockCopy(socketAddress, 0, remoteSocketAddress.Buffer, 0, socketAddressLen);
 
@@ -44,7 +46,7 @@ namespace System.Net.Sockets
             base.CompletionCallback(0, errorCode);
         }
 
-        internal override object PostCompletion(int numBytes)
+        internal override object? PostCompletion(int numBytes)
         {
             _numBytes = numBytes;
             return (SocketError)ErrorCode == SocketError.Success ? _acceptedSocket : null;
index 239b6c1..73d3b21 100644 (file)
@@ -10,23 +10,23 @@ namespace System.Net.Sockets
     // AcceptOverlappedAsyncResult - used to take care of storage for async Socket BeginAccept call.
     internal sealed partial class AcceptOverlappedAsyncResult : BaseOverlappedAsyncResult
     {
-        private Socket _acceptSocket;
+        private Socket? _acceptSocket;
         private int _addressBufferLength;
 
         // This method will be called by us when the IO completes synchronously and
         // by the ThreadPool when the IO completes asynchronously. (only called on WinNT)
-        internal override object PostCompletion(int numBytes)
+        internal override object? PostCompletion(int numBytes)
         {
             SocketError errorCode = (SocketError)ErrorCode;
 
-            Internals.SocketAddress remoteSocketAddress = null;
+            Internals.SocketAddress? remoteSocketAddress = null;
             if (errorCode == SocketError.Success)
             {
                 _numBytes = numBytes;
                 if (NetEventSource.IsEnabled) LogBuffer(numBytes);
 
                 // get the endpoint
-                remoteSocketAddress = IPEndPointExtensions.Serialize(_listenSocket._rightEndPoint);
+                remoteSocketAddress = IPEndPointExtensions.Serialize(_listenSocket._rightEndPoint!);
 
                 IntPtr localAddr;
                 int localAddrLength;
@@ -40,6 +40,7 @@ namespace System.Net.Sockets
                     safeHandle.DangerousAddRef(ref refAdded);
                     IntPtr handle = safeHandle.DangerousGetHandle();
 
+                    Debug.Assert(_buffer != null);
                     _listenSocket.GetAcceptExSockaddrs(
                         Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, 0),
                         _buffer.Length - (_addressBufferLength * 2),
@@ -53,7 +54,7 @@ namespace System.Net.Sockets
                     Marshal.Copy(remoteAddr, remoteSocketAddress.Buffer, 0, remoteSocketAddress.Size);
 
                     errorCode = Interop.Winsock.setsockopt(
-                        _acceptSocket.SafeHandle,
+                        _acceptSocket!.SafeHandle,
                         SocketOptionLevel.Socket,
                         SocketOptionName.UpdateAcceptContext,
                         ref handle,
@@ -86,7 +87,7 @@ namespace System.Net.Sockets
                 return null;
             }
 
-            return _listenSocket.UpdateAcceptSocket(_acceptSocket, _listenSocket._rightEndPoint.Create(remoteSocketAddress));
+            return _listenSocket.UpdateAcceptSocket(_acceptSocket!, _listenSocket._rightEndPoint!.Create(remoteSocketAddress!));
         }
 
         // SetUnmanagedStructures
@@ -111,6 +112,7 @@ namespace System.Net.Sockets
             // condition where tracing is disabled between a calling check and here, in which case the assert
             // may fire erroneously.
             Debug.Assert(NetEventSource.IsEnabled);
+            Debug.Assert(_buffer != null);
 
             if (size > -1)
             {
index 0e9022e..0c8acde 100644 (file)
@@ -8,15 +8,15 @@ namespace System.Net.Sockets
     internal sealed partial class AcceptOverlappedAsyncResult : BaseOverlappedAsyncResult
     {
         private readonly Socket _listenSocket;
-        private byte[] _buffer;
+        private byte[]? _buffer;
 
-        internal AcceptOverlappedAsyncResult(Socket listenSocket, object asyncState, AsyncCallback asyncCallback) :
+        internal AcceptOverlappedAsyncResult(Socket listenSocket, object? asyncState, AsyncCallback? asyncCallback) :
             base(listenSocket, asyncState, asyncCallback)
         {
             _listenSocket = listenSocket;
         }
 
-        internal byte[] Buffer
+        internal byte[]? Buffer
         {
             get
             {
index 3301913..9c3e660 100644 (file)
@@ -17,7 +17,7 @@ namespace System.Net.Sockets
     // BeginReceive, BeginReceiveFrom, BeginSendFile, and BeginAccept calls.
     internal partial class BaseOverlappedAsyncResult : ContextAwareResult
     {
-        public BaseOverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback)
+        public BaseOverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback)
             : base(socket, asyncState, asyncCallback)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Info(this, socket);
index fe32c73..65cab78 100644 (file)
@@ -14,12 +14,12 @@ namespace System.Net.Sockets
     internal partial class BaseOverlappedAsyncResult : ContextAwareResult
     {
         private int _cleanupCount;
-        private SafeNativeOverlapped _nativeOverlapped;
+        private SafeNativeOverlapped? _nativeOverlapped;
 
         // The WinNT Completion Port callback.
         private static readonly unsafe IOCompletionCallback s_ioCallback = new IOCompletionCallback(CompletionPortCallback);
 
-        internal BaseOverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback)
+        internal BaseOverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback)
             : base(socket, asyncState, asyncCallback)
         {
             _cleanupCount = 1;
@@ -34,7 +34,7 @@ namespace System.Net.Sockets
         // These calls are outside the runtime and are unmanaged code, so we need
         // to prepare specific structures and ints that lie in unmanaged memory
         // since the overlapped calls may complete asynchronously.
-        internal void SetUnmanagedStructures(object objectsToPin)
+        internal void SetUnmanagedStructures(object? objectsToPin)
         {
             Socket s = (Socket)AsyncObject;
 
@@ -65,7 +65,7 @@ namespace System.Net.Sockets
             using (DebugThreadTracking.SetThreadKind(ThreadKinds.System))
             {
 #endif
-                BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped);
+                BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!;
 
                 if (asyncResult.InternalPeekCompleted)
                 {
@@ -84,7 +84,7 @@ namespace System.Net.Sockets
                     // or receiving data after shutdown (SD_RECV)).  With Winsock/TCP stack rewrite in longhorn, there may
                     // be other differences as well."
 
-                    Socket socket = asyncResult.AsyncObject as Socket;
+                    Socket? socket = asyncResult.AsyncObject as Socket;
                     if (socket == null)
                     {
                         socketError = SocketError.NotSocket;
@@ -134,12 +134,12 @@ namespace System.Net.Sockets
         private void CompletionCallback(int numBytes, SocketError socketError)
         {
             ErrorCode = (int)socketError;
-            object result = PostCompletion(numBytes);
+            object? result = PostCompletion(numBytes);
             ReleaseUnmanagedStructures(); // must come after PostCompletion, as overrides may use these resources
             InvokeCallback(result);
         }
 
-        internal unsafe NativeOverlapped* DangerousOverlappedPointer => (NativeOverlapped*)_nativeOverlapped.DangerousGetHandle();
+        internal unsafe NativeOverlapped* DangerousOverlappedPointer => (NativeOverlapped*)_nativeOverlapped!.DangerousGetHandle();
 
         // Check the result of the overlapped operation.
         // Handle synchronous success by completing the asyncResult here.
@@ -206,7 +206,7 @@ namespace System.Net.Sockets
         {
             // Free the unmanaged memory if allocated.
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
-            _nativeOverlapped.Dispose();
+            _nativeOverlapped!.Dispose();
             _nativeOverlapped = null;
             GC.SuppressFinalize(this);
         }
index 09b2ff9..08660fa 100644 (file)
@@ -17,7 +17,7 @@ namespace System.Net.Sockets
         internal int _numBytes;
 
         // PostCompletion returns the result object to be set before the user's callback is invoked.
-        internal virtual object PostCompletion(int numBytes)
+        internal virtual object? PostCompletion(int numBytes)
         {
             _numBytes = numBytes;
             return s_resultObjectSentinel; // return sentinel rather than boxing numBytes
index 2e0be37..af40673 100644 (file)
@@ -19,7 +19,7 @@ namespace System.Net.Sockets
         }
 
         // This method is called by base.CompletionPortCallback base.OverlappedCallback as part of IO completion
-        internal override object PostCompletion(int numBytes)
+        internal override object? PostCompletion(int numBytes)
         {
             var errorCode = (SocketError)ErrorCode;
             if (errorCode == SocketError.Success)
index 4c8833f..aba4be6 100644 (file)
@@ -8,7 +8,7 @@ namespace System.Net.Sockets
     internal sealed partial class ConnectOverlappedAsyncResult : BaseOverlappedAsyncResult
     {
         // This method is called by base.CompletionPortCallback base.OverlappedCallback as part of IO completion
-        internal override object PostCompletion(int numBytes)
+        internal override object? PostCompletion(int numBytes)
         {
             SocketError errorCode = (SocketError)ErrorCode;
             Socket socket = (Socket)AsyncObject;
index d479082..288bfa3 100644 (file)
@@ -9,7 +9,7 @@ namespace System.Net.Sockets
     {
         private readonly EndPoint _endPoint;
 
-        internal ConnectOverlappedAsyncResult(Socket socket, EndPoint endPoint, object asyncState, AsyncCallback asyncCallback) :
+        internal ConnectOverlappedAsyncResult(Socket socket, EndPoint endPoint, object? asyncState, AsyncCallback? asyncCallback) :
             base(socket, asyncState, asyncCallback)
         {
             _endPoint = endPoint;
index 7b7064d..0ad746c 100644 (file)
@@ -7,14 +7,14 @@ namespace System.Net.Sockets
     // DisconnectOverlappedAsyncResult - used to take care of storage for async Socket BeginDisconnect call.
     internal sealed partial class DisconnectOverlappedAsyncResult : BaseOverlappedAsyncResult
     {
-        internal DisconnectOverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback) :
+        internal DisconnectOverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback) :
             base(socket, asyncState, asyncCallback)
         {
         }
 
         // This method will be called by us when the IO completes synchronously and
         // by the ThreadPool when the IO completes asynchronously.
-        internal override object PostCompletion(int numBytes)
+        internal override object? PostCompletion(int numBytes)
         {
             if (ErrorCode == (int)SocketError.Success)
             {
index d62adc6..5b2e3c4 100644 (file)
@@ -41,16 +41,16 @@ namespace System.Net.Sockets
         private readonly ProtocolType _protocolType;
         private readonly object _lockObject;
 
-        private AcceptExDelegate _acceptEx;
-        private GetAcceptExSockaddrsDelegate _getAcceptExSockaddrs;
-        private ConnectExDelegate _connectEx;
-        private TransmitPacketsDelegate _transmitPackets;
+        private AcceptExDelegate? _acceptEx;
+        private GetAcceptExSockaddrsDelegate? _getAcceptExSockaddrs;
+        private ConnectExDelegate? _connectEx;
+        private TransmitPacketsDelegate? _transmitPackets;
 
-        private DisconnectExDelegate _disconnectEx;
-        private DisconnectExDelegateBlocking _disconnectExBlocking;
+        private DisconnectExDelegate? _disconnectEx;
+        private DisconnectExDelegateBlocking? _disconnectExBlocking;
 
-        private WSARecvMsgDelegate _recvMsg;
-        private WSARecvMsgDelegateBlocking _recvMsgBlocking;
+        private WSARecvMsgDelegate? _recvMsg;
+        private WSARecvMsgDelegateBlocking? _recvMsgBlocking;
 
         private DynamicWinsockMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
         {
@@ -84,11 +84,13 @@ namespace System.Net.Sockets
             else if (typeof(T) == typeof(DisconnectExDelegate))
             {
                 EnsureDisconnectEx(socketHandle);
+                Debug.Assert(_disconnectEx != null);
                 return (T)(object)_disconnectEx;
             }
             else if (typeof(T) == typeof(DisconnectExDelegateBlocking))
             {
                 EnsureDisconnectEx(socketHandle);
+                Debug.Assert(_disconnectExBlocking != null);
                 return (T)(object)_disconnectExBlocking;
             }
             else if (typeof(T) == typeof(WSARecvMsgDelegate))
index d2bd73e..178ff72 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Net.Sockets
         private static readonly bool s_supportsKeepAliveViaSocketOption = SupportsKeepAliveViaSocketOption();
         private static readonly ConditionalWeakTable<SafeSocketHandle, IOControlKeepAlive> s_socketKeepAliveTable = new ConditionalWeakTable<SafeSocketHandle, IOControlKeepAlive>();
         [ThreadStatic]
-        private static byte[] s_keepAliveValuesBuffer;
+        private static byte[]? s_keepAliveValuesBuffer;
 
         private uint _timeMs = WindowsDefaultTimeMs;
         private uint _intervalMs = WindowsDefaultIntervalMs;
@@ -37,7 +37,7 @@ namespace System.Net.Sockets
 
         public static int Get(SafeSocketHandle handle, SocketOptionName optionName)
         {
-            if (s_socketKeepAliveTable.TryGetValue(handle, out IOControlKeepAlive ioControlKeepAlive))
+            if (s_socketKeepAliveTable.TryGetValue(handle, out IOControlKeepAlive? ioControlKeepAlive))
             {
                 return optionName == SocketOptionName.TcpKeepAliveTime ?
                     MillisecondsToSeconds(ioControlKeepAlive._timeMs) :
index e4df577..2f43cb2 100644 (file)
@@ -34,7 +34,8 @@ namespace System.Net.Sockets
         public static bool operator ==(IPPacketInformation packetInformation1, IPPacketInformation packetInformation2)
         {
             return packetInformation1._networkInterface == packetInformation2._networkInterface &&
-                (packetInformation1._address == null && packetInformation2._address == null || packetInformation1._address.Equals(packetInformation2._address));
+                ((packetInformation1._address == null && packetInformation2._address == null) ||
+                (packetInformation1._address != null && packetInformation1._address.Equals(packetInformation2._address)));
         }
 
         public static bool operator !=(IPPacketInformation packetInformation1, IPPacketInformation packetInformation2)
@@ -42,7 +43,7 @@ namespace System.Net.Sockets
             return !(packetInformation1 == packetInformation2);
         }
 
-        public override bool Equals(object comparand) =>
+        public override bool Equals(object? comparand) =>
             comparand is IPPacketInformation other && this == other;
 
         public override int GetHashCode()
index 5f413cf..7fc0634 100644 (file)
@@ -8,7 +8,7 @@ namespace System.Net.Sockets
     public class MulticastOption
     {
         private IPAddress _group;
-        private IPAddress _localAddress;
+        private IPAddress? _localAddress;
         private int _ifIndex;
 
         // Creates a new instance of the MulticastOption class with the specified IP address
@@ -25,7 +25,7 @@ namespace System.Net.Sockets
                 throw new ArgumentNullException(nameof(mcint));
             }
 
-            Group = group;
+            _group = group;
             LocalAddress = mcint;
         }
 
@@ -41,7 +41,7 @@ namespace System.Net.Sockets
                 throw new ArgumentOutOfRangeException(nameof(interfaceIndex));
             }
 
-            Group = group;
+            _group = group;
             _ifIndex = interfaceIndex;
         }
 
@@ -53,7 +53,7 @@ namespace System.Net.Sockets
                 throw new ArgumentNullException(nameof(group));
             }
 
-            Group = group;
+            _group = group;
 
             LocalAddress = IPAddress.Any;
         }
@@ -72,7 +72,7 @@ namespace System.Net.Sockets
         }
 
         // Sets the local address of a multicast group.
-        public IPAddress LocalAddress
+        public IPAddress? LocalAddress
         {
             get
             {
@@ -124,7 +124,7 @@ namespace System.Net.Sockets
                 throw new ArgumentOutOfRangeException(nameof(ifindex));
             }
 
-            Group = group;
+            _group = group;
             InterfaceIndex = ifindex;
         }
 
@@ -137,7 +137,7 @@ namespace System.Net.Sockets
                 throw new ArgumentNullException(nameof(group));
             }
 
-            Group = group;
+            _group = group;
             InterfaceIndex = 0;
         }
 
index 1eac93c..e301f6d 100644 (file)
@@ -13,11 +13,11 @@ namespace System.Net.Sockets
     // on behalf of a single user call to ConnectAsync with a DnsEndPoint
     internal abstract class MultipleConnectAsync
     {
-        protected SocketAsyncEventArgs _userArgs;
-        protected SocketAsyncEventArgs _internalArgs;
+        protected SocketAsyncEventArgs? _userArgs;
+        protected SocketAsyncEventArgs? _internalArgs;
 
-        protected DnsEndPoint _endPoint;
-        protected IPAddress[] _addressList;
+        protected DnsEndPoint? _endPoint;
+        protected IPAddress[]? _addressList;
         protected int _nextAddress;
 
         private enum State
@@ -90,7 +90,7 @@ namespace System.Net.Sockets
         // false if it has failed synchronously.
         private bool DoDnsCallback(IAsyncResult result, bool sync)
         {
-            Exception exception = null;
+            Exception? exception = null;
 
             lock (_lockObject)
             {
@@ -127,7 +127,7 @@ namespace System.Net.Sockets
 
                     _internalArgs = new SocketAsyncEventArgs();
                     _internalArgs.Completed += InternalConnectCallback;
-                    _internalArgs.CopyBufferFrom(_userArgs);
+                    _internalArgs.CopyBufferFrom(_userArgs!);
 
                     exception = AttemptConnection();
 
@@ -152,9 +152,9 @@ namespace System.Net.Sockets
 
         // Callback which fires when an internal connection attempt completes.
         // If it failed and there are more addresses to try, do it.
-        private void InternalConnectCallback(object sender, SocketAsyncEventArgs args)
+        private void InternalConnectCallback(object? sender, SocketAsyncEventArgs args)
         {
-            Exception exception = null;
+            Exception? exception = null;
 
             lock (_lockObject)
             {
@@ -187,7 +187,7 @@ namespace System.Net.Sockets
 
                         // Keep track of this because it will be overwritten by AttemptConnection
                         SocketError currentFailure = args.SocketError;
-                        Exception connectException = AttemptConnection();
+                        Exception? connectException = AttemptConnection();
 
                         if (connectException == null)
                         {
@@ -196,7 +196,7 @@ namespace System.Net.Sockets
                         }
                         else
                         {
-                            SocketException socketException = connectException as SocketException;
+                            SocketException? socketException = connectException as SocketException;
                             if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
                             {
                                 // If the error is NoData, that means there are no more IPAddresses to attempt
@@ -226,21 +226,21 @@ namespace System.Net.Sockets
 
         // Called to initiate a connection attempt to the next address in the list.  Returns an exception
         // if the attempt failed synchronously, or null if it was successfully initiated.
-        private Exception AttemptConnection()
+        private Exception? AttemptConnection()
         {
             try
             {
-                Socket attemptSocket;
-                IPAddress attemptAddress = GetNextAddress(out attemptSocket);
+                Socket? attemptSocket;
+                IPAddress? attemptAddress = GetNextAddress(out attemptSocket);
 
                 if (attemptAddress == null)
                 {
                     return new SocketException((int)SocketError.NoData);
                 }
 
-                _internalArgs.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint.Port);
+                _internalArgs!.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint!.Port);
 
-                return AttemptConnection(attemptSocket, _internalArgs);
+                return AttemptConnection(attemptSocket!, _internalArgs);
             }
             catch (Exception e)
             {
@@ -252,7 +252,7 @@ namespace System.Net.Sockets
             }
         }
 
-        private Exception AttemptConnection(Socket attemptSocket, SocketAsyncEventArgs args)
+        private Exception? AttemptConnection(Socket attemptSocket, SocketAsyncEventArgs args)
         {
             try
             {
@@ -286,7 +286,7 @@ namespace System.Net.Sockets
         private void Succeed()
         {
             OnSucceed();
-            _userArgs.FinishWrapperConnectSuccess(_internalArgs.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
+            _userArgs!.FinishWrapperConnectSuccess(_internalArgs!.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
             _internalArgs.Dispose();
         }
 
@@ -315,10 +315,10 @@ namespace System.Net.Sockets
                 _internalArgs.Dispose();
             }
 
-            SocketException socketException = e as SocketException;
+            SocketException? socketException = e as SocketException;
             if (socketException != null)
             {
-                _userArgs.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None);
+                _userArgs!.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None);
             }
             else
             {
@@ -335,7 +335,7 @@ namespace System.Net.Sockets
                 _internalArgs.Dispose();
             }
 
-            _userArgs.FinishConnectByNameAsyncFailure(e, 0, SocketFlags.None);
+            _userArgs!.FinishConnectByNameAsyncFailure(e, 0, SocketFlags.None);
         }
 
         public void Cancel()
@@ -396,12 +396,12 @@ namespace System.Net.Sockets
         }
 
         // Call AsyncFail on a threadpool thread so it's asynchronous with respect to Cancel().
-        private void CallAsyncFail(object ignored)
+        private void CallAsyncFail(object? ignored)
         {
             AsyncFail(new SocketException((int)SocketError.OperationAborted));
         }
 
-        protected abstract IPAddress GetNextAddress(out Socket attemptSocket);
+        protected abstract IPAddress? GetNextAddress(out Socket? attemptSocket);
     }
 
     // Used when the instance ConnectAsync method is called, or when the DnsEndPoint specified
@@ -418,14 +418,14 @@ namespace System.Net.Sockets
             _userSocket = userSocket;
         }
 
-        protected override IPAddress GetNextAddress(out Socket attemptSocket)
+        protected override IPAddress? GetNextAddress(out Socket? attemptSocket)
         {
             _socket.ReplaceHandleIfNecessaryAfterFailedConnect();
 
-            IPAddress rval = null;
+            IPAddress? rval = null;
             do
             {
-                if (_nextAddress >= _addressList.Length)
+                if (_nextAddress >= _addressList!.Length)
                 {
                     attemptSocket = null;
                     return null;
@@ -458,8 +458,8 @@ namespace System.Net.Sockets
     // ahead of time, so we create both IPv4 and IPv6 sockets.
     internal sealed class DualSocketMultipleConnectAsync : MultipleConnectAsync
     {
-        private readonly Socket _socket4;
-        private readonly Socket _socket6;
+        private readonly Socket? _socket4;
+        private readonly Socket? _socket6;
 
         public DualSocketMultipleConnectAsync(SocketType socketType, ProtocolType protocolType)
         {
@@ -473,14 +473,14 @@ namespace System.Net.Sockets
             }
         }
 
-        protected override IPAddress GetNextAddress(out Socket attemptSocket)
+        protected override IPAddress? GetNextAddress(out Socket? attemptSocket)
         {
-            IPAddress rval = null;
+            IPAddress? rval = null;
             attemptSocket = null;
 
             while (attemptSocket == null)
             {
-                if (_nextAddress >= _addressList.Length)
+                if (_nextAddress >= _addressList!.Length)
                 {
                     return null;
                 }
index 373c913..447cdec 100644 (file)
@@ -18,7 +18,7 @@ namespace System.Net
         private const int NotLoggedFileId = ConnectedAsyncDnsId + 1;
 
         [NonEvent]
-        public static void Accepted(Socket socket, object remoteEp, object localEp)
+        public static void Accepted(Socket socket, object? remoteEp, object? localEp)
         {
             if (IsEnabled)
             {
@@ -33,7 +33,7 @@ namespace System.Net
         }
 
         [NonEvent]
-        public static void Connected(Socket socket, object localEp, object remoteEp)
+        public static void Connected(Socket socket, object? localEp, object? remoteEp)
         {
             if (IsEnabled)
             {
@@ -82,7 +82,7 @@ namespace System.Net
         /// <param name="buffer">The buffer to be logged.</param>
         /// <param name="memberName">The calling member.</param>
         [NonEvent]
-        public static void DumpBuffer(object thisOrContextObject, Memory<byte> buffer, [CallerMemberName] string memberName = null)
+        public static void DumpBuffer(object thisOrContextObject, Memory<byte> buffer, [CallerMemberName] string? memberName = null)
         {
             DumpBuffer(thisOrContextObject, buffer, 0, buffer.Length, memberName);
         }
@@ -94,7 +94,7 @@ namespace System.Net
         /// <param name="count">The number of bytes to log.</param>
         /// <param name="memberName">The calling member.</param>
         [NonEvent]
-        public static void DumpBuffer(object thisOrContextObject, Memory<byte> buffer, int offset, int count, [CallerMemberName] string memberName = null)
+        public static void DumpBuffer(object thisOrContextObject, Memory<byte> buffer, int offset, int count, [CallerMemberName] string? memberName = null)
         {
             if (IsEnabled)
             {
@@ -106,7 +106,7 @@ namespace System.Net
 
                 buffer = buffer.Slice(offset, Math.Min(count, MaxDumpSize));
                 byte[] slice = MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> arraySegment) && arraySegment.Offset == 0 && arraySegment.Count == buffer.Length ?
-                    arraySegment.Array :
+                    arraySegment.Array! :
                     buffer.ToArray();
 
                 Log.DumpBuffer(IdOf(thisOrContextObject), memberName, slice);
index d15d771..78f8781 100644 (file)
@@ -124,7 +124,7 @@ namespace System.Net.Sockets
                 using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
                 {
 #endif
-                    int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
+                    int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout)!;
                     if (timeout == 0)
                     {
                         return -1;
@@ -161,7 +161,7 @@ namespace System.Net.Sockets
                 using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
                 {
 #endif
-                    int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
+                    int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout)!;
                     if (timeout == 0)
                     {
                         return -1;
@@ -482,7 +482,7 @@ namespace System.Net.Sockets
         // Returns:
         //
         //     An IASyncResult, representing the read.
-        public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
+        public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state)
         {
 #if DEBUG
             using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
@@ -581,7 +581,7 @@ namespace System.Net.Sockets
         // Returns:
         //
         //     An IASyncResult, representing the write.
-        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
+        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state)
         {
 #if DEBUG
             using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
index 4a027bb..f70099e 100644 (file)
@@ -19,7 +19,7 @@ namespace System.Net.Sockets
             return _socketAddressSize;
         }
 
-        public void CompletionCallback(int numBytes, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError errorCode)
+        public void CompletionCallback(int numBytes, byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError errorCode)
         {
             if (_socketAddress != null)
             {
index e6468df..409f450 100644 (file)
@@ -15,16 +15,16 @@ namespace System.Net.Sockets
     internal partial class OverlappedAsyncResult : BaseOverlappedAsyncResult
     {
         internal WSABuffer _singleBuffer;
-        internal WSABuffer[] _wsaBuffers;
+        internal WSABuffer[]? _wsaBuffers;
 
         internal IntPtr GetSocketAddressPtr()
         {
-            return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, 0);
+            return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress!.Buffer, 0);
         }
 
         internal IntPtr GetSocketAddressSizePtr()
         {
-            return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, _socketAddress.GetAddressSizeOffset());
+            return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress!.Buffer, _socketAddress.GetAddressSizeOffset());
         }
 
         internal unsafe int GetSocketAddressSize()
@@ -38,14 +38,13 @@ namespace System.Net.Sockets
         // These calls are outside the runtime and are unmanaged code, so we need
         // to prepare specific structures and ints that lie in unmanaged memory
         // since the overlapped calls may complete asynchronously.
-        internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, Internals.SocketAddress socketAddress)
+        internal void SetUnmanagedStructures(byte[] buffer, int offset, int size, Internals.SocketAddress? socketAddress)
         {
             // Fill in Buffer Array structure that will be used for our send/recv Buffer
             _socketAddress = socketAddress;
             if (_socketAddress != null)
             {
-                object[] objectsToPin = null;
-                objectsToPin = new object[2];
+                object[] objectsToPin = new object[2];
                 objectsToPin[0] = buffer;
 
                 _socketAddress.CopyAddressSizeIntoBuffer();
@@ -81,7 +80,7 @@ namespace System.Net.Sockets
             object[] objectsToPin = new object[count];
             for (int i = 0; i < count; i++)
             {
-                objectsToPin[i] = buffersCopy[i].Array;
+                objectsToPin[i] = buffersCopy[i].Array!;
             }
 
             base.SetUnmanagedStructures(objectsToPin);
@@ -89,7 +88,7 @@ namespace System.Net.Sockets
             for (int i = 0; i < count; i++)
             {
                 _wsaBuffers[i].Length = buffersCopy[i].Count;
-                _wsaBuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffersCopy[i].Array, buffersCopy[i].Offset);
+                _wsaBuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffersCopy[i].Array!, buffersCopy[i].Offset);
             }
         }
 
@@ -98,7 +97,7 @@ namespace System.Net.Sockets
         // 1) completed synchronously.
         // 2) was pended.
         // 3) failed.
-        internal override object PostCompletion(int numBytes)
+        internal override object? PostCompletion(int numBytes)
         {
             if (ErrorCode == 0 && NetEventSource.IsEnabled)
             {
index 3048115..991f11a 100644 (file)
@@ -10,14 +10,14 @@ namespace System.Net.Sockets
     // from the BeginSend, BeginSendTo, BeginReceive, BeginReceiveFrom calls.
     internal partial class OverlappedAsyncResult : BaseOverlappedAsyncResult
     {
-        private Internals.SocketAddress _socketAddress;
+        private Internals.SocketAddress? _socketAddress;
 
-        internal OverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback) :
+        internal OverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback) :
             base(socket, asyncState, asyncCallback)
         {
         }
 
-        internal Internals.SocketAddress SocketAddress
+        internal Internals.SocketAddress? SocketAddress
         {
             get { return _socketAddress; }
             set { _socketAddress = value; }
@@ -26,11 +26,11 @@ namespace System.Net.Sockets
 
     internal sealed class OriginalAddressOverlappedAsyncResult : OverlappedAsyncResult
     {
-        internal OriginalAddressOverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback) :
+        internal OriginalAddressOverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback) :
             base(socket, asyncState, asyncCallback)
         {
         }
 
-        internal Internals.SocketAddress SocketAddressOriginal { get; set; }
+        internal Internals.SocketAddress? SocketAddressOriginal { get; set; }
     }
 }
index 003fb24..f9da58f 100644 (file)
@@ -11,13 +11,13 @@ namespace System.Net.Sockets
     {
         private Interop.Winsock.WSAMsg* _message;
         private WSABuffer* _wsaBuffer;
-        private byte[] _wsaBufferArray;
-        private byte[] _controlBuffer;
-        internal byte[] _messageBuffer;
+        private byte[]? _wsaBufferArray;
+        private byte[]? _controlBuffer;
+        internal byte[]? _messageBuffer;
 
         private IntPtr GetSocketAddressSizePtr()
         {
-            return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, _socketAddress.GetAddressSizeOffset());
+            return Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress!.Buffer, _socketAddress.GetAddressSizeOffset());
         }
 
         internal unsafe int GetSocketAddressSize()
@@ -91,12 +91,13 @@ namespace System.Net.Sockets
 
         private unsafe void InitIPPacketInformation()
         {
-            if (_controlBuffer.Length == sizeof(Interop.Winsock.ControlData))
+            int? controlBufferLength = _controlBuffer?.Length;
+            if (controlBufferLength == sizeof(Interop.Winsock.ControlData))
             {
                 // IPv4
                 _ipPacketInformation = SocketPal.GetIPPacketInformation((Interop.Winsock.ControlData*)_message->controlBuffer.Pointer);
             }
-            else if (_controlBuffer.Length == sizeof(Interop.Winsock.ControlDataIPv6))
+            else if (controlBufferLength == sizeof(Interop.Winsock.ControlDataIPv6))
             {
                 // IPv6
                 _ipPacketInformation = SocketPal.GetIPPacketInformation((Interop.Winsock.ControlDataIPv6*)_message->controlBuffer.Pointer);
@@ -114,7 +115,7 @@ namespace System.Net.Sockets
             base.ForceReleaseUnmanagedStructures();
         }
 
-        internal override object PostCompletion(int numBytes)
+        internal override object? PostCompletion(int numBytes)
         {
             InitIPPacketInformation();
             if (ErrorCode == 0 && NetEventSource.IsEnabled)
index 4606292..ad3bf3b 100644 (file)
@@ -6,17 +6,17 @@ namespace System.Net.Sockets
 {
     internal unsafe sealed partial class ReceiveMessageOverlappedAsyncResult : BaseOverlappedAsyncResult
     {
-        private Internals.SocketAddress _socketAddressOriginal;
-        private Internals.SocketAddress _socketAddress;
+        private Internals.SocketAddress? _socketAddressOriginal;
+        private Internals.SocketAddress? _socketAddress;
 
         private SocketFlags _socketFlags;
         private IPPacketInformation _ipPacketInformation;
 
-        internal ReceiveMessageOverlappedAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback) :
+        internal ReceiveMessageOverlappedAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback) :
             base(socket, asyncState, asyncCallback)
         { }
 
-        internal Internals.SocketAddress SocketAddress
+        internal Internals.SocketAddress? SocketAddress
         {
             get
             {
@@ -28,7 +28,7 @@ namespace System.Net.Sockets
             }
         }
 
-        internal Internals.SocketAddress SocketAddressOriginal
+        internal Internals.SocketAddress? SocketAddressOriginal
         {
             get
             {
index 49eb5a1..39bbe58 100644 (file)
@@ -17,7 +17,7 @@ namespace System.Net.Sockets
         private int _sendTimeout = -1;
         private bool _nonBlocking;
         private bool _underlyingHandleNonBlocking;
-        private SocketAsyncContext _asyncContext;
+        private SocketAsyncContext? _asyncContext;
 
         private TrackedSocketOptions _trackedOptions;
         internal bool LastConnectFailed { get; set; }
@@ -104,7 +104,7 @@ namespace System.Net.Sockets
                     Interlocked.CompareExchange(ref _asyncContext, new SocketAsyncContext(this), null);
                 }
 
-                return _asyncContext;
+                return _asyncContext!;
             }
         }
 
index 11c4ad6..b821bed 100644 (file)
@@ -10,12 +10,12 @@ namespace System.Net.Sockets
 {
     public partial class SafeSocketHandle
     {
-        private ThreadPoolBoundHandle _iocpBoundHandle;
+        private ThreadPoolBoundHandle? _iocpBoundHandle;
         private bool _skipCompletionPortOnSuccess;
 
         internal void SetExposed() { /* nop */ }
 
-        internal ThreadPoolBoundHandle IOCPBoundHandle
+        internal ThreadPoolBoundHandle? IOCPBoundHandle
         {
             get
             {
@@ -23,7 +23,7 @@ namespace System.Net.Sockets
             }
         }
 
-        internal ThreadPoolBoundHandle GetThreadPoolBoundHandle() => !_released ? _iocpBoundHandle : null;
+        internal ThreadPoolBoundHandle? GetThreadPoolBoundHandle() => !_released ? _iocpBoundHandle : null;
 
         // Binds the Socket Win32 Handle to the ThreadPool's CompletionPort.
         internal ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandle(bool trySkipCompletionPortOnSuccess)
@@ -40,7 +40,7 @@ namespace System.Net.Sockets
 
             lock (this)
             {
-                ThreadPoolBoundHandle boundHandle = _iocpBoundHandle;
+                ThreadPoolBoundHandle? boundHandle = _iocpBoundHandle;
 
                 if (boundHandle == null)
                 {
@@ -208,7 +208,7 @@ namespace System.Net.Sockets
             return errorCode;
         }
 
-        private static void ThrowSocketDisposedException(Exception innerException = null) =>
+        private static void ThrowSocketDisposedException(Exception? innerException = null) =>
             throw new ObjectDisposedException(typeof(Socket).FullName, innerException);
     }
 }
index b17b104..eb56541 100644 (file)
@@ -106,7 +106,7 @@ namespace System.Net.Sockets
             Initialize(null, null, buffer, offset, count, endOfPacket);
         }
 
-        private void Initialize(string filePath, FileStream fileStream, byte[] buffer, long offset, int count, bool endOfPacket)
+        private void Initialize(string? filePath, FileStream? fileStream, byte[]? buffer, long offset, int count, bool endOfPacket)
         {
             FilePath = filePath;
             FileStream = fileStream;
@@ -116,11 +116,11 @@ namespace System.Net.Sockets
             EndOfPacket = endOfPacket;
         }
 
-        public string FilePath { get; private set; }
+        public string? FilePath { get; private set; }
 
-        public FileStream FileStream { get; private set; }
+        public FileStream? FileStream { get; private set; }
 
-        public byte[] Buffer { get; private set; }
+        public byte[]? Buffer { get; private set; }
 
         public int Count { get; private set; }
 
index ce8bf88..3a8593d 100644 (file)
@@ -29,11 +29,11 @@ namespace System.Net.Sockets
     public partial class Socket
     {
         /// <summary>Handler for completed AcceptAsync operations.</summary>
-        private static readonly EventHandler<SocketAsyncEventArgs> AcceptCompletedHandler = (s, e) => CompleteAccept((Socket)s, (TaskSocketAsyncEventArgs<Socket>)e);
+        private static readonly EventHandler<SocketAsyncEventArgs> AcceptCompletedHandler = (s, e) => CompleteAccept((Socket)s!, (TaskSocketAsyncEventArgs<Socket>)e);
         /// <summary>Handler for completed ReceiveAsync operations.</summary>
-        private static readonly EventHandler<SocketAsyncEventArgs> ReceiveCompletedHandler = (s, e) => CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: true);
+        private static readonly EventHandler<SocketAsyncEventArgs> ReceiveCompletedHandler = (s, e) => CompleteSendReceive((Socket)s!, (Int32TaskSocketAsyncEventArgs)e, isReceive: true);
         /// <summary>Handler for completed SendAsync operations.</summary>
-        private static readonly EventHandler<SocketAsyncEventArgs> SendCompletedHandler = (s, e) => CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: false);
+        private static readonly EventHandler<SocketAsyncEventArgs> SendCompletedHandler = (s, e) => CompleteSendReceive((Socket)s!, (Int32TaskSocketAsyncEventArgs)e, isReceive: false);
         /// <summary>
         /// Sentinel that can be stored into one of the Socket cached fields to indicate that an instance
         /// was previously created but is currently being used by another concurrent operation.
@@ -48,14 +48,14 @@ namespace System.Net.Sockets
         private static readonly Task<int> s_zeroTask = Task.FromResult(0);
 
         /// <summary>Cached event args used with Task-based async operations.</summary>
-        private CachedEventArgs _cachedTaskEventArgs;
+        private CachedEventArgs? _cachedTaskEventArgs;
 
         private CachedEventArgs EventArgs => LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs, () => new CachedEventArgs());
 
-        internal Task<Socket> AcceptAsync(Socket acceptSocket)
+        internal Task<Socket> AcceptAsync(Socket? acceptSocket)
         {
             // Get any cached SocketAsyncEventArg we may have.
-            TaskSocketAsyncEventArgs<Socket> saea = Interlocked.Exchange(ref EventArgs.TaskAccept, s_rentedSocketSentinel);
+            TaskSocketAsyncEventArgs<Socket>? saea = Interlocked.Exchange(ref EventArgs.TaskAccept, s_rentedSocketSentinel);
             if (saea == s_rentedSocketSentinel)
             {
                 // An instance was once created (or is currently being created elsewhere), but some other
@@ -94,7 +94,7 @@ namespace System.Net.Sockets
             {
                 // The operation completed synchronously.  Get a task for it.
                 t = saea.SocketError == SocketError.Success ?
-                    Task.FromResult(saea.AcceptSocket) :
+                    Task.FromResult(saea.AcceptSocket!) :
                     Task.FromException<Socket>(GetException(saea.SocketError));
 
                 // There won't be a callback, and we're done with the SAEA, so return it to the pool.
@@ -105,13 +105,13 @@ namespace System.Net.Sockets
         }
 
         /// <summary>Implements Task-returning AcceptAsync on top of Begin/EndAsync.</summary>
-        private Task<Socket> AcceptAsyncApm(Socket acceptSocket)
+        private Task<Socket> AcceptAsyncApm(Socket? acceptSocket)
         {
             var tcs = new TaskCompletionSource<Socket>(this);
             BeginAccept(acceptSocket, 0, iar =>
             {
-                var innerTcs = (TaskCompletionSource<Socket>)iar.AsyncState;
-                try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndAccept(iar)); }
+                var innerTcs = (TaskCompletionSource<Socket>)iar.AsyncState!;
+                try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndAccept(iar)); }
                 catch (Exception e) { innerTcs.TrySetException(e); }
             }, tcs);
             return tcs.Task;
@@ -122,10 +122,10 @@ namespace System.Net.Sockets
             var tcs = new TaskCompletionSource<bool>(this);
             BeginConnect(remoteEP, iar =>
             {
-                var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
+                var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState!;
                 try
                 {
-                    ((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
+                    ((Socket)innerTcs.Task.AsyncState!).EndConnect(iar);
                     innerTcs.TrySetResult(true);
                 }
                 catch (Exception e) { innerTcs.TrySetException(e); }
@@ -138,10 +138,10 @@ namespace System.Net.Sockets
             var tcs = new TaskCompletionSource<bool>(this);
             BeginConnect(address, port, iar =>
             {
-                var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
+                var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState!;
                 try
                 {
-                    ((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
+                    ((Socket)innerTcs.Task.AsyncState!).EndConnect(iar);
                     innerTcs.TrySetResult(true);
                 }
                 catch (Exception e) { innerTcs.TrySetException(e); }
@@ -154,10 +154,10 @@ namespace System.Net.Sockets
             var tcs = new TaskCompletionSource<bool>(this);
             BeginConnect(addresses, port, iar =>
             {
-                var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
+                var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState!;
                 try
                 {
-                    ((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
+                    ((Socket)innerTcs.Task.AsyncState!).EndConnect(iar);
                     innerTcs.TrySetResult(true);
                 }
                 catch (Exception e) { innerTcs.TrySetException(e); }
@@ -170,10 +170,10 @@ namespace System.Net.Sockets
             var tcs = new TaskCompletionSource<bool>(this);
             BeginConnect(host, port, iar =>
             {
-                var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState;
+                var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState!;
                 try
                 {
-                    ((Socket)innerTcs.Task.AsyncState).EndConnect(iar);
+                    ((Socket)innerTcs.Task.AsyncState!).EndConnect(iar);
                     innerTcs.TrySetResult(true);
                 }
                 catch (Exception e) { innerTcs.TrySetException(e); }
@@ -218,10 +218,10 @@ namespace System.Net.Sockets
             {
                 // We were able to extract the underlying byte[] from the Memory<byte>. Use it.
                 var tcs = new TaskCompletionSource<int>(this);
-                BeginReceive(bufferArray.Array, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
+                BeginReceive(bufferArray.Array!, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
                 {
-                    var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
-                    try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndReceive(iar)); }
+                    var innerTcs = (TaskCompletionSource<int>)iar.AsyncState!;
+                    try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndReceive(iar)); }
                     catch (Exception e) { innerTcs.TrySetException(e); }
                 }, tcs);
                 return tcs.Task;
@@ -234,10 +234,10 @@ namespace System.Net.Sockets
                 var tcs = new TaskCompletionSource<int>(this);
                 BeginReceive(poolArray, 0, buffer.Length, socketFlags, iar =>
                 {
-                    var state = (Tuple<TaskCompletionSource<int>, Memory<byte>, byte[]>)iar.AsyncState;
+                    var state = (Tuple<TaskCompletionSource<int>, Memory<byte>, byte[]>)iar.AsyncState!;
                     try
                     {
-                        int bytesCopied = ((Socket)state.Item1.Task.AsyncState).EndReceive(iar);
+                        int bytesCopied = ((Socket)state.Item1.Task.AsyncState!).EndReceive(iar);
                         new ReadOnlyMemory<byte>(state.Item3, 0, bytesCopied).Span.CopyTo(state.Item2.Span);
                         state.Item1.TrySetResult(bytesCopied);
                     }
@@ -259,7 +259,7 @@ namespace System.Net.Sockets
             // Validate the arguments.
             ValidateBuffersList(buffers);
 
-            Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: true);
+            Int32TaskSocketAsyncEventArgs? saea = RentSocketAsyncEventArgs(isReceive: true);
             if (saea != null)
             {
                 // We got a cached instance. Configure the buffer list and initate the operation.
@@ -280,8 +280,8 @@ namespace System.Net.Sockets
             var tcs = new TaskCompletionSource<int>(this);
             BeginReceive(buffers, socketFlags, iar =>
             {
-                var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
-                try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndReceive(iar)); }
+                var innerTcs = (TaskCompletionSource<int>)iar.AsyncState!;
+                try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndReceive(iar)); }
                 catch (Exception e) { innerTcs.TrySetException(e); }
             }, tcs);
             return tcs.Task;
@@ -290,12 +290,12 @@ namespace System.Net.Sockets
         internal Task<SocketReceiveFromResult> ReceiveFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)
         {
             var tcs = new StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>(this) { _field1 = remoteEndPoint };
-            BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref tcs._field1, iar =>
+            BeginReceiveFrom(buffer.Array!, buffer.Offset, buffer.Count, socketFlags, ref tcs._field1, iar =>
             {
-                var innerTcs = (StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>)iar.AsyncState;
+                var innerTcs = (StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>)iar.AsyncState!;
                 try
                 {
-                    int receivedBytes = ((Socket)innerTcs.Task.AsyncState).EndReceiveFrom(iar, ref innerTcs._field1);
+                    int receivedBytes = ((Socket)innerTcs.Task.AsyncState!).EndReceiveFrom(iar, ref innerTcs._field1);
                     innerTcs.TrySetResult(new SocketReceiveFromResult
                     {
                         ReceivedBytes = receivedBytes,
@@ -310,13 +310,13 @@ namespace System.Net.Sockets
         internal Task<SocketReceiveMessageFromResult> ReceiveMessageFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)
         {
             var tcs = new StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>(this) { _field1 = socketFlags, _field2 = remoteEndPoint };
-            BeginReceiveMessageFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref tcs._field2, iar =>
+            BeginReceiveMessageFrom(buffer.Array!, buffer.Offset, buffer.Count, socketFlags, ref tcs._field2, iar =>
             {
-                var innerTcs = (StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>)iar.AsyncState;
+                var innerTcs = (StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>)iar.AsyncState!;
                 try
                 {
                     IPPacketInformation ipPacketInformation;
-                    int receivedBytes = ((Socket)innerTcs.Task.AsyncState).EndReceiveMessageFrom(iar, ref innerTcs._field1, ref innerTcs._field2, out ipPacketInformation);
+                    int receivedBytes = ((Socket)innerTcs.Task.AsyncState!).EndReceiveMessageFrom(iar, ref innerTcs._field1, ref innerTcs._field2, out ipPacketInformation);
                     innerTcs.TrySetResult(new SocketReceiveMessageFromResult
                     {
                         ReceivedBytes = receivedBytes,
@@ -390,10 +390,10 @@ namespace System.Net.Sockets
             if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> bufferArray))
             {
                 var tcs = new TaskCompletionSource<int>(this);
-                BeginSend(bufferArray.Array, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
+                BeginSend(bufferArray.Array!, bufferArray.Offset, bufferArray.Count, socketFlags, iar =>
                 {
-                    var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
-                    try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSend(iar)); }
+                    var innerTcs = (TaskCompletionSource<int>)iar.AsyncState!;
+                    try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndSend(iar)); }
                     catch (Exception e) { innerTcs.TrySetException(e); }
                 }, tcs);
                 return tcs.Task;
@@ -407,10 +407,10 @@ namespace System.Net.Sockets
                 var tcs = new TaskCompletionSource<int>(this);
                 BeginSend(poolArray, 0, buffer.Length, socketFlags, iar =>
                 {
-                    var state = (Tuple<TaskCompletionSource<int>, byte[]>)iar.AsyncState;
+                    var state = (Tuple<TaskCompletionSource<int>, byte[]>)iar.AsyncState!;
                     try
                     {
-                        state.Item1.TrySetResult(((Socket)state.Item1.Task.AsyncState).EndSend(iar));
+                        state.Item1.TrySetResult(((Socket)state.Item1.Task.AsyncState!).EndSend(iar));
                     }
                     catch (Exception e)
                     {
@@ -430,7 +430,7 @@ namespace System.Net.Sockets
             // Validate the arguments.
             ValidateBuffersList(buffers);
 
-            Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: false);
+            Int32TaskSocketAsyncEventArgs? saea = RentSocketAsyncEventArgs(isReceive: false);
             if (saea != null)
             {
                 // We got a cached instance. Configure the buffer list and initate the operation.
@@ -451,8 +451,8 @@ namespace System.Net.Sockets
             var tcs = new TaskCompletionSource<int>(this);
             BeginSend(buffers, socketFlags, iar =>
             {
-                var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
-                try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSend(iar)); }
+                var innerTcs = (TaskCompletionSource<int>)iar.AsyncState!;
+                try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndSend(iar)); }
                 catch (Exception e) { innerTcs.TrySetException(e); }
             }, tcs);
             return tcs.Task;
@@ -461,10 +461,10 @@ namespace System.Net.Sockets
         internal Task<int> SendToAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEP)
         {
             var tcs = new TaskCompletionSource<int>(this);
-            BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, socketFlags, remoteEP, iar =>
+            BeginSendTo(buffer.Array!, buffer.Offset, buffer.Count, socketFlags, remoteEP, iar =>
             {
-                var innerTcs = (TaskCompletionSource<int>)iar.AsyncState;
-                try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSendTo(iar)); }
+                var innerTcs = (TaskCompletionSource<int>)iar.AsyncState!;
+                try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState!).EndSendTo(iar)); }
                 catch (Exception e) { innerTcs.TrySetException(e); }
             }, tcs);
             return tcs.Task;
@@ -578,7 +578,7 @@ namespace System.Net.Sockets
         {
             // Pull the relevant state off of the SAEA
             SocketError error = saea.SocketError;
-            Socket acceptSocket = saea.AcceptSocket;
+            Socket? acceptSocket = saea.AcceptSocket;
 
             // Synchronize with the initiating thread. If the synchronous caller already got what
             // it needs from the SAEA, then we can return it to the pool now. Otherwise, it'll be
@@ -593,7 +593,7 @@ namespace System.Net.Sockets
             // Complete the builder/task with the results.
             if (error == SocketError.Success)
             {
-                builder.SetResult(acceptSocket);
+                builder.SetResult(acceptSocket!);
             }
             else
             {
@@ -641,11 +641,11 @@ namespace System.Net.Sockets
 
         /// <summary>Rents a <see cref="Int32TaskSocketAsyncEventArgs"/> for immediate use.</summary>
         /// <param name="isReceive">true if this instance will be used for a receive; false if for sends.</param>
-        private Int32TaskSocketAsyncEventArgs RentSocketAsyncEventArgs(bool isReceive)
+        private Int32TaskSocketAsyncEventArgs? RentSocketAsyncEventArgs(bool isReceive)
         {
             // Get any cached SocketAsyncEventArg we may have.
             CachedEventArgs cea = EventArgs;
-            Int32TaskSocketAsyncEventArgs saea = isReceive ?
+            Int32TaskSocketAsyncEventArgs? saea = isReceive ?
                 Interlocked.Exchange(ref cea.TaskReceive, s_rentedInt32Sentinel) :
                 Interlocked.Exchange(ref cea.TaskSend, s_rentedInt32Sentinel);
 
@@ -720,7 +720,7 @@ namespace System.Net.Sockets
         /// <summary>Dispose of any cached <see cref="Int32TaskSocketAsyncEventArgs"/> instances.</summary>
         private void DisposeCachedTaskSocketAsyncEventArgs()
         {
-            CachedEventArgs cea = _cachedTaskEventArgs;
+            CachedEventArgs? cea = _cachedTaskEventArgs;
             if (cea != null)
             {
                 Interlocked.Exchange(ref cea.TaskAccept, s_rentedSocketSentinel)?.Dispose();
@@ -734,14 +734,14 @@ namespace System.Net.Sockets
         /// <summary>A TaskCompletionSource that carries an extra field of strongly-typed state.</summary>
         private class StateTaskCompletionSource<TField1, TResult> : TaskCompletionSource<TResult>
         {
-            internal TField1 _field1;
+            internal TField1 _field1 = default!; // always set on construction
             public StateTaskCompletionSource(object baseState) : base(baseState) { }
         }
 
         /// <summary>A TaskCompletionSource that carries several extra fields of strongly-typed state.</summary>
         private class StateTaskCompletionSource<TField1, TField2, TResult> : StateTaskCompletionSource<TField1, TResult>
         {
-            internal TField2 _field2;
+            internal TField2 _field2 = default!; // always set on construction
             public StateTaskCompletionSource(object baseState) : base(baseState) { }
         }
 
@@ -749,15 +749,15 @@ namespace System.Net.Sockets
         private sealed class CachedEventArgs
         {
             /// <summary>Cached instance for accept operations.</summary>
-            public TaskSocketAsyncEventArgs<Socket> TaskAccept;
+            public TaskSocketAsyncEventArgs<Socket>? TaskAccept;
             /// <summary>Cached instance for receive operations that return <see cref="Task{Int32}"/>.</summary>
-            public Int32TaskSocketAsyncEventArgs TaskReceive;
+            public Int32TaskSocketAsyncEventArgs? TaskReceive;
             /// <summary>Cached instance for send operations that return <see cref="Task{Int32}"/>.</summary>
-            public Int32TaskSocketAsyncEventArgs TaskSend;
+            public Int32TaskSocketAsyncEventArgs? TaskSend;
             /// <summary>Cached instance for receive operations that return <see cref="ValueTask{Int32}"/>.</summary>
-            public AwaitableSocketAsyncEventArgs ValueTaskReceive;
+            public AwaitableSocketAsyncEventArgs? ValueTaskReceive;
             /// <summary>Cached instance for send operations that return <see cref="ValueTask{Int32}"/>.</summary>
-            public AwaitableSocketAsyncEventArgs ValueTaskSend;
+            public AwaitableSocketAsyncEventArgs? ValueTaskSend;
         }
 
         /// <summary>A SocketAsyncEventArgs with an associated async method builder.</summary>
@@ -808,9 +808,9 @@ namespace System.Net.Sockets
         {
             internal static readonly AwaitableSocketAsyncEventArgs Reserved = new AwaitableSocketAsyncEventArgs() { _continuation = null };
             /// <summary>Sentinel object used to indicate that the operation has completed prior to OnCompleted being called.</summary>
-            private static readonly Action<object> s_completedSentinel = new Action<object>(state => throw new InvalidOperationException(SR.Format(SR.net_sockets_valuetaskmisuse, nameof(s_completedSentinel))));
+            private static readonly Action<object?> s_completedSentinel = new Action<object?>(state => throw new InvalidOperationException(SR.Format(SR.net_sockets_valuetaskmisuse, nameof(s_completedSentinel))));
             /// <summary>Sentinel object used to indicate that the instance is available for use.</summary>
-            private static readonly Action<object> s_availableSentinel = new Action<object>(state => throw new InvalidOperationException(SR.Format(SR.net_sockets_valuetaskmisuse, nameof(s_availableSentinel))));
+            private static readonly Action<object?> s_availableSentinel = new Action<object?>(state => throw new InvalidOperationException(SR.Format(SR.net_sockets_valuetaskmisuse, nameof(s_availableSentinel))));
             /// <summary>
             /// <see cref="s_availableSentinel"/> if the object is available for use, after GetResult has been called on a previous use.
             /// null if the operation has not completed.
@@ -818,9 +818,9 @@ namespace System.Net.Sockets
             /// Another delegate if OnCompleted was called before the operation could complete, in which case it's the delegate to invoke
             /// when the operation does complete.
             /// </summary>
-            private Action<object> _continuation = s_availableSentinel;
-            private ExecutionContext _executionContext;
-            private object _scheduler;
+            private Action<object?>? _continuation = s_availableSentinel;
+            private ExecutionContext? _executionContext;
+            private object? _scheduler;
             /// <summary>Current token value given to a ValueTask and then verified against the value it passes back to us.</summary>
             /// <remarks>
             /// This is not meant to be a completely reliable mechanism, doesn't require additional synchronization, etc.
@@ -853,17 +853,17 @@ namespace System.Net.Sockets
             {
                 // When the operation completes, see if OnCompleted was already called to hook up a continuation.
                 // If it was, invoke the continuation.
-                Action<object> c = _continuation;
+                Action<object?>? c = _continuation;
                 if (c != null || (c = Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null)) != null)
                 {
                     Debug.Assert(c != s_availableSentinel, "The delegate should not have been the available sentinel.");
                     Debug.Assert(c != s_completedSentinel, "The delegate should not have been the completed sentinel.");
 
-                    object continuationState = UserToken;
+                    object? continuationState = UserToken;
                     UserToken = null;
                     _continuation = s_completedSentinel; // in case someone's polling IsCompleted
 
-                    ExecutionContext ec = _executionContext;
+                    ExecutionContext? ec = _executionContext;
                     if (ec == null)
                     {
                         InvokeContinuation(c, continuationState, forceAsync: false, requiresExecutionContextFlow: false);
@@ -876,7 +876,7 @@ namespace System.Net.Sockets
                         _executionContext = null;
                         ExecutionContext.Run(ec, runState =>
                         {
-                            var t = (Tuple<AwaitableSocketAsyncEventArgs, Action<object>, object>)runState;
+                            var t = (Tuple<AwaitableSocketAsyncEventArgs, Action<object?>, object>)runState!;
                             t.Item1.InvokeContinuation(t.Item2, t.Item3, forceAsync: false, requiresExecutionContextFlow: false);
                         }, Tuple.Create(this, c, continuationState));
                     }
@@ -961,7 +961,7 @@ namespace System.Net.Sockets
             }
 
             /// <summary>Queues the provided continuation to be executed once the operation has completed.</summary>
-            public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
+            public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
             {
                 if (token != _token)
                 {
@@ -975,7 +975,7 @@ namespace System.Net.Sockets
 
                 if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0)
                 {
-                    SynchronizationContext sc = SynchronizationContext.Current;
+                    SynchronizationContext? sc = SynchronizationContext.Current;
                     if (sc != null && sc.GetType() != typeof(SynchronizationContext))
                     {
                         _scheduler = sc;
@@ -991,7 +991,7 @@ namespace System.Net.Sockets
                 }
 
                 UserToken = state; // Use UserToken to carry the continuation state around
-                Action<object> prevContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null);
+                Action<object>? prevContinuation = Interlocked.CompareExchange(ref _continuation, continuation, null);
                 if (ReferenceEquals(prevContinuation, s_completedSentinel))
                 {
                     // Lost the race condition and the operation has now already completed.
@@ -1012,9 +1012,9 @@ namespace System.Net.Sockets
                 }
             }
 
-            private void InvokeContinuation(Action<object> continuation, object state, bool forceAsync, bool requiresExecutionContextFlow)
+            private void InvokeContinuation(Action<object?> continuation, object? state, bool forceAsync, bool requiresExecutionContextFlow)
             {
-                object scheduler = _scheduler;
+                object? scheduler = _scheduler;
                 _scheduler = null;
 
                 if (scheduler != null)
@@ -1023,7 +1023,7 @@ namespace System.Net.Sockets
                     {
                         sc.Post(s =>
                         {
-                            var t = (Tuple<Action<object>, object>)s;
+                            var t = (Tuple<Action<object>, object>)s!;
                             t.Item1(t.Item2);
                         }, Tuple.Create(continuation, state));
                     }
index fc9ef1d..804b9d3 100644 (file)
@@ -73,7 +73,7 @@ namespace System.Net.Sockets
             bool broadcast = false, dontFragment = false, noDelay = false;
             int receiveSize = -1, receiveTimeout = -1, sendSize = -1, sendTimeout = -1;
             short ttl = -1;
-            LingerOption linger = null;
+            LingerOption? linger = null;
             if (_handle.IsTrackedOption(TrackedSocketOptions.DontFragment)) dontFragment = DontFragment;
             if (_handle.IsTrackedOption(TrackedSocketOptions.EnableBroadcast)) broadcast = EnableBroadcast;
             if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) linger = LingerState;
@@ -100,7 +100,7 @@ namespace System.Net.Sockets
             if (_handle.IsTrackedOption(TrackedSocketOptions.DualMode)) DualMode = _handle.DualMode;
             if (_handle.IsTrackedOption(TrackedSocketOptions.DontFragment)) DontFragment = dontFragment;
             if (_handle.IsTrackedOption(TrackedSocketOptions.EnableBroadcast)) EnableBroadcast = broadcast;
-            if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) LingerState = linger;
+            if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) LingerState = linger!;
             if (_handle.IsTrackedOption(TrackedSocketOptions.NoDelay)) NoDelay = noDelay;
             if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveBufferSize)) ReceiveBufferSize = receiveSize;
             if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveTimeout)) ReceiveTimeout = receiveTimeout;
@@ -116,7 +116,7 @@ namespace System.Net.Sockets
             throw new PlatformNotSupportedException(SR.net_sockets_connect_multiconnect_notsupported);
         }
 
-        private Socket GetOrCreateAcceptSocket(Socket acceptSocket, bool unused, string propertyName, out SafeSocketHandle handle)
+        private Socket? GetOrCreateAcceptSocket(Socket? acceptSocket, bool unused, string propertyName, out SafeSocketHandle? handle)
         {
             // AcceptSocket is not supported on Unix.
             if (acceptSocket != null)
@@ -138,13 +138,13 @@ namespace System.Net.Sockets
             }
         }
 
-        private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
+        private void SendFileInternal(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags)
         {
             CheckTransmitFileOptions(flags);
 
             // Open the file, if any
             // Open it before we send the preBuffer so that any exception happens first
-            FileStream fileStream = OpenFile(fileName);
+            FileStream? fileStream = OpenFile(fileName);
 
             SocketError errorCode = SocketError.Success;
             using (fileStream)
@@ -179,7 +179,7 @@ namespace System.Net.Sockets
             }
         }
 
-        private async Task SendFileInternalAsync(FileStream fileStream, byte[] preBuffer, byte[] postBuffer)
+        private async Task SendFileInternalAsync(FileStream? fileStream, byte[]? preBuffer, byte[]? postBuffer)
         {
             SocketError errorCode = SocketError.Success;
             using (fileStream)
@@ -219,13 +219,13 @@ namespace System.Net.Sockets
             }
         }
 
-        private IAsyncResult BeginSendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
+        private IAsyncResult BeginSendFileInternal(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags, AsyncCallback? callback, object? state)
         {
             CheckTransmitFileOptions(flags);
 
             // Open the file, if any
             // Open it before we send the preBuffer so that any exception happens first
-            FileStream fileStream = OpenFile(fileName);
+            FileStream? fileStream = OpenFile(fileName);
 
             return TaskToApm.Begin(SendFileInternalAsync(fileStream, preBuffer, postBuffer), callback, state);
         }
index 741b9f6..d606032 100644 (file)
@@ -13,7 +13,7 @@ namespace System.Net.Sockets
 {
     public partial class Socket
     {
-        private DynamicWinsockMethods _dynamicWinsockMethods;
+        private DynamicWinsockMethods? _dynamicWinsockMethods;
 
         internal void ReplaceHandleIfNecessaryAfterFailedConnect() { /* nop on Windows */ }
 
@@ -29,7 +29,7 @@ namespace System.Net.Sockets
             if (errorCode != SocketError.Success)
             {
                 Debug.Assert(_handle.IsInvalid);
-                _handle = null;
+                _handle = null!;
 
                 if (errorCode == SocketError.InvalidArgument)
                 {
@@ -43,7 +43,7 @@ namespace System.Net.Sockets
             if (_addressFamily != AddressFamily.InterNetwork && _addressFamily != AddressFamily.InterNetworkV6)
             {
                 _handle.Dispose();
-                _handle = null;
+                _handle = null!;
                 throw new NotSupportedException(SR.net_invalidversion);
             }
 
@@ -69,7 +69,7 @@ namespace System.Net.Sockets
             else
             {
                 _handle.Dispose();
-                _handle = null;
+                _handle = null!;
                 throw new SocketException((int)errorCode);
             }
 
@@ -117,7 +117,7 @@ namespace System.Net.Sockets
             NativeOverlapped* overlapped)
         {
             EnsureDynamicWinsockMethods();
-            AcceptExDelegate acceptEx = _dynamicWinsockMethods.GetDelegate<AcceptExDelegate>(listenSocketHandle);
+            AcceptExDelegate acceptEx = _dynamicWinsockMethods!.GetDelegate<AcceptExDelegate>(listenSocketHandle);
 
             return acceptEx(listenSocketHandle,
                 acceptSocketHandle,
@@ -139,7 +139,7 @@ namespace System.Net.Sockets
             out int remoteSocketAddressLength)
         {
             EnsureDynamicWinsockMethods();
-            GetAcceptExSockaddrsDelegate getAcceptExSockaddrs = _dynamicWinsockMethods.GetDelegate<GetAcceptExSockaddrsDelegate>(_handle);
+            GetAcceptExSockaddrsDelegate getAcceptExSockaddrs = _dynamicWinsockMethods!.GetDelegate<GetAcceptExSockaddrsDelegate>(_handle);
 
             getAcceptExSockaddrs(buffer,
                 receiveDataLength,
@@ -154,7 +154,7 @@ namespace System.Net.Sockets
         internal unsafe bool DisconnectEx(SafeSocketHandle socketHandle, NativeOverlapped* overlapped, int flags, int reserved)
         {
             EnsureDynamicWinsockMethods();
-            DisconnectExDelegate disconnectEx = _dynamicWinsockMethods.GetDelegate<DisconnectExDelegate>(socketHandle);
+            DisconnectExDelegate disconnectEx = _dynamicWinsockMethods!.GetDelegate<DisconnectExDelegate>(socketHandle);
 
             return disconnectEx(socketHandle, overlapped, flags, reserved);
         }
@@ -162,7 +162,7 @@ namespace System.Net.Sockets
         internal bool DisconnectExBlocking(SafeSocketHandle socketHandle, IntPtr overlapped, int flags, int reserved)
         {
             EnsureDynamicWinsockMethods();
-            DisconnectExDelegateBlocking disconnectEx_Blocking = _dynamicWinsockMethods.GetDelegate<DisconnectExDelegateBlocking>(socketHandle);
+            DisconnectExDelegateBlocking disconnectEx_Blocking = _dynamicWinsockMethods!.GetDelegate<DisconnectExDelegateBlocking>(socketHandle);
 
             return disconnectEx_Blocking(socketHandle, overlapped, flags, reserved);
         }
@@ -206,7 +206,7 @@ namespace System.Net.Sockets
             NativeOverlapped* overlapped)
         {
             EnsureDynamicWinsockMethods();
-            ConnectExDelegate connectEx = _dynamicWinsockMethods.GetDelegate<ConnectExDelegate>(socketHandle);
+            ConnectExDelegate connectEx = _dynamicWinsockMethods!.GetDelegate<ConnectExDelegate>(socketHandle);
 
             return connectEx(socketHandle, socketAddress, socketAddressSize, buffer, dataLength, out bytesSent, overlapped);
         }
@@ -214,7 +214,7 @@ namespace System.Net.Sockets
         internal unsafe SocketError WSARecvMsg(SafeSocketHandle socketHandle, IntPtr msg, out int bytesTransferred, NativeOverlapped* overlapped, IntPtr completionRoutine)
         {
             EnsureDynamicWinsockMethods();
-            WSARecvMsgDelegate recvMsg = _dynamicWinsockMethods.GetDelegate<WSARecvMsgDelegate>(socketHandle);
+            WSARecvMsgDelegate recvMsg = _dynamicWinsockMethods!.GetDelegate<WSARecvMsgDelegate>(socketHandle);
 
             return recvMsg(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
         }
@@ -222,7 +222,7 @@ namespace System.Net.Sockets
         internal SocketError WSARecvMsgBlocking(SafeSocketHandle socketHandle, IntPtr msg, out int bytesTransferred, IntPtr overlapped, IntPtr completionRoutine)
         {
             EnsureDynamicWinsockMethods();
-            WSARecvMsgDelegateBlocking recvMsg_Blocking = _dynamicWinsockMethods.GetDelegate<WSARecvMsgDelegateBlocking>(_handle);
+            WSARecvMsgDelegateBlocking recvMsg_Blocking = _dynamicWinsockMethods!.GetDelegate<WSARecvMsgDelegateBlocking>(_handle);
 
             return recvMsg_Blocking(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
         }
@@ -230,12 +230,12 @@ namespace System.Net.Sockets
         internal unsafe bool TransmitPackets(SafeSocketHandle socketHandle, IntPtr packetArray, int elementCount, int sendSize, NativeOverlapped* overlapped, TransmitFileOptions flags)
         {
             EnsureDynamicWinsockMethods();
-            TransmitPacketsDelegate transmitPackets = _dynamicWinsockMethods.GetDelegate<TransmitPacketsDelegate>(socketHandle);
+            TransmitPacketsDelegate transmitPackets = _dynamicWinsockMethods!.GetDelegate<TransmitPacketsDelegate>(socketHandle);
 
             return transmitPackets(socketHandle, packetArray, elementCount, sendSize, overlapped, flags);
         }
 
-        internal static void SocketListToFileDescriptorSet(IList socketList, Span<IntPtr> fileDescriptorSet, ref int refsAdded)
+        internal static void SocketListToFileDescriptorSet(IList? socketList, Span<IntPtr> fileDescriptorSet, ref int refsAdded)
         {
             int count;
             if (socketList == null || (count = socketList.Count) == 0)
@@ -250,7 +250,7 @@ namespace System.Net.Sockets
             {
                 if (!(socketList[current] is Socket socket))
                 {
-                    throw new ArgumentException(SR.Format(SR.net_sockets_select, socketList[current].GetType().FullName, typeof(System.Net.Sockets.Socket).FullName), nameof(socketList));
+                    throw new ArgumentException(SR.Format(SR.net_sockets_select, socketList[current]?.GetType().FullName, typeof(System.Net.Sockets.Socket).FullName), nameof(socketList));
                 }
 
                 bool success = false;
@@ -262,7 +262,7 @@ namespace System.Net.Sockets
 
         // Transform the list socketList such that the only sockets left are those
         // with a file descriptor contained in the array "fileDescriptorArray".
-        internal static void SelectFileDescriptor(IList socketList, Span<IntPtr> fileDescriptorSet, ref int refsAdded)
+        internal static void SelectFileDescriptor(IList? socketList, Span<IntPtr> fileDescriptorSet, ref int refsAdded)
         {
             // Walk the list in order.
             //
@@ -292,7 +292,8 @@ namespace System.Net.Sockets
             {
                 for (int currentSocket = 0; currentSocket < count; currentSocket++)
                 {
-                    Socket socket = socketList[currentSocket] as Socket;
+                    Socket? socket = socketList[currentSocket] as Socket;
+                    Debug.Assert(socket != null);
 
                     // Look for the file descriptor in the array.
                     int currentFileDescriptor;
@@ -316,7 +317,7 @@ namespace System.Net.Sockets
             }
         }
 
-        private Socket GetOrCreateAcceptSocket(Socket acceptSocket, bool checkDisconnected, string propertyName, out SafeSocketHandle handle)
+        private Socket GetOrCreateAcceptSocket(Socket? acceptSocket, bool checkDisconnected, string propertyName, out SafeSocketHandle handle)
         {
             // If an acceptSocket isn't specified, then we need to create one.
             if (acceptSocket == null)
@@ -332,15 +333,15 @@ namespace System.Net.Sockets
             return acceptSocket;
         }
 
-        private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
+        private void SendFileInternal(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags)
         {
             // Open the file, if any
-            FileStream fileStream = OpenFile(fileName);
+            FileStream? fileStream = OpenFile(fileName);
 
             SocketError errorCode;
             using (fileStream)
             {
-                SafeFileHandle fileHandle = fileStream?.SafeFileHandle;
+                SafeFileHandle? fileHandle = fileStream?.SafeFileHandle;
 
                 // This can throw ObjectDisposedException.
                 errorCode = SocketPal.SendFile(_handle, fileHandle, preBuffer, postBuffer, flags);
@@ -362,9 +363,9 @@ namespace System.Net.Sockets
             }
         }
 
-        private IAsyncResult BeginSendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
+        private IAsyncResult BeginSendFileInternal(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags, AsyncCallback? callback, object? state)
         {
-            FileStream fileStream = OpenFile(fileName);
+            FileStream? fileStream = OpenFile(fileName);
 
             TransmitFileAsyncResult asyncResult = new TransmitFileAsyncResult(this, state, callback);
             asyncResult.StartPostingAsyncOp(false);
@@ -385,7 +386,7 @@ namespace System.Net.Sockets
 
         private void EndSendFileInternal(IAsyncResult asyncResult)
         {
-            TransmitFileAsyncResult castedAsyncResult = asyncResult as TransmitFileAsyncResult;
+            TransmitFileAsyncResult? castedAsyncResult = asyncResult as TransmitFileAsyncResult;
             if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
             {
                 throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
index 69de733..4f182c9 100644 (file)
@@ -5,6 +5,7 @@
 using System.Collections;
 using System.Collections.Generic;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Globalization;
 using System.IO;
 using System.Net.Internals;
@@ -24,8 +25,8 @@ namespace System.Net.Sockets
 
         // _rightEndPoint is null if the socket has not been bound.  Otherwise, it is any EndPoint of the
         // correct type (IPEndPoint, etc).
-        internal EndPoint _rightEndPoint;
-        internal EndPoint _remoteEndPoint;
+        internal EndPoint? _rightEndPoint;
+        internal EndPoint? _remoteEndPoint;
 
         // These flags monitor if the socket was ever connected at any time and if it still is.
         private bool _isConnected;
@@ -44,7 +45,7 @@ namespace System.Net.Sockets
 
         // Keep track of the kind of endpoint used to do a non-blocking connect, so we can set
         // it to _rightEndPoint when we discover we're connected.
-        private EndPoint _nonBlockingConnectRightEndPoint;
+        private EndPoint? _nonBlockingConnectRightEndPoint;
 
         // These are constants initialized by constructor.
         private AddressFamily _addressFamily;
@@ -52,20 +53,20 @@ namespace System.Net.Sockets
         private ProtocolType _protocolType;
 
         // These caches are one degree off of Socket since they're not used in the sync case/when disabled in config.
-        private CacheSet _caches;
+        private CacheSet? _caches;
 
         private class CacheSet
         {
-            internal CallbackClosure ConnectClosureCache;
-            internal CallbackClosure AcceptClosureCache;
-            internal CallbackClosure SendClosureCache;
-            internal CallbackClosure ReceiveClosureCache;
+            internal CallbackClosure? ConnectClosureCache;
+            internal CallbackClosure? AcceptClosureCache;
+            internal CallbackClosure? SendClosureCache;
+            internal CallbackClosure? ReceiveClosureCache;
         }
 
         // Bool marked true if the native socket option IP_PKTINFO or IPV6_PKTINFO has been set.
         private bool _receivingPacketInformation;
 
-        private static object s_internalSyncObject;
+        private static object? s_internalSyncObject;
         private int _closeTimeout = Socket.DefaultCloseTimeout;
         private int _disposed; // 0 == false, anything else == true
 
@@ -187,7 +188,7 @@ namespace System.Net.Sockets
         }
 
         // Gets the local end point.
-        public EndPoint LocalEndPoint
+        public EndPoint? LocalEndPoint
         {
             get
             {
@@ -224,7 +225,7 @@ namespace System.Net.Sockets
         }
 
         // Gets the remote end point.
-        public EndPoint RemoteEndPoint
+        public EndPoint? RemoteEndPoint
         {
             get
             {
@@ -391,7 +392,7 @@ namespace System.Net.Sockets
         {
             get
             {
-                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse) != 0 ? true : false;
+                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse)! != 0 ? true : false;
             }
             set
             {
@@ -407,7 +408,7 @@ namespace System.Net.Sockets
         {
             get
             {
-                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer);
+                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer)!;
             }
             set
             {
@@ -424,7 +425,7 @@ namespace System.Net.Sockets
         {
             get
             {
-                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
+                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer)!;
             }
 
             set
@@ -442,7 +443,7 @@ namespace System.Net.Sockets
         {
             get
             {
-                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
+                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout)!;
             }
             set
             {
@@ -463,7 +464,7 @@ namespace System.Net.Sockets
         {
             get
             {
-                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
+                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout)!;
             }
 
             set
@@ -481,15 +482,16 @@ namespace System.Net.Sockets
             }
         }
 
-        public LingerOption LingerState
+        [DisallowNull]
+        public LingerOption? LingerState
         {
             get
             {
-                return (LingerOption)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger);
+                return (LingerOption?)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger);
             }
             set
             {
-                SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value);
+                SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value!);
             }
         }
 
@@ -497,7 +499,7 @@ namespace System.Net.Sockets
         {
             get
             {
-                return (int)GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay) != 0 ? true : false;
+                return (int)GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay)! != 0 ? true : false;
             }
             set
             {
@@ -511,11 +513,11 @@ namespace System.Net.Sockets
             {
                 if (_addressFamily == AddressFamily.InterNetwork)
                 {
-                    return (short)(int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive);
+                    return (short)(int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive)!;
                 }
                 else if (_addressFamily == AddressFamily.InterNetworkV6)
                 {
-                    return (short)(int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IpTimeToLive);
+                    return (short)(int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IpTimeToLive)!;
                 }
                 else
                 {
@@ -553,7 +555,7 @@ namespace System.Net.Sockets
             {
                 if (_addressFamily == AddressFamily.InterNetwork)
                 {
-                    return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment) != 0 ? true : false;
+                    return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment)! != 0 ? true : false;
                 }
                 else
                 {
@@ -580,11 +582,11 @@ namespace System.Net.Sockets
             {
                 if (_addressFamily == AddressFamily.InterNetwork)
                 {
-                    return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback) != 0 ? true : false;
+                    return (int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback)! != 0 ? true : false;
                 }
                 else if (_addressFamily == AddressFamily.InterNetworkV6)
                 {
-                    return (int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback) != 0 ? true : false;
+                    return (int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback)! != 0 ? true : false;
                 }
                 else
                 {
@@ -614,7 +616,7 @@ namespace System.Net.Sockets
         {
             get
             {
-                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast) != 0 ? true : false;
+                return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast)! != 0 ? true : false;
             }
             set
             {
@@ -634,7 +636,7 @@ namespace System.Net.Sockets
                 {
                     throw new NotSupportedException(SR.net_invalidversion);
                 }
-                return ((int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only) == 0);
+                return ((int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only)! == 0);
             }
             set
             {
@@ -686,7 +688,7 @@ namespace System.Net.Sockets
         private void DoBind(EndPoint endPointSnapshot, Internals.SocketAddress socketAddress)
         {
             // Mitigation for Blue Screen of Death (Win7, maybe others).
-            IPEndPoint ipEndPoint = endPointSnapshot as IPEndPoint;
+            IPEndPoint? ipEndPoint = endPointSnapshot as IPEndPoint;
             if (!OSSupportsIPv4 && ipEndPoint != null && ipEndPoint.Address.IsIPv4MappedToIPv6)
             {
                 UpdateStatusAfterSocketErrorAndThrowException(SocketError.InvalidArgument);
@@ -756,7 +758,7 @@ namespace System.Net.Sockets
                 if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"DST:{remoteEP}");
             }
 
-            DnsEndPoint dnsEP = remoteEP as DnsEndPoint;
+            DnsEndPoint? dnsEP = remoteEP as DnsEndPoint;
             if (dnsEP != null)
             {
                 ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call
@@ -838,7 +840,7 @@ namespace System.Net.Sockets
             // No need to call ValidateForMultiConnect(), as the validation
             // will be handled by the delegated Connect overloads.
 
-            IPAddress parsedAddress;
+            IPAddress? parsedAddress;
             if (IPAddress.TryParse(host, out parsedAddress))
             {
                 Connect(parsedAddress, port);
@@ -882,7 +884,7 @@ namespace System.Net.Sockets
 
             ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call
 
-            ExceptionDispatchInfo lastex = null;
+            ExceptionDispatchInfo? lastex = null;
             foreach (IPAddress address in addresses)
             {
                 if (CanTryAddressFamily(address.AddressFamily))
@@ -1031,7 +1033,7 @@ namespace System.Net.Sockets
             Socket socket = CreateAcceptSocket(acceptedSocketHandle, _rightEndPoint.Create(socketAddress));
             if (NetEventSource.IsEnabled)
             {
-                NetEventSource.Accepted(socket, socket.RemoteEndPoint, socket.LocalEndPoint);
+                NetEventSource.Accepted(socket, socket.RemoteEndPoint!, socket.LocalEndPoint);
                 NetEventSource.Exit(this, socket);
             }
             return socket;
@@ -1220,7 +1222,7 @@ namespace System.Net.Sockets
             SendFile(fileName, null, null, TransmitFileOptions.UseDefaultWorkerThread);
         }
 
-        public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
+        public void SendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
 
@@ -1646,7 +1648,7 @@ namespace System.Net.Sockets
             UpdateReceiveSocketErrorForDisposed(ref errorCode, bytesTransferred);
 
             // If the native call fails we'll throw a SocketException.
-            SocketException socketException = null;
+            SocketException? socketException = null;
             if (errorCode != SocketError.Success)
             {
                 socketException = new SocketException((int)errorCode);
@@ -1704,7 +1706,7 @@ namespace System.Net.Sockets
             return ReceiveFrom(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None, ref remoteEP);
         }
 
-        public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue)
+        public int IOControl(int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue)
         {
             ThrowIfDisposed();
 
@@ -1727,7 +1729,7 @@ namespace System.Net.Sockets
             return realOptionLength;
         }
 
-        public int IOControl(IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue)
+        public int IOControl(IOControlCode ioControlCode, byte[]? optionInValue, byte[]? optionOutValue)
         {
             return IOControl(unchecked((int)ioControlCode), optionInValue, optionOutValue);
         }
@@ -1780,7 +1782,7 @@ namespace System.Net.Sockets
 
             if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger)
             {
-                LingerOption lingerOption = optionValue as LingerOption;
+                LingerOption? lingerOption = optionValue as LingerOption;
                 if (lingerOption == null)
                 {
                     throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "LingerOption"), nameof(optionValue));
@@ -1793,7 +1795,7 @@ namespace System.Net.Sockets
             }
             else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership))
             {
-                MulticastOption multicastOption = optionValue as MulticastOption;
+                MulticastOption? multicastOption = optionValue as MulticastOption;
                 if (multicastOption == null)
                 {
                     throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "MulticastOption"), nameof(optionValue));
@@ -1803,7 +1805,7 @@ namespace System.Net.Sockets
             else if (optionLevel == SocketOptionLevel.IPv6 && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership))
             {
                 // IPv6 Changes: Handle IPv6 Multicast Add / Drop
-                IPv6MulticastOption multicastOption = optionValue as IPv6MulticastOption;
+                IPv6MulticastOption? multicastOption = optionValue as IPv6MulticastOption;
                 if (multicastOption == null)
                 {
                     throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue, "IPv6MulticastOption"), nameof(optionValue));
@@ -1817,7 +1819,7 @@ namespace System.Net.Sockets
         }
 
         // Gets the value of a socket option.
-        public object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName)
+        public object? GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName)
         {
             ThrowIfDisposed();
             if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger)
@@ -1865,7 +1867,7 @@ namespace System.Net.Sockets
                 _handle,
                 optionLevel,
                 optionName,
-                optionValue,
+                optionValue!,
                 ref optionLength);
 
             if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
@@ -1950,7 +1952,7 @@ namespace System.Net.Sockets
         }
 
         // Determines the status of a socket.
-        public static void Select(IList checkRead, IList checkWrite, IList checkError, int microSeconds)
+        public static void Select(IList? checkRead, IList? checkWrite, IList? checkError, int microSeconds)
         {
             // Validate input parameters.
             if ((checkRead == null || checkRead.Count == 0) && (checkWrite == null || checkWrite.Count == 0) && (checkError == null || checkError.Count == 0))
@@ -1993,7 +1995,7 @@ namespace System.Net.Sockets
         // Return Value:
         //
         //    IAsyncResult - Async result used to retrieve result
-        public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
+        public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback? callback, object? state)
         {
             // Validate input parameters.
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, remoteEP);
@@ -2015,7 +2017,7 @@ namespace System.Net.Sockets
             }
 
 
-            DnsEndPoint dnsEP = remoteEP as DnsEndPoint;
+            DnsEndPoint? dnsEP = remoteEP as DnsEndPoint;
             if (dnsEP != null)
             {
                 ValidateForMultiConnect(isMultiEndpoint: true); // needs to come before CanTryAddressFamily call
@@ -2040,7 +2042,7 @@ namespace System.Net.Sockets
 
 
 
-        internal IAsyncResult UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, object state, bool flowContext = false)
+        internal IAsyncResult UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback? callback, object? state, bool flowContext = false)
         {
             if (CanUseConnectEx(remoteEP))
             {
@@ -2059,7 +2061,7 @@ namespace System.Net.Sockets
             return asyncResult;
         }
 
-        public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
+        public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host);
             ThrowIfDisposed();
@@ -2087,7 +2089,7 @@ namespace System.Net.Sockets
                 throw new SocketException((int)SocketError.IsConnected);
             }
 
-            IPAddress parsedAddress;
+            IPAddress? parsedAddress;
             if (IPAddress.TryParse(host, out parsedAddress))
             {
                 IAsyncResult r = BeginConnect(parsedAddress, port, requestCallback, state);
@@ -2117,7 +2119,7 @@ namespace System.Net.Sockets
             return result;
         }
 
-        public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
+        public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? requestCallback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, address);
             ThrowIfDisposed();
@@ -2148,7 +2150,7 @@ namespace System.Net.Sockets
             return result;
         }
 
-        public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
+        public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? requestCallback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, addresses);
             ThrowIfDisposed();
@@ -2199,7 +2201,7 @@ namespace System.Net.Sockets
             return result;
         }
 
-        public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state)
+        public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
             ThrowIfDisposed();
@@ -2286,10 +2288,10 @@ namespace System.Net.Sockets
                 throw new ArgumentNullException(nameof(asyncResult));
             }
 
-            ContextAwareResult castedAsyncResult =
+            ContextAwareResult? castedAsyncResult =
                 asyncResult as ConnectOverlappedAsyncResult ??
                 asyncResult as MultipleAddressConnectAsyncResult ??
-                (ContextAwareResult)(asyncResult as ConnectAsyncResult);
+                (ContextAwareResult?)(asyncResult as ConnectAsyncResult);
 
             if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
             {
@@ -2305,7 +2307,7 @@ namespace System.Net.Sockets
 
             if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"asyncResult:{asyncResult}");
 
-            Exception ex = castedAsyncResult.Result as Exception;
+            Exception? ex = castedAsyncResult.Result as Exception;
             if (ex != null || (SocketError)castedAsyncResult.ErrorCode != SocketError.Success)
             {
                 if (ex == null)
@@ -2340,7 +2342,7 @@ namespace System.Net.Sockets
             }
 
             //get async result and check for errors
-            LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult;
+            LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult;
             if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
             {
                 throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
@@ -2385,18 +2387,18 @@ namespace System.Net.Sockets
         // Return Value:
         //
         //    IAsyncResult - Async result used to retrieve result
-        public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
+        public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback? callback, object? state)
         {
             SocketError errorCode;
-            IAsyncResult result = BeginSend(buffer, offset, size, socketFlags, out errorCode, callback, state);
+            IAsyncResult? result = BeginSend(buffer, offset, size, socketFlags, out errorCode, callback, state);
             if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
             {
                 throw new SocketException((int)errorCode);
             }
-            return result;
+            return result!;
         }
 
-        public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
+        public IAsyncResult? BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
             ThrowIfDisposed();
@@ -2416,7 +2418,7 @@ namespace System.Net.Sockets
             }
 
             // We need to flow the context here.  But we don't need to lock the context - we don't use it until the callback.
-            OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
+            OverlappedAsyncResult? asyncResult = new OverlappedAsyncResult(this, state, callback);
             asyncResult.StartPostingAsyncOp(false);
 
             // Run the send with this asyncResult.
@@ -2457,18 +2459,18 @@ namespace System.Net.Sockets
             return errorCode;
         }
 
-        public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
+        public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback? callback, object? state)
         {
             SocketError errorCode;
-            IAsyncResult result = BeginSend(buffers, socketFlags, out errorCode, callback, state);
+            IAsyncResult? result = BeginSend(buffers, socketFlags, out errorCode, callback, state);
             if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
             {
                 throw new SocketException((int)errorCode);
             }
-            return result;
+            return result!;
         }
 
-        public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
+        public IAsyncResult? BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
             ThrowIfDisposed();
@@ -2485,7 +2487,7 @@ namespace System.Net.Sockets
             }
 
             // We need to flow the context here.  But we don't need to lock the context - we don't use it until the callback.
-            OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
+            OverlappedAsyncResult? asyncResult = new OverlappedAsyncResult(this, state, callback);
             asyncResult.StartPostingAsyncOp(false);
 
             // Run the send with this asyncResult.
@@ -2556,7 +2558,7 @@ namespace System.Net.Sockets
                 throw new ArgumentNullException(nameof(asyncResult));
             }
 
-            OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
+            OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult;
             if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
             {
                 throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
@@ -2590,12 +2592,12 @@ namespace System.Net.Sockets
             return bytesTransferred;
         }
 
-        public IAsyncResult BeginSendFile(string fileName, AsyncCallback callback, object state)
+        public IAsyncResult BeginSendFile(string fileName, AsyncCallback? callback, object? state)
         {
             return BeginSendFile(fileName, null, null, TransmitFileOptions.UseDefaultWorkerThread, callback, state);
         }
 
-        public IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
+        public IAsyncResult BeginSendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags, AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
 
@@ -2650,7 +2652,7 @@ namespace System.Net.Sockets
         // Return Value:
         //
         //    IAsyncResult - Async result used to retrieve result
-        public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state)
+        public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
             ThrowIfDisposed();
@@ -2693,7 +2695,7 @@ namespace System.Net.Sockets
         {
             if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size}");
 
-            EndPoint oldEndPoint = _rightEndPoint;
+            EndPoint? oldEndPoint = _rightEndPoint;
 
             // Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to
             // avoid a Socket leak in case of error.
@@ -2752,7 +2754,7 @@ namespace System.Net.Sockets
                 throw new ArgumentNullException(nameof(asyncResult));
             }
 
-            OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
+            OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult;
             if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
             {
                 throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
@@ -2801,18 +2803,18 @@ namespace System.Net.Sockets
         // Return Value:
         //
         //    IAsyncResult - Async result used to retrieve result
-        public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
+        public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback? callback, object? state)
         {
             SocketError errorCode;
-            IAsyncResult result = BeginReceive(buffer, offset, size, socketFlags, out errorCode, callback, state);
+            IAsyncResult? result = BeginReceive(buffer, offset, size, socketFlags, out errorCode, callback, state);
             if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
             {
                 throw new SocketException((int)errorCode);
             }
-            return result;
+            return result!;
         }
 
-        public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
+        public IAsyncResult? BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
 
@@ -2833,7 +2835,7 @@ namespace System.Net.Sockets
             }
 
             // We need to flow the context here.  But we don't need to lock the context - we don't use it until the callback.
-            OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
+            OverlappedAsyncResult? asyncResult = new OverlappedAsyncResult(this, state, callback);
             asyncResult.StartPostingAsyncOp(false);
 
             // Run the receive with this asyncResult.
@@ -2878,18 +2880,18 @@ namespace System.Net.Sockets
             return errorCode;
         }
 
-        public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
+        public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback? callback, object? state)
         {
             SocketError errorCode;
-            IAsyncResult result = BeginReceive(buffers, socketFlags, out errorCode, callback, state);
+            IAsyncResult? result = BeginReceive(buffers, socketFlags, out errorCode, callback, state);
             if (errorCode != SocketError.Success && errorCode != SocketError.IOPending)
             {
                 throw new SocketException((int)errorCode);
             }
-            return result;
+            return result!;
         }
 
-        public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
+        public IAsyncResult? BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
 
@@ -2907,7 +2909,7 @@ namespace System.Net.Sockets
             }
 
             // We need to flow the context here.  But we don't need to lock the context - we don't use it until the callback.
-            OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback);
+            OverlappedAsyncResult? asyncResult = new OverlappedAsyncResult(this, state, callback);
             asyncResult.StartPostingAsyncOp(false);
 
             // Run the receive with this asyncResult.
@@ -2995,7 +2997,7 @@ namespace System.Net.Sockets
                 throw new ArgumentNullException(nameof(asyncResult));
             }
 
-            OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
+            OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult;
             if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
             {
                 throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
@@ -3038,7 +3040,7 @@ namespace System.Net.Sockets
             return bytesTransferred;
         }
 
-        public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
+        public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled)
             {
@@ -3141,7 +3143,7 @@ namespace System.Net.Sockets
             {
                 try
                 {
-                    remoteEP = remoteEP.Create(asyncResult.SocketAddress);
+                    remoteEP = remoteEP.Create(asyncResult.SocketAddress!);
                 }
                 catch
                 {
@@ -3174,7 +3176,7 @@ namespace System.Net.Sockets
                 throw new ArgumentNullException(nameof(asyncResult));
             }
 
-            ReceiveMessageOverlappedAsyncResult castedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult;
+            ReceiveMessageOverlappedAsyncResult? castedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult;
             if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
             {
                 throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
@@ -3190,7 +3192,7 @@ namespace System.Net.Sockets
             castedAsyncResult.EndCalled = true;
 
             // Update socket address size.
-            castedAsyncResult.SocketAddress.InternalSize = castedAsyncResult.GetSocketAddressSize();
+            castedAsyncResult.SocketAddress!.InternalSize = castedAsyncResult.GetSocketAddressSize();
 
             if (!socketAddressOriginal.Equals(castedAsyncResult.SocketAddress))
             {
@@ -3244,7 +3246,7 @@ namespace System.Net.Sockets
         // Return Value:
         //
         //    IAsyncResult - Async result used to retrieve result
-        public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
+        public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
 
@@ -3293,11 +3295,11 @@ namespace System.Net.Sockets
             // Capture the context, maybe call the callback, and return.
             asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
 
-            if (asyncResult.CompletedSynchronously && !asyncResult.SocketAddressOriginal.Equals(asyncResult.SocketAddress))
+            if (asyncResult.CompletedSynchronously && !asyncResult.SocketAddressOriginal!.Equals(asyncResult.SocketAddress))
             {
                 try
                 {
-                    remoteEP = remoteEP.Create(asyncResult.SocketAddress);
+                    remoteEP = remoteEP.Create(asyncResult.SocketAddress!);
                 }
                 catch
                 {
@@ -3310,7 +3312,7 @@ namespace System.Net.Sockets
 
         private void DoBeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint endPointSnapshot, Internals.SocketAddress socketAddress, OriginalAddressOverlappedAsyncResult asyncResult)
         {
-            EndPoint oldEndPoint = _rightEndPoint;
+            EndPoint? oldEndPoint = _rightEndPoint;
 
             if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"size:{size}");
 
@@ -3383,7 +3385,7 @@ namespace System.Net.Sockets
                 throw new ArgumentNullException(nameof(asyncResult));
             }
 
-            OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult;
+            OverlappedAsyncResult? castedAsyncResult = asyncResult as OverlappedAsyncResult;
             if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
             {
                 throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
@@ -3399,7 +3401,7 @@ namespace System.Net.Sockets
             castedAsyncResult.EndCalled = true;
 
             // Update socket address size.
-            castedAsyncResult.SocketAddress.InternalSize = castedAsyncResult.GetSocketAddressSize();
+            castedAsyncResult.SocketAddress!.InternalSize = castedAsyncResult.GetSocketAddressSize();
 
             if (!socketAddressOriginal.Equals(castedAsyncResult.SocketAddress))
             {
@@ -3443,7 +3445,7 @@ namespace System.Net.Sockets
         // Return Value:
         //
         //    IAsyncResult - Async result used to retrieve resultant new socket
-        public IAsyncResult BeginAccept(AsyncCallback callback, object state)
+        public IAsyncResult BeginAccept(AsyncCallback? callback, object? state)
         {
             if (!_isDisconnected)
             {
@@ -3457,13 +3459,13 @@ namespace System.Net.Sockets
             return null; // unreachable
         }
 
-        public IAsyncResult BeginAccept(int receiveSize, AsyncCallback callback, object state)
+        public IAsyncResult BeginAccept(int receiveSize, AsyncCallback? callback, object? state)
         {
             return BeginAccept(null, receiveSize, callback, state);
         }
 
         // This is the truly async version that uses AcceptEx.
-        public IAsyncResult BeginAccept(Socket acceptSocket, int receiveSize, AsyncCallback callback, object state)
+        public IAsyncResult BeginAccept(Socket? acceptSocket, int receiveSize, AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
             ThrowIfDisposed();
@@ -3488,7 +3490,7 @@ namespace System.Net.Sockets
             return asyncResult;
         }
 
-        private void DoBeginAccept(Socket acceptSocket, int receiveSize, AcceptOverlappedAsyncResult asyncResult)
+        private void DoBeginAccept(Socket? acceptSocket, int receiveSize, AcceptOverlappedAsyncResult asyncResult)
         {
             if (_rightEndPoint == null)
             {
@@ -3500,7 +3502,7 @@ namespace System.Net.Sockets
                 throw new InvalidOperationException(SR.net_sockets_mustlisten);
             }
 
-            SafeSocketHandle acceptHandle;
+            SafeSocketHandle? acceptHandle;
             asyncResult.AcceptSocket = GetOrCreateAcceptSocket(acceptSocket, false, nameof(acceptSocket), out acceptHandle);
 
             if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"AcceptSocket:{acceptSocket}");
@@ -3534,22 +3536,23 @@ namespace System.Net.Sockets
         public Socket EndAccept(IAsyncResult asyncResult)
         {
             int bytesTransferred;
-            byte[] buffer;
+            byte[]? buffer;
             return EndAccept(out buffer, out bytesTransferred, asyncResult);
         }
 
-        public Socket EndAccept(out byte[] buffer, IAsyncResult asyncResult)
+        public Socket EndAccept(out byte[]? buffer, IAsyncResult asyncResult)
         {
             int bytesTransferred;
-            byte[] innerBuffer;
+            byte[]? innerBuffer;
 
             Socket socket = EndAccept(out innerBuffer, out bytesTransferred, asyncResult);
             buffer = new byte[bytesTransferred];
-            Buffer.BlockCopy(innerBuffer, 0, buffer, 0, bytesTransferred);
+            // https://github.com/dotnet/runtime/issues/32633 - this throws on Unix
+            Buffer.BlockCopy(innerBuffer!, 0, buffer, 0, bytesTransferred);
             return socket;
         }
 
-        public Socket EndAccept(out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
+        public Socket EndAccept(out byte[]? buffer, out int bytesTransferred, IAsyncResult asyncResult)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);
             ThrowIfDisposed();
@@ -3559,7 +3562,7 @@ namespace System.Net.Sockets
             {
                 throw new ArgumentNullException(nameof(asyncResult));
             }
-            AcceptOverlappedAsyncResult castedAsyncResult = asyncResult as AcceptOverlappedAsyncResult;
+            AcceptOverlappedAsyncResult? castedAsyncResult = asyncResult as AcceptOverlappedAsyncResult;
             if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
             {
                 throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
@@ -3569,7 +3572,7 @@ namespace System.Net.Sockets
                 throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAccept"));
             }
 
-            Socket socket = (Socket)castedAsyncResult.InternalWaitForCompletion();
+            Socket socket = (Socket)castedAsyncResult.InternalWaitForCompletion()!;
             bytesTransferred = (int)castedAsyncResult.BytesTransferred;
             buffer = castedAsyncResult.Buffer;
 
@@ -3650,7 +3653,7 @@ namespace System.Net.Sockets
             }
 
             // Handle AcceptSocket property.
-            SafeSocketHandle acceptHandle;
+            SafeSocketHandle? acceptHandle;
             e.AcceptSocket = GetOrCreateAcceptSocket(e.AcceptSocket, true, "AcceptSocket", out acceptHandle);
 
             // Prepare for and make the native call.
@@ -3706,8 +3709,8 @@ namespace System.Net.Sockets
             }
 
             // Prepare SocketAddress.
-            EndPoint endPointSnapshot = e.RemoteEndPoint;
-            DnsEndPoint dnsEP = endPointSnapshot as DnsEndPoint;
+            EndPoint? endPointSnapshot = e.RemoteEndPoint;
+            DnsEndPoint? dnsEP = endPointSnapshot as DnsEndPoint;
 
             if (dnsEP != null)
             {
@@ -3750,7 +3753,7 @@ namespace System.Net.Sockets
                 WildcardBindForConnectIfNecessary(endPointSnapshot.AddressFamily);
 
                 // Save the old RightEndPoint and prep new RightEndPoint.
-                EndPoint oldEndPoint = _rightEndPoint;
+                EndPoint? oldEndPoint = _rightEndPoint;
                 if (_rightEndPoint == null)
                 {
                     _rightEndPoint = endPointSnapshot;
@@ -3801,12 +3804,12 @@ namespace System.Net.Sockets
             }
 
             EndPoint endPointSnapshot = e.RemoteEndPoint;
-            DnsEndPoint dnsEP = endPointSnapshot as DnsEndPoint;
+            DnsEndPoint? dnsEP = endPointSnapshot as DnsEndPoint;
 
             if (dnsEP != null)
             {
-                Socket attemptSocket = null;
-                MultipleConnectAsync multipleConnectAsync = null;
+                Socket? attemptSocket = null;
+                MultipleConnectAsync? multipleConnectAsync = null;
                 if (dnsEP.AddressFamily == AddressFamily.Unspecified)
                 {
                     // This is the only *Connect* API that fully supports multiple endpoint attempts, as it's responsible
@@ -3862,6 +3865,11 @@ namespace System.Net.Sockets
             // Throw if socket disposed
             ThrowIfDisposed();
 
+            if (e == null)
+            {
+                throw new ArgumentNullException(nameof(e));
+            }
+
             // Prepare for and make the native call.
             e.StartOperationCommon(this, SocketAsyncOperation.Disconnect);
             SocketError socketError = SocketError.Success;
@@ -4107,7 +4115,7 @@ namespace System.Net.Sockets
             // Prepare for and make the native call.
             e.StartOperationCommon(this, SocketAsyncOperation.SendTo);
 
-            EndPoint oldEndPoint = _rightEndPoint;
+            EndPoint? oldEndPoint = _rightEndPoint;
             if (_rightEndPoint == null)
             {
                 _rightEndPoint = endPointSnapshot;
@@ -4422,8 +4430,8 @@ namespace System.Net.Sockets
             {
                 // DualMode: When bound to IPv6Any you must enable both socket options.
                 // When bound to an IPv4 mapped IPv6 address you must enable the IPv4 socket option.
-                IPEndPoint ipEndPoint = _rightEndPoint as IPEndPoint;
-                IPAddress boundAddress = (ipEndPoint != null ? ipEndPoint.Address : null);
+                IPEndPoint? ipEndPoint = _rightEndPoint as IPEndPoint;
+                IPAddress? boundAddress = (ipEndPoint != null ? ipEndPoint.Address : null);
                 Debug.Assert(boundAddress != null, "Not Bound");
                 if (_addressFamily == AddressFamily.InterNetwork)
                 {
@@ -4528,9 +4536,9 @@ namespace System.Net.Sockets
             }
         }
 
-        private LingerOption GetLingerOpt()
+        private LingerOption? GetLingerOpt()
         {
-            LingerOption lingerOption;
+            LingerOption? lingerOption;
             SocketError errorCode = SocketPal.GetLingerOption(_handle, out lingerOption);
 
             if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
@@ -4544,9 +4552,9 @@ namespace System.Net.Sockets
             return lingerOption;
         }
 
-        private MulticastOption GetMulticastOpt(SocketOptionName optionName)
+        private MulticastOption? GetMulticastOpt(SocketOptionName optionName)
         {
-            MulticastOption multicastOption;
+            MulticastOption? multicastOption;
             SocketError errorCode = SocketPal.GetMulticastOption(_handle, optionName, out multicastOption);
 
             if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
@@ -4561,9 +4569,9 @@ namespace System.Net.Sockets
         }
 
         // IPv6 getsockopt for JOIN / LEAVE multicast group.
-        private IPv6MulticastOption GetIPv6MulticastOpt(SocketOptionName optionName)
+        private IPv6MulticastOption? GetIPv6MulticastOpt(SocketOptionName optionName)
         {
-            IPv6MulticastOption multicastOption;
+            IPv6MulticastOption? multicastOption;
             SocketError errorCode = SocketPal.GetIPv6MulticastOption(_handle, optionName, out multicastOption);
 
             if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Interop.Winsock.getsockopt returns errorCode:{errorCode}");
@@ -4626,7 +4634,7 @@ namespace System.Net.Sockets
 
         // Implements ConnectEx - this provides completion port IO and support for disconnect and reconnects.
         // Since this is private, the unsafe mode is specified with a flag instead of an overload.
-        private IAsyncResult BeginConnectEx(EndPoint remoteEP, bool flowContext, AsyncCallback callback, object state)
+        private IAsyncResult BeginConnectEx(EndPoint remoteEP, bool flowContext, AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
 
@@ -4644,7 +4652,7 @@ namespace System.Net.Sockets
                 asyncResult.StartPostingAsyncOp(false);
             }
 
-            EndPoint oldEndPoint = _rightEndPoint;
+            EndPoint? oldEndPoint = _rightEndPoint;
             if (_rightEndPoint == null)
             {
                 _rightEndPoint = endPointSnapshot;
@@ -4700,7 +4708,7 @@ namespace System.Net.Sockets
 
             bool invokeCallback = false;
 
-            MultipleAddressConnectAsyncResult context = (MultipleAddressConnectAsyncResult)result.AsyncState;
+            MultipleAddressConnectAsyncResult context = (MultipleAddressConnectAsyncResult)result.AsyncState!;
             try
             {
                 invokeCallback = DoDnsCallback(result, context);
@@ -4728,7 +4736,7 @@ namespace System.Net.Sockets
         {
             private readonly EndPoint _endPoint;
 
-            internal ConnectAsyncResult(object myObject, EndPoint endPoint, object myState, AsyncCallback myCallBack) :
+            internal ConnectAsyncResult(object myObject, EndPoint endPoint, object? myState, AsyncCallback? myCallBack) :
                 base(myObject, myState, myCallBack)
             {
                 _endPoint = endPoint;
@@ -4742,7 +4750,7 @@ namespace System.Net.Sockets
 
         private sealed class MultipleAddressConnectAsyncResult : ContextAwareResult
         {
-            internal MultipleAddressConnectAsyncResult(IPAddress[] addresses, int port, Socket socket, object myState, AsyncCallback myCallBack) :
+            internal MultipleAddressConnectAsyncResult(IPAddress[]? addresses, int port, Socket socket, object? myState, AsyncCallback? myCallBack) :
                 base(socket, myState, myCallBack)
             {
                 _addresses = addresses;
@@ -4751,12 +4759,12 @@ namespace System.Net.Sockets
             }
 
             internal Socket _socket;   // Keep this member just to avoid all the casting.
-            internal IPAddress[] _addresses;
+            internal IPAddress[]? _addresses;
             internal int _index;
             internal int _port;
-            internal Exception _lastException;
+            internal Exception? _lastException;
 
-            internal override EndPoint RemoteEndPoint
+            internal override EndPoint? RemoteEndPoint
             {
                 get
                 {
@@ -4772,7 +4780,7 @@ namespace System.Net.Sockets
             }
         }
 
-        private static AsyncCallback s_multipleAddressConnectCallback;
+        private static AsyncCallback? s_multipleAddressConnectCallback;
         private static AsyncCallback CachedMultipleAddressConnectCallback
         {
             get
@@ -4785,9 +4793,9 @@ namespace System.Net.Sockets
             }
         }
 
-        private static object PostOneBeginConnect(MultipleAddressConnectAsyncResult context)
+        private static object? PostOneBeginConnect(MultipleAddressConnectAsyncResult context)
         {
-            IPAddress currentAddressSnapshot = context._addresses[context._index];
+            IPAddress currentAddressSnapshot = context._addresses![context._index];
 
             context._socket.ReplaceHandleIfNecessaryAfterFailedConnect();
 
@@ -4825,7 +4833,7 @@ namespace System.Net.Sockets
 
             bool invokeCallback = false;
 
-            MultipleAddressConnectAsyncResult context = (MultipleAddressConnectAsyncResult)result.AsyncState;
+            MultipleAddressConnectAsyncResult context = (MultipleAddressConnectAsyncResult)result.AsyncState!;
             try
             {
                 invokeCallback = DoMultipleAddressConnectCallback(result, context);
@@ -4844,11 +4852,11 @@ namespace System.Net.Sockets
 
         // This is like a regular async callback worker, except the result can be an exception.  This is a useful pattern when
         // processing should continue whether or not an async step failed.
-        private static bool DoMultipleAddressConnectCallback(object result, MultipleAddressConnectAsyncResult context)
+        private static bool DoMultipleAddressConnectCallback(object? result, MultipleAddressConnectAsyncResult context)
         {
             while (result != null)
             {
-                Exception ex = result as Exception;
+                Exception? ex = result as Exception;
                 if (ex == null)
                 {
                     try
@@ -4870,7 +4878,7 @@ namespace System.Net.Sockets
                 }
                 else
                 {
-                    if (++context._index >= context._addresses.Length)
+                    if (++context._index >= context._addresses!.Length)
                     {
                         ExceptionDispatchInfo.Throw(ex);
                     }
@@ -4957,7 +4965,7 @@ namespace System.Net.Sockets
             }
         }
 
-        private void UpdateStatusAfterSocketErrorAndThrowException(SocketError error, [CallerMemberName] string callerName = null)
+        private void UpdateStatusAfterSocketErrorAndThrowException(SocketError error, [CallerMemberName] string? callerName = null)
         {
             // Update the internal state of this socket according to the error before throwing.
             var socketException = new SocketException((int)error);
@@ -5020,7 +5028,7 @@ namespace System.Net.Sockets
         partial void ValidateForMultiConnect(bool isMultiEndpoint);
 
         // Helper for SendFile implementations
-        private static FileStream OpenFile(string name) => string.IsNullOrEmpty(name) ? null : File.OpenRead(name);
+        private static FileStream? OpenFile(string? name) => string.IsNullOrEmpty(name) ? null : File.OpenRead(name);
 
         private void UpdateReceiveSocketErrorForDisposed(ref SocketError socketError, int bytesTransferred)
         {
@@ -5065,11 +5073,12 @@ namespace System.Net.Sockets
             }
         }
 
+        [DoesNotReturn]
         private void ThrowObjectDisposedException() => throw new ObjectDisposedException(GetType().FullName);
 
         private bool IsConnectionOriented => _socketType == SocketType.Stream;
 
-        internal static void SocketListDangerousReleaseRefs(IList socketList, ref int refsAdded)
+        internal static void SocketListDangerousReleaseRefs(IList? socketList, ref int refsAdded)
         {
             if (socketList == null)
             {
@@ -5078,7 +5087,7 @@ namespace System.Net.Sockets
 
             for (int i = 0; (i < socketList.Count) && (refsAdded > 0); i++)
             {
-                Socket socket = (Socket)socketList[i];
+                Socket socket = (Socket)socketList[i]!;
                 socket.InternalSafeHandle.DangerousRelease();
                 refsAdded--;
             }
index 6901197..beb4cc0 100644 (file)
@@ -38,11 +38,11 @@ namespace System.Net.Sockets
         // refactoring, these could also potentially be moved to SocketAsyncEventArgs, which
         // would be more invasive but which would allow them to be reused across socket instances
         // and also eliminate the interlocked necessary to rent the instances.
-        private AcceptOperation _cachedAcceptOperation;
-        private BufferMemoryReceiveOperation _cachedBufferMemoryReceiveOperation;
-        private BufferListReceiveOperation _cachedBufferListReceiveOperation;
-        private BufferMemorySendOperation _cachedBufferMemorySendOperation;
-        private BufferListSendOperation _cachedBufferListSendOperation;
+        private AcceptOperation? _cachedAcceptOperation;
+        private BufferMemoryReceiveOperation? _cachedBufferMemoryReceiveOperation;
+        private BufferListReceiveOperation? _cachedBufferListReceiveOperation;
+        private BufferMemorySendOperation? _cachedBufferMemorySendOperation;
+        private BufferListSendOperation? _cachedBufferListSendOperation;
 
         private void ReturnOperation(AcceptOperation operation)
         {
@@ -125,14 +125,14 @@ namespace System.Net.Sockets
 #endif
 
             public readonly SocketAsyncContext AssociatedContext;
-            public AsyncOperation Next;
-            protected object CallbackOrEvent;
+            public AsyncOperation Next = null!; // initialized by helper called from ctor
+            protected object? CallbackOrEvent;
             public SocketError ErrorCode;
-            public byte[] SocketAddress;
+            public byte[]? SocketAddress;
             public int SocketAddressLen;
             public CancellationTokenRegistration CancellationRegistration;
 
-            public ManualResetEventSlim Event
+            public ManualResetEventSlim? Event
             {
                 get { return CallbackOrEvent as ManualResetEventSlim; }
                 set { CallbackOrEvent = value; }
@@ -254,7 +254,7 @@ namespace System.Net.Sockets
                     // we can't pool the object, as ProcessQueue may still have a reference to it, due to
                     // using a pattern whereby it takes the lock to grab an item, but then releases the lock
                     // to do further processing on the item that's still in the list.
-                    ThreadPool.UnsafeQueueUserWorkItem(o => ((AsyncOperation)o).InvokeCallback(allowPooling: false), this);
+                    ThreadPool.UnsafeQueueUserWorkItem(o => ((AsyncOperation)o!).InvokeCallback(allowPooling: false), this);
                 }
 
                 Trace("Exit");
@@ -266,7 +266,7 @@ namespace System.Net.Sockets
 
             public void Dispatch()
             {
-                ManualResetEventSlim e = Event;
+                ManualResetEventSlim? e = Event;
                 if (e != null)
                 {
                     // Sync operation.  Signal waiting thread to continue processing.
@@ -311,13 +311,13 @@ namespace System.Net.Sockets
             public abstract void InvokeCallback(bool allowPooling);
 
             [Conditional("SOCKETASYNCCONTEXT_TRACE")]
-            public void Trace(string message, [CallerMemberName] string memberName = null)
+            public void Trace(string message, [CallerMemberName] string? memberName = null)
             {
                 OutputTrace($"{IdOf(this)}.{memberName}: {message}");
             }
 
             [Conditional("SOCKETASYNCCONTEXT_TRACE")]
-            public void TraceWithContext(SocketAsyncContext context, string message, [CallerMemberName] string memberName = null)
+            public void TraceWithContext(SocketAsyncContext context, string message, [CallerMemberName] string? memberName = null)
             {
                 OutputTrace($"{IdOf(context)}, {IdOf(this)}.{memberName}: {message}");
             }
@@ -350,13 +350,13 @@ namespace System.Net.Sockets
 
             protected sealed override void Abort() { }
 
-            public Action<int, byte[], int, SocketFlags, SocketError> Callback
+            public Action<int, byte[]?, int, SocketFlags, SocketError>? Callback
             {
                 set => CallbackOrEvent = value;
             }
 
             public override void InvokeCallback(bool allowPooling) =>
-                ((Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent)(BytesTransferred, SocketAddress, SocketAddressLen, SocketFlags.None, ErrorCode);
+                ((Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!)(BytesTransferred, SocketAddress, SocketAddressLen, SocketFlags.None, ErrorCode);
         }
 
         private sealed class BufferMemorySendOperation : SendOperation
@@ -373,9 +373,9 @@ namespace System.Net.Sockets
 
             public override void InvokeCallback(bool allowPooling)
             {
-                var cb = (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent;
+                var cb = (Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!;
                 int bt = BytesTransferred;
-                byte[] sa = SocketAddress;
+                byte[]? sa = SocketAddress;
                 int sal = SocketAddressLen;
                 SocketError ec = ErrorCode;
 
@@ -390,7 +390,7 @@ namespace System.Net.Sockets
 
         private sealed class BufferListSendOperation : SendOperation
         {
-            public IList<ArraySegment<byte>> Buffers;
+            public IList<ArraySegment<byte>>? Buffers;
             public int BufferIndex;
 
             public BufferListSendOperation(SocketAsyncContext context) : base(context) { }
@@ -402,9 +402,9 @@ namespace System.Net.Sockets
 
             public override void InvokeCallback(bool allowPooling)
             {
-                var cb = (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent;
+                var cb = (Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!;
                 int bt = BytesTransferred;
-                byte[] sa = SocketAddress;
+                byte[]? sa = SocketAddress;
                 int sal = SocketAddressLen;
                 SocketError ec = ErrorCode;
 
@@ -440,13 +440,13 @@ namespace System.Net.Sockets
 
             protected sealed override void Abort() { }
 
-            public Action<int, byte[], int, SocketFlags, SocketError> Callback
+            public Action<int, byte[]?, int, SocketFlags, SocketError>? Callback
             {
                 set => CallbackOrEvent = value;
             }
 
             public override void InvokeCallback(bool allowPooling) =>
-                ((Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent)(
+                ((Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!)(
                     BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, ErrorCode);
         }
 
@@ -475,9 +475,9 @@ namespace System.Net.Sockets
 
             public override void InvokeCallback(bool allowPooling)
             {
-                var cb = (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent;
+                var cb = (Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!;
                 int bt = BytesTransferred;
-                byte[] sa = SocketAddress;
+                byte[]? sa = SocketAddress;
                 int sal = SocketAddressLen;
                 SocketFlags rf = ReceivedFlags;
                 SocketError ec = ErrorCode;
@@ -493,7 +493,7 @@ namespace System.Net.Sockets
 
         private sealed class BufferListReceiveOperation : ReceiveOperation
         {
-            public IList<ArraySegment<byte>> Buffers;
+            public IList<ArraySegment<byte>>? Buffers;
 
             public BufferListReceiveOperation(SocketAsyncContext context) : base(context) { }
 
@@ -502,9 +502,9 @@ namespace System.Net.Sockets
 
             public override void InvokeCallback(bool allowPooling)
             {
-                var cb = (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent;
+                var cb = (Action<int, byte[]?, int, SocketFlags, SocketError>)CallbackOrEvent!;
                 int bt = BytesTransferred;
-                byte[] sa = SocketAddress;
+                byte[]? sa = SocketAddress;
                 int sal = SocketAddressLen;
                 SocketFlags rf = ReceivedFlags;
                 SocketError ec = ErrorCode;
@@ -535,7 +535,7 @@ namespace System.Net.Sockets
             public SocketFlags Flags;
             public int BytesTransferred;
             public SocketFlags ReceivedFlags;
-            public IList<ArraySegment<byte>> Buffers;
+            public IList<ArraySegment<byte>>? Buffers;
 
             public bool IsIPv4;
             public bool IsIPv6;
@@ -551,11 +551,11 @@ namespace System.Net.Sockets
             }
 
             protected override bool DoTryComplete(SocketAsyncContext context) =>
-                SocketPal.TryCompleteReceiveMessageFrom(context._socket, Buffer.Span, Buffers, Flags, SocketAddress, ref SocketAddressLen, IsIPv4, IsIPv6, out BytesTransferred, out ReceivedFlags, out IPPacketInformation, out ErrorCode);
+                SocketPal.TryCompleteReceiveMessageFrom(context._socket, Buffer.Span, Buffers, Flags, SocketAddress!, ref SocketAddressLen, IsIPv4, IsIPv6, out BytesTransferred, out ReceivedFlags, out IPPacketInformation, out ErrorCode);
 
             public override void InvokeCallback(bool allowPooling) =>
-                ((Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError>)CallbackOrEvent)(
-                    BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, IPPacketInformation, ErrorCode);
+                ((Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError>)CallbackOrEvent!)(
+                    BytesTransferred, SocketAddress!, SocketAddressLen, ReceivedFlags, IPPacketInformation, ErrorCode);
         }
 
         private sealed class AcceptOperation : ReadOperation
@@ -564,7 +564,7 @@ namespace System.Net.Sockets
 
             public AcceptOperation(SocketAsyncContext context) : base(context) { }
 
-            public Action<IntPtr, byte[], int, SocketError> Callback
+            public Action<IntPtr, byte[], int, SocketError>? Callback
             {
                 set => CallbackOrEvent = value;
             }
@@ -574,16 +574,16 @@ namespace System.Net.Sockets
 
             protected override bool DoTryComplete(SocketAsyncContext context)
             {
-                bool completed = SocketPal.TryCompleteAccept(context._socket, SocketAddress, ref SocketAddressLen, out AcceptedFileDescriptor, out ErrorCode);
+                bool completed = SocketPal.TryCompleteAccept(context._socket, SocketAddress!, ref SocketAddressLen, out AcceptedFileDescriptor, out ErrorCode);
                 Debug.Assert(ErrorCode == SocketError.Success || AcceptedFileDescriptor == (IntPtr)(-1), $"Unexpected values: ErrorCode={ErrorCode}, AcceptedFileDescriptor={AcceptedFileDescriptor}");
                 return completed;
             }
 
             public override void InvokeCallback(bool allowPooling)
             {
-                var cb = (Action<IntPtr, byte[], int, SocketError>)CallbackOrEvent;
+                var cb = (Action<IntPtr, byte[], int, SocketError>)CallbackOrEvent!;
                 IntPtr fd = AcceptedFileDescriptor;
-                byte[] sa = SocketAddress;
+                byte[] sa = SocketAddress!;
                 int sal = SocketAddressLen;
                 SocketError ec = ErrorCode;
 
@@ -615,12 +615,12 @@ namespace System.Net.Sockets
             }
 
             public override void InvokeCallback(bool allowPooling) =>
-                ((Action<SocketError>)CallbackOrEvent)(ErrorCode);
+                ((Action<SocketError>)CallbackOrEvent!)(ErrorCode);
         }
 
         private sealed class SendFileOperation : WriteOperation
         {
-            public SafeFileHandle FileHandle;
+            public SafeFileHandle FileHandle = null!; // always set when constructed
             public long Offset;
             public long Count;
             public long BytesTransferred;
@@ -635,7 +635,7 @@ namespace System.Net.Sockets
             }
 
             public override void InvokeCallback(bool allowPooling) =>
-                ((Action<long, SocketError>)CallbackOrEvent)(BytesTransferred, ErrorCode);
+                ((Action<long, SocketError>)CallbackOrEvent!)(BytesTransferred, ErrorCode);
 
             protected override bool DoTryComplete(SocketAsyncContext context) =>
                 SocketPal.TryCompleteSendFile(context._socket, FileHandle, ref Offset, ref Count, ref BytesTransferred, out ErrorCode);
@@ -711,7 +711,7 @@ namespace System.Net.Sockets
                                             // since the last time we checked the state of the queue.
                                             // If this happens, we MUST retry the operation, otherwise we risk
                                             // "losing" the notification and causing the operation to pend indefinitely.
-            private AsyncOperation _tail;   // Queue of pending IO operations to process when data becomes available.
+            private AsyncOperation? _tail;   // Queue of pending IO operations to process when data becomes available.
 
             // The _queueLock is used to ensure atomic access to the queue state above.
             // The lock is only ever held briefly, to read and/or update queue state, and
@@ -793,7 +793,7 @@ namespace System.Net.Sockets
                                 // call TryCancel, so we do this after the op is fully enqueued.
                                 if (cancellationToken.CanBeCanceled)
                                 {
-                                    operation.CancellationRegistration = cancellationToken.UnsafeRegister(s => ((TOperation)s).TryCancel(), operation);
+                                    operation.CancellationRegistration = cancellationToken.UnsafeRegister(s => ((TOperation)s!).TryCancel(), operation);
                                 }
 
                                 return true;
@@ -974,7 +974,7 @@ namespace System.Net.Sockets
 
                 // Remove the op from the queue and see if there's more to process.
 
-                AsyncOperation nextOp = null;
+                AsyncOperation? nextOp = null;
                 using (Lock())
                 {
                     if (_state == QueueState.Stopped)
@@ -1015,7 +1015,7 @@ namespace System.Net.Sockets
 
                 // Remove operation from queue.
                 // Note it must be there since it can only be processed and removed by the caller.
-                AsyncOperation nextOp = null;
+                AsyncOperation? nextOp = null;
                 using (Lock())
                 {
                     if (_state == QueueState.Stopped)
@@ -1120,7 +1120,7 @@ namespace System.Net.Sockets
             }
 
             [Conditional("SOCKETASYNCCONTEXT_TRACE")]
-            public void Trace(SocketAsyncContext context, string message, [CallerMemberName] string memberName = null)
+            public void Trace(SocketAsyncContext context, string message, [CallerMemberName] string? memberName = null)
             {
                 string queueType =
                     typeof(TOperation) == typeof(ReadOperation) ? "recv" :
@@ -1436,13 +1436,13 @@ namespace System.Net.Sockets
             return ReceiveFrom(buffer, ref flags, null, ref socketAddressLen, timeout, out bytesReceived);
         }
 
-        public SocketError ReceiveAsync(Memory<byte> buffer, SocketFlags flags, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback, CancellationToken cancellationToken)
+        public SocketError ReceiveAsync(Memory<byte> buffer, SocketFlags flags, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[]?, int, SocketFlags, SocketError> callback, CancellationToken cancellationToken)
         {
             int socketAddressLen = 0;
             return ReceiveFromAsync(buffer, flags, null, ref socketAddressLen, out bytesReceived, out receivedFlags, callback, cancellationToken);
         }
 
-        public SocketError ReceiveFrom(Memory<byte> buffer, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived)
+        public SocketError ReceiveFrom(Memory<byte> buffer, ref SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived)
         {
             Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
 
@@ -1472,7 +1472,7 @@ namespace System.Net.Sockets
             return operation.ErrorCode;
         }
 
-        public unsafe SocketError ReceiveFrom(Span<byte> buffer, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived)
+        public unsafe SocketError ReceiveFrom(Span<byte> buffer, ref SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived)
         {
             SocketFlags receivedFlags;
             SocketError errorCode;
@@ -1504,7 +1504,7 @@ namespace System.Net.Sockets
             }
         }
 
-        public SocketError ReceiveFromAsync(Memory<byte> buffer,  SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback, CancellationToken cancellationToken = default)
+        public SocketError ReceiveFromAsync(Memory<byte> buffer,  SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[]?, int, SocketFlags, SocketError> callback, CancellationToken cancellationToken = default)
         {
             SetNonBlocking();
 
@@ -1543,13 +1543,13 @@ namespace System.Net.Sockets
             return ReceiveFrom(buffers, ref flags, null, 0, timeout, out bytesReceived);
         }
 
-        public SocketError ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback)
+        public SocketError ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[]?, int, SocketFlags, SocketError> callback)
         {
             int socketAddressLen = 0;
             return ReceiveFromAsync(buffers, flags, null, ref socketAddressLen, out bytesReceived, out receivedFlags, callback);
         }
 
-        public SocketError ReceiveFrom(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesReceived)
+        public SocketError ReceiveFrom(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, byte[]? socketAddress, int socketAddressLen, int timeout, out int bytesReceived)
         {
             Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
 
@@ -1580,7 +1580,7 @@ namespace System.Net.Sockets
             return operation.ErrorCode;
         }
 
-        public SocketError ReceiveFromAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[], int, SocketFlags, SocketError> callback)
+        public SocketError ReceiveFromAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, Action<int, byte[]?, int, SocketFlags, SocketError> callback)
         {
             SetNonBlocking();
 
@@ -1617,7 +1617,7 @@ namespace System.Net.Sockets
         }
 
         public SocketError ReceiveMessageFrom(
-            Memory<byte> buffer, IList<ArraySegment<byte>> buffers, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, int timeout, out IPPacketInformation ipPacketInformation, out int bytesReceived)
+            Memory<byte> buffer, IList<ArraySegment<byte>>? buffers, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, int timeout, out IPPacketInformation ipPacketInformation, out int bytesReceived)
         {
             Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
 
@@ -1652,7 +1652,7 @@ namespace System.Net.Sockets
             return operation.ErrorCode;
         }
 
-        public SocketError ReceiveMessageFromAsync(Memory<byte> buffer, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> callback)
+        public SocketError ReceiveMessageFromAsync(Memory<byte> buffer, IList<ArraySegment<byte>>? buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> callback)
         {
             SetNonBlocking();
 
@@ -1699,13 +1699,13 @@ namespace System.Net.Sockets
             return SendTo(buffer, offset, count, flags, null, 0, timeout, out bytesSent);
         }
 
-        public SocketError SendAsync(Memory<byte> buffer, int offset, int count, SocketFlags flags, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback, CancellationToken cancellationToken)
+        public SocketError SendAsync(Memory<byte> buffer, int offset, int count, SocketFlags flags, out int bytesSent, Action<int, byte[]?, int, SocketFlags, SocketError> callback, CancellationToken cancellationToken)
         {
             int socketAddressLen = 0;
             return SendToAsync(buffer, offset, count, flags, null, ref socketAddressLen, out bytesSent, callback, cancellationToken);
         }
 
-        public SocketError SendTo(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
+        public SocketError SendTo(byte[] buffer, int offset, int count, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, int timeout, out int bytesSent)
         {
             Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
 
@@ -1736,7 +1736,7 @@ namespace System.Net.Sockets
             return operation.ErrorCode;
         }
 
-        public unsafe SocketError SendTo(ReadOnlySpan<byte> buffer, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
+        public unsafe SocketError SendTo(ReadOnlySpan<byte> buffer, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, int timeout, out int bytesSent)
         {
             Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
 
@@ -1771,7 +1771,7 @@ namespace System.Net.Sockets
             }
         }
 
-        public SocketError SendToAsync(Memory<byte> buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback, CancellationToken cancellationToken = default)
+        public SocketError SendToAsync(Memory<byte> buffer, int offset, int count, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesSent, Action<int, byte[]?, int, SocketFlags, SocketError> callback, CancellationToken cancellationToken = default)
         {
             SetNonBlocking();
 
@@ -1811,13 +1811,13 @@ namespace System.Net.Sockets
             return SendTo(buffers, flags, null, 0, timeout, out bytesSent);
         }
 
-        public SocketError SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback)
+        public SocketError SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, out int bytesSent, Action<int, byte[]?, int, SocketFlags, SocketError> callback)
         {
             int socketAddressLen = 0;
             return SendToAsync(buffers, flags, null, ref socketAddressLen, out bytesSent, callback);
         }
 
-        public SocketError SendTo(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
+        public SocketError SendTo(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, int timeout, out int bytesSent)
         {
             Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
 
@@ -1850,7 +1850,7 @@ namespace System.Net.Sockets
             return operation.ErrorCode;
         }
 
-        public SocketError SendToAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesSent, Action<int, byte[], int, SocketFlags, SocketError> callback)
+        public SocketError SendToAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesSent, Action<int, byte[]?, int, SocketFlags, SocketError> callback)
         {
             SetNonBlocking();
 
@@ -1975,7 +1975,7 @@ namespace System.Net.Sockets
         // (2) #define SOCKETASYNCCONTEXT_TRACE
 
         [Conditional("SOCKETASYNCCONTEXT_TRACE")]
-        public void Trace(string message, [CallerMemberName] string memberName = null)
+        public void Trace(string message, [CallerMemberName] string? memberName = null)
         {
             OutputTrace($"{IdOf(this)}.{memberName}: {message}");
         }
index 84f733c..8b4e207 100644 (file)
@@ -18,7 +18,7 @@ namespace System.Net.Sockets
         //
         public readonly struct Token
         {
-            private readonly SocketAsyncEngine _engine;
+            private readonly SocketAsyncEngine? _engine;
             private readonly IntPtr _handle;
 
             public Token(SocketAsyncContext context)
@@ -35,14 +35,14 @@ namespace System.Net.Sockets
             {
                 if (WasAllocated)
                 {
-                    _engine.FreeHandle(_handle);
+                    _engine!.FreeHandle(_handle);
                 }
             }
 
             public bool TryRegister(SafeSocketHandle socket, out Interop.Error error)
             {
                 Debug.Assert(WasAllocated, "Expected WasAllocated to be true");
-                return _engine.TryRegister(socket, _handle, out error);
+                return _engine!.TryRegister(socket, _handle, out error);
             }
         }
 
@@ -70,7 +70,7 @@ namespace System.Net.Sockets
         // The current engines. We replace an engine when it runs out of "handle" values.
         // Must be accessed under s_lock.
         //
-        private static readonly SocketAsyncEngine[] s_currentEngines = new SocketAsyncEngine[s_engineCount];
+        private static readonly SocketAsyncEngine?[] s_currentEngines = new SocketAsyncEngine?[s_engineCount];
         private static int s_allocateFromEngine = 0;
 
         private readonly IntPtr _port;
@@ -149,7 +149,7 @@ namespace System.Net.Sockets
         //
         // Allocates a new {SocketAsyncEngine, handle} pair.
         //
-        private static void AllocateToken(SocketAsyncContext context, out SocketAsyncEngine engine, out IntPtr handle)
+        private static void AllocateToken(SocketAsyncContext context, out SocketAsyncEngine? engine, out IntPtr handle)
         {
             lock (s_lock)
             {
@@ -285,7 +285,7 @@ namespace System.Net.Sockets
                 {
                     if (suppressFlow) ExecutionContext.SuppressFlow();
                     Task.Factory.StartNew(
-                        s => ((SocketAsyncEngine)s).EventLoop(),
+                        s => ((SocketAsyncEngine)s!).EventLoop(),
                         this,
                         CancellationToken.None,
                         TaskCreationOptions.LongRunning,
@@ -330,7 +330,7 @@ namespace System.Net.Sockets
                         else
                         {
                             Debug.Assert(handle.ToInt64() < MaxHandles.ToInt64(), $"Unexpected values: handle={handle}, MaxHandles={MaxHandles}");
-                            _handleToContextMap.TryGetValue(handle, out SocketAsyncContext context);
+                            _handleToContextMap.TryGetValue(handle, out SocketAsyncContext? context);
                             if (context != null)
                             {
                                 context.HandleEvents(_buffer[i].Events);
index e722e60..b46cda4 100644 (file)
@@ -14,7 +14,7 @@ namespace System.Net.Sockets
         private IntPtr _acceptedFileDescriptor;
         private int _socketAddressSize;
         private SocketFlags _receivedFlags;
-        private Action<int, byte[], int, SocketFlags, SocketError> _transferCompletionCallback;
+        private Action<int, byte[]?, int, SocketFlags, SocketError>? _transferCompletionCallback;
 
         private void InitializeInternals()
         {
@@ -66,7 +66,7 @@ namespace System.Net.Sockets
             _acceptAddressBufferCount = socketAddressSize;
         }
 
-        internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle)
+        internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle handle, SafeSocketHandle? acceptHandle)
         {
             if (!_buffer.Equals(default))
             {
@@ -79,11 +79,11 @@ namespace System.Net.Sockets
 
             IntPtr acceptedFd;
             int socketAddressLen = _acceptAddressBufferCount / 2;
-            SocketError socketError = handle.AsyncContext.AcceptAsync(_acceptBuffer, ref socketAddressLen, out acceptedFd, AcceptCompletionCallback);
+            SocketError socketError = handle.AsyncContext.AcceptAsync(_acceptBuffer!, ref socketAddressLen, out acceptedFd, AcceptCompletionCallback);
 
             if (socketError != SocketError.IOPending)
             {
-                CompleteAcceptOperation(acceptedFd, _acceptBuffer, socketAddressLen, socketError);
+                CompleteAcceptOperation(acceptedFd, _acceptBuffer!, socketAddressLen, socketError);
                 FinishOperationSync(socketError, 0, SocketFlags.None);
             }
 
@@ -97,7 +97,7 @@ namespace System.Net.Sockets
 
         internal unsafe SocketError DoOperationConnect(Socket socket, SafeSocketHandle handle)
         {
-            SocketError socketError = handle.AsyncContext.ConnectAsync(_socketAddress.Buffer, _socketAddress.Size, ConnectCompletionCallback);
+            SocketError socketError = handle.AsyncContext.ConnectAsync(_socketAddress!.Buffer, _socketAddress.Size, ConnectCompletionCallback);
             if (socketError != SocketError.IOPending)
             {
                 FinishOperationSync(socketError, 0, SocketFlags.None);
@@ -112,19 +112,19 @@ namespace System.Net.Sockets
             return socketError;
         }
 
-        private Action<int, byte[], int, SocketFlags, SocketError> TransferCompletionCallback =>
+        private Action<int, byte[]?, int, SocketFlags, SocketError> TransferCompletionCallback =>
             _transferCompletionCallback ?? (_transferCompletionCallback = TransferCompletionCallbackCore);
 
-        private void TransferCompletionCallbackCore(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError)
+        private void TransferCompletionCallbackCore(int bytesTransferred, byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError)
         {
             CompleteTransferOperation(bytesTransferred, socketAddress, socketAddressSize, receivedFlags, socketError);
 
             CompletionCallback(bytesTransferred, receivedFlags, socketError);
         }
 
-        private void CompleteTransferOperation(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError)
+        private void CompleteTransferOperation(int bytesTransferred, byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError)
         {
-            Debug.Assert(socketAddress == null || socketAddress == _socketAddress.Buffer, $"Unexpected socketAddress: {socketAddress}");
+            Debug.Assert(socketAddress == null || socketAddress == _socketAddress!.Buffer, $"Unexpected socketAddress: {socketAddress}");
             _socketAddressSize = socketAddressSize;
             _receivedFlags = receivedFlags;
         }
@@ -143,7 +143,7 @@ namespace System.Net.Sockets
             }
             else
             {
-                errorCode = handle.AsyncContext.ReceiveAsync(_bufferListInternal, _socketFlags, out bytesReceived, out flags, TransferCompletionCallback);
+                errorCode = handle.AsyncContext.ReceiveAsync(_bufferListInternal!, _socketFlags, out bytesReceived, out flags, TransferCompletionCallback);
             }
 
             if (errorCode != SocketError.IOPending)
@@ -163,14 +163,14 @@ namespace System.Net.Sockets
             SocketFlags flags;
             SocketError errorCode;
             int bytesReceived = 0;
-            int socketAddressLen = _socketAddress.Size;
+            int socketAddressLen = _socketAddress!.Size;
             if (_bufferList == null)
             {
                 errorCode = handle.AsyncContext.ReceiveFromAsync(_buffer.Slice(_offset, _count), _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesReceived, out flags, TransferCompletionCallback);
             }
             else
             {
-                errorCode = handle.AsyncContext.ReceiveFromAsync(_bufferListInternal, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesReceived, out flags, TransferCompletionCallback);
+                errorCode = handle.AsyncContext.ReceiveFromAsync(_bufferListInternal!, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesReceived, out flags, TransferCompletionCallback);
             }
 
             if (errorCode != SocketError.IOPending)
@@ -206,9 +206,9 @@ namespace System.Net.Sockets
             _socketAddressSize = 0;
 
             bool isIPv4, isIPv6;
-            Socket.GetIPProtocolInformation(socket.AddressFamily, _socketAddress, out isIPv4, out isIPv6);
+            Socket.GetIPProtocolInformation(socket.AddressFamily, _socketAddress!, out isIPv4, out isIPv6);
 
-            int socketAddressSize = _socketAddress.Size;
+            int socketAddressSize = _socketAddress!.Size;
             int bytesReceived;
             SocketFlags receivedFlags;
             IPPacketInformation ipPacketInformation;
@@ -234,7 +234,7 @@ namespace System.Net.Sockets
             }
             else
             {
-                errorCode = handle.AsyncContext.SendAsync(_bufferListInternal, _socketFlags, out bytesSent, TransferCompletionCallback);
+                errorCode = handle.AsyncContext.SendAsync(_bufferListInternal!, _socketFlags, out bytesSent, TransferCompletionCallback);
             }
 
             if (errorCode != SocketError.IOPending)
@@ -258,7 +258,7 @@ namespace System.Net.Sockets
             {
                 for (int i = 0; i < elements.Length; i++)
                 {
-                    string path = elements[i]?.FilePath;
+                    string? path = elements[i]?.FilePath;
                     if (path != null)
                     {
                         files[i] = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, useAsync: true);
@@ -279,7 +279,7 @@ namespace System.Net.Sockets
                 // this check, but it's good enough for most situations.
                 if (exc is FileNotFoundException fnfe)
                 {
-                    string dirname = Path.GetDirectoryName(fnfe.FileName);
+                    string? dirname = Path.GetDirectoryName(fnfe.FileName);
                     if (!string.IsNullOrEmpty(dirname) && !Directory.Exists(dirname))
                     {
                         throw new DirectoryNotFoundException(fnfe.Message);
@@ -311,7 +311,7 @@ namespace System.Net.Sockets
             _socketAddressSize = 0;
 
             int bytesSent;
-            int socketAddressLen = _socketAddress.Size;
+            int socketAddressLen = _socketAddress!.Size;
             SocketError errorCode;
             if (_bufferList == null)
             {
@@ -319,7 +319,7 @@ namespace System.Net.Sockets
             }
             else
             {
-                errorCode = handle.AsyncContext.SendToAsync(_bufferListInternal, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesSent, TransferCompletionCallback);
+                errorCode = handle.AsyncContext.SendToAsync(_bufferListInternal!, _socketFlags, _socketAddress.Buffer, ref socketAddressLen, out bytesSent, TransferCompletionCallback);
             }
 
             if (errorCode != SocketError.IOPending)
@@ -350,10 +350,10 @@ namespace System.Net.Sockets
 
         private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress)
         {
-            System.Buffer.BlockCopy(_acceptBuffer, 0, remoteSocketAddress.Buffer, 0, _acceptAddressBufferCount);
-            _acceptSocket = _currentSocket.CreateAcceptSocket(
+            System.Buffer.BlockCopy(_acceptBuffer!, 0, remoteSocketAddress.Buffer, 0, _acceptAddressBufferCount);
+            _acceptSocket = _currentSocket!.CreateAcceptSocket(
                 SocketPal.CreateSocket(_acceptedFileDescriptor),
-                _currentSocket._rightEndPoint.Create(remoteSocketAddress));
+                _currentSocket._rightEndPoint!.Create(remoteSocketAddress));
             return SocketError.Success;
         }
 
@@ -386,7 +386,7 @@ namespace System.Net.Sockets
             }
             else
             {
-                if (_currentSocket.Disposed)
+                if (_currentSocket!.Disposed)
                 {
                     socketError = SocketError.OperationAborted;
                 }
index 29a0226..adb2cab 100644 (file)
@@ -21,27 +21,27 @@ namespace System.Net.Sockets
         // BufferList property variables.
         // Note that these arrays are allocated and then grown as necessary, but never shrunk.
         // Thus the actual in-use length is defined by _bufferListInternal.Count, not the length of these arrays.
-        private WSABuffer[] _wsaBufferArray;
-        private GCHandle[] _multipleBufferGCHandles;
+        private WSABuffer[]? _wsaBufferArray;
+        private GCHandle[]? _multipleBufferGCHandles;
 
         // Internal buffers for WSARecvMsg
-        private byte[] _wsaMessageBuffer;
+        private byte[]? _wsaMessageBuffer;
         private GCHandle _wsaMessageBufferGCHandle;
-        private byte[] _controlBuffer;
+        private byte[]? _controlBuffer;
         private GCHandle _controlBufferGCHandle;
-        private WSABuffer[] _wsaRecvMsgWSABufferArray;
+        private WSABuffer[]? _wsaRecvMsgWSABufferArray;
         private GCHandle _wsaRecvMsgWSABufferArrayGCHandle;
 
         // Internal SocketAddress buffer
         private GCHandle _socketAddressGCHandle;
-        private Internals.SocketAddress _pinnedSocketAddress;
+        private Internals.SocketAddress? _pinnedSocketAddress;
 
         // SendPacketsElements property variables.
-        private FileStream[] _sendPacketsFileStreams;
+        private FileStream[]? _sendPacketsFileStreams;
 
         // Overlapped object related variables.
-        private PreAllocatedOverlapped _preAllocatedOverlapped;
-        private readonly StrongBox<SocketAsyncEventArgs> _strongThisRef = new StrongBox<SocketAsyncEventArgs>(); // state for _preAllocatedOverlapped; .Value set to this while operations in flight
+        private PreAllocatedOverlapped _preAllocatedOverlapped = null!; // initialized by helper called from ctor
+        private readonly StrongBox<SocketAsyncEventArgs?> _strongThisRef = new StrongBox<SocketAsyncEventArgs?>(); // state for _preAllocatedOverlapped; .Value set to this while operations in flight
 
         // Cancellation support
         private CancellationTokenRegistration _registrationToCancelPendingIO;
@@ -107,8 +107,8 @@ namespace System.Net.Sockets
             {
                 // Try to cancel the I/O.  We ignore the return value (other than for logging), as cancellation
                 // is opportunistic and we don't want to fail the operation because we couldn't cancel it.
-                var thisRef = (SocketAsyncEventArgs)s;
-                SafeSocketHandle handle = thisRef._currentSocket.SafeHandle;
+                var thisRef = (SocketAsyncEventArgs)s!;
+                SafeSocketHandle handle = thisRef._currentSocket!.SafeHandle;
                 if (!handle.IsClosed)
                 {
                     try
@@ -151,7 +151,7 @@ namespace System.Net.Sockets
             if (success)
             {
                 // Synchronous success.
-                if (_currentSocket.SafeHandle.SkipCompletionPortOnSuccess)
+                if (_currentSocket!.SafeHandle.SkipCompletionPortOnSuccess)
                 {
                     // The socket handle is configured to skip completion on success,
                     // so we can set the results right now.
@@ -197,7 +197,7 @@ namespace System.Net.Sockets
             if (socketError == SocketError.Success)
             {
                 // Synchronous success.
-                if (_currentSocket.SafeHandle.SkipCompletionPortOnSuccess)
+                if (_currentSocket!.SafeHandle.SkipCompletionPortOnSuccess)
                 {
                     // The socket handle is configured to skip completion on success,
                     // so we can set the results right now.
@@ -288,7 +288,7 @@ namespace System.Net.Sockets
                 bool success = socket.ConnectEx(
                     handle,
                     PtrSocketAddressBuffer,
-                    _socketAddress.Size,
+                    _socketAddress!.Size,
                     (IntPtr)((byte*)_singleBufferHandle.Pointer + _offset),
                     _count,
                     out int bytesTransferred,
@@ -370,7 +370,7 @@ namespace System.Net.Sockets
                 SocketError socketError = Interop.Winsock.WSARecv(
                     handle,
                     _wsaBufferArray,
-                    _bufferListInternal.Count,
+                    _bufferListInternal!.Count,
                     out int bytesTransferred,
                     ref flags,
                     overlapped,
@@ -441,8 +441,8 @@ namespace System.Net.Sockets
                 SocketFlags flags = _socketFlags;
                 SocketError socketError = Interop.Winsock.WSARecvFrom(
                     handle,
-                    _wsaBufferArray,
-                    _bufferListInternal.Count,
+                    _wsaBufferArray!,
+                    _bufferListInternal!.Count,
                     out int bytesTransferred,
                     ref flags,
                     PtrSocketAddressBuffer,
@@ -484,8 +484,8 @@ namespace System.Net.Sockets
             }
 
             // Create and pin an appropriately sized control buffer if none already
-            IPAddress ipAddress = (_socketAddress.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null);
-            bool ipv4 = (_currentSocket.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode
+            IPAddress? ipAddress = (_socketAddress!.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null);
+            bool ipv4 = (_currentSocket!.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode
             bool ipv6 = _currentSocket.AddressFamily == AddressFamily.InterNetworkV6;
 
             if (ipv4 && (_controlBuffer == null || _controlBuffer.Length != sizeof(Interop.Winsock.ControlData)))
@@ -527,8 +527,8 @@ namespace System.Net.Sockets
             else
             {
                 // Use the multi-buffer WSABuffer.
-                wsaRecvMsgWSABufferArray = _wsaBufferArray;
-                wsaRecvMsgWSABufferCount = (uint)_bufferListInternal.Count;
+                wsaRecvMsgWSABufferArray = _wsaBufferArray!;
+                wsaRecvMsgWSABufferCount = (uint)_bufferListInternal!.Count;
             }
 
             // Ensure the array is pinned.
@@ -632,7 +632,7 @@ namespace System.Net.Sockets
                 SocketError socketError = Interop.Winsock.WSASend(
                     handle,
                     _wsaBufferArray,
-                    _bufferListInternal.Count,
+                    _bufferListInternal!.Count,
                     out int bytesTransferred,
                     _socketFlags,
                     overlapped,
@@ -779,7 +779,7 @@ namespace System.Net.Sockets
                         out int bytesTransferred,
                         _socketFlags,
                         PtrSocketAddressBuffer,
-                        _socketAddress.Size,
+                        _socketAddress!.Size,
                         overlapped,
                         IntPtr.Zero);
 
@@ -801,12 +801,12 @@ namespace System.Net.Sockets
             {
                 SocketError socketError = Interop.Winsock.WSASendTo(
                     handle,
-                    _wsaBufferArray,
-                    _bufferListInternal.Count,
+                    _wsaBufferArray!,
+                    _bufferListInternal!.Count,
                     out int bytesTransferred,
                     _socketFlags,
                     PtrSocketAddressBuffer,
-                    _socketAddress.Size,
+                    _socketAddress!.Size,
                     overlapped,
                     IntPtr.Zero);
 
@@ -870,7 +870,7 @@ namespace System.Net.Sockets
                     for (int i = 0; i < bufferCount; i++)
                     {
                         ArraySegment<byte> localCopy = _bufferListInternal[i];
-                        _wsaBufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array, localCopy.Offset);
+                        _wsaBufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array!, localCopy.Offset);
                         _wsaBufferArray[i].Length = localCopy.Count;
                     }
 
@@ -900,7 +900,7 @@ namespace System.Net.Sockets
             }
 
             // Pin down the new one.
-            _socketAddressGCHandle = GCHandle.Alloc(_socketAddress.Buffer, GCHandleType.Pinned);
+            _socketAddressGCHandle = GCHandle.Alloc(_socketAddress!.Buffer, GCHandleType.Pinned);
             _socketAddress.CopyAddressSizeIntoBuffer();
             _pinnedSocketAddress = _socketAddress;
         }
@@ -921,7 +921,7 @@ namespace System.Net.Sockets
             }
         }
 
-        private IntPtr PtrSocketAddressBufferSize => PtrSocketAddressBuffer + _socketAddress.GetAddressSizeOffset();
+        private IntPtr PtrSocketAddressBufferSize => PtrSocketAddressBuffer + _socketAddress!.GetAddressSizeOffset();
 
         // Cleans up any existing Overlapped object and related state variables.
         private void FreeOverlapped()
@@ -931,7 +931,7 @@ namespace System.Net.Sockets
             if (_preAllocatedOverlapped != null)
             {
                 _preAllocatedOverlapped.Dispose();
-                _preAllocatedOverlapped = null;
+                _preAllocatedOverlapped = null!;
             }
         }
 
@@ -1043,7 +1043,7 @@ namespace System.Net.Sockets
                     else if (spe.FilePath != null)
                     {
                         // This element is a file.
-                        sendPacketsDescriptor[descriptorIndex].fileHandle = _sendPacketsFileStreams[fileIndex].SafeFileHandle.DangerousGetHandle();
+                        sendPacketsDescriptor[descriptorIndex].fileHandle = _sendPacketsFileStreams![fileIndex].SafeFileHandle.DangerousGetHandle();
                         sendPacketsDescriptor[descriptorIndex].fileOffset = spe.OffsetLong;
                         sendPacketsDescriptor[descriptorIndex].length = (uint)spe.Count;
                         sendPacketsDescriptor[descriptorIndex].flags =
@@ -1084,9 +1084,9 @@ namespace System.Net.Sockets
 
             if (_bufferList != null)
             {
-                for (int i = 0; i < _bufferListInternal.Count; i++)
+                for (int i = 0; i < _bufferListInternal!.Count; i++)
                 {
-                    WSABuffer wsaBuffer = _wsaBufferArray[i];
+                    WSABuffer wsaBuffer = _wsaBufferArray![i];
                     NetEventSource.DumpBuffer(this, wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
                     if ((size -= wsaBuffer.Length) <= 0)
                     {
@@ -1108,7 +1108,7 @@ namespace System.Net.Sockets
             IntPtr remoteAddr;
 
             bool refAdded = false;
-            SafeHandle safeHandle = _currentSocket.SafeHandle;
+            SafeHandle safeHandle = _currentSocket!.SafeHandle;
             try
             {
                 safeHandle.DangerousAddRef(ref refAdded);
@@ -1130,7 +1130,7 @@ namespace System.Net.Sockets
                 Marshal.Copy(remoteAddr, remoteSocketAddress.Buffer, 0, remoteSocketAddress.Size);
 
                 socketError = Interop.Winsock.setsockopt(
-                    _acceptSocket.SafeHandle,
+                    _acceptSocket!.SafeHandle,
                     SocketOptionLevel.Socket,
                     SocketOptionName.UpdateAcceptContext,
                     ref handle,
@@ -1162,7 +1162,7 @@ namespace System.Net.Sockets
             {
                 // Update the socket context.
                 SocketError socketError = Interop.Winsock.setsockopt(
-                    _currentSocket.SafeHandle,
+                    _currentSocket!.SafeHandle,
                     SocketOptionLevel.Socket,
                     SocketOptionName.UpdateConnectContext,
                     null,
@@ -1218,9 +1218,9 @@ namespace System.Net.Sockets
 
         private unsafe void FinishOperationReceiveMessageFrom()
         {
-            Interop.Winsock.WSAMsg* PtrMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
+            Interop.Winsock.WSAMsg* PtrMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer!, 0);
 
-            if (_controlBuffer.Length == sizeof(Interop.Winsock.ControlData))
+            if (_controlBuffer!.Length == sizeof(Interop.Winsock.ControlData))
             {
                 // IPv4.
                 _receiveMessageFromPacketInfo = SocketPal.GetIPPacketInformation((Interop.Winsock.ControlData*)PtrMessage->controlBuffer.Pointer);
@@ -1253,9 +1253,9 @@ namespace System.Net.Sockets
 
         private static readonly unsafe IOCompletionCallback s_completionPortCallback = delegate (uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
         {
-            var saeaBox = (StrongBox<SocketAsyncEventArgs>)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped);
+            var saeaBox = (StrongBox<SocketAsyncEventArgs>)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!;
+            Debug.Assert(saeaBox.Value != null);
             SocketAsyncEventArgs saea = saeaBox.Value;
-            Debug.Assert(saea != null);
 
             if ((SocketError)errorCode == SocketError.Success)
             {
@@ -1275,7 +1275,7 @@ namespace System.Net.Sockets
 
             if (socketError != SocketError.OperationAborted)
             {
-                if (_currentSocket.Disposed)
+                if (_currentSocket!.Disposed)
                 {
                     socketError = SocketError.OperationAborted;
                 }
index 60bde3e..9a38815 100644 (file)
@@ -12,8 +12,8 @@ namespace System.Net.Sockets
     public partial class SocketAsyncEventArgs : EventArgs, IDisposable
     {
         // AcceptSocket property variables.
-        private Socket _acceptSocket;
-        private Socket _connectSocket;
+        private Socket? _acceptSocket;
+        private Socket? _connectSocket;
 
         // Single buffer.
         private Memory<byte> _buffer;
@@ -22,8 +22,8 @@ namespace System.Net.Sockets
         private bool _bufferIsExplicitArray;
 
         // BufferList property variables.
-        private IList<ArraySegment<byte>> _bufferList;
-        private List<ArraySegment<byte>> _bufferListInternal;
+        private IList<ArraySegment<byte>>? _bufferList;
+        private List<ArraySegment<byte>>? _bufferListInternal;
 
         // BytesTransferred property variables.
         private int _bytesTransferred;
@@ -38,39 +38,39 @@ namespace System.Net.Sockets
         private IPPacketInformation _receiveMessageFromPacketInfo;
 
         // RemoteEndPoint property variables.
-        private EndPoint _remoteEndPoint;
+        private EndPoint? _remoteEndPoint;
 
         // SendPacketsSendSize property variable.
         private int _sendPacketsSendSize;
 
         // SendPacketsElements property variables.
-        private SendPacketsElement[] _sendPacketsElements;
+        private SendPacketsElement[]? _sendPacketsElements;
 
         // SendPacketsFlags property variable.
         private TransmitFileOptions _sendPacketsFlags;
 
         // SocketError property variables.
         private SocketError _socketError;
-        private Exception _connectByNameError;
+        private Exception? _connectByNameError;
 
         // SocketFlags property variables.
         private SocketFlags _socketFlags;
 
         // UserToken property variables.
-        private object _userToken;
+        private object? _userToken;
 
         // Internal buffer for AcceptEx when Buffer not supplied.
-        private byte[] _acceptBuffer;
+        private byte[]? _acceptBuffer;
         private int _acceptAddressBufferCount;
 
         // Internal SocketAddress buffer.
-        internal Internals.SocketAddress _socketAddress;
+        internal Internals.SocketAddress? _socketAddress;
 
         // Misc state variables.
         private readonly bool _flowExecutionContext;
-        private ExecutionContext _context;
+        private ExecutionContext? _context;
         private static readonly ContextCallback s_executionCallback = ExecutionCallback;
-        private Socket _currentSocket;
+        private Socket? _currentSocket;
         private bool _userSocket; // if false when performing Connect, _currentSocket should be disposed
         private bool _disposeCalled;
 
@@ -81,7 +81,7 @@ namespace System.Net.Sockets
         private const int Disposed = 2;
         private int _operating;
 
-        private MultipleConnectAsync _multipleConnect;
+        private MultipleConnectAsync? _multipleConnect;
 
         public SocketAsyncEventArgs() : this(unsafeSuppressExecutionContextFlow: false)
         {
@@ -98,18 +98,18 @@ namespace System.Net.Sockets
             InitializeInternals();
         }
 
-        public Socket AcceptSocket
+        public Socket? AcceptSocket
         {
             get { return _acceptSocket; }
             set { _acceptSocket = value; }
         }
 
-        public Socket ConnectSocket
+        public Socket? ConnectSocket
         {
             get { return _connectSocket; }
         }
 
-        public byte[] Buffer
+        public byte[]? Buffer
         {
             get
             {
@@ -139,7 +139,7 @@ namespace System.Net.Sockets
 
         // NOTE: this property is mutually exclusive with Buffer.
         // Setting this property with an existing non-null Buffer will throw.
-        public IList<ArraySegment<byte>> BufferList
+        public IList<ArraySegment<byte>>? BufferList
         {
             get { return _bufferList; }
             set
@@ -196,7 +196,7 @@ namespace System.Net.Sockets
             get { return _bytesTransferred; }
         }
 
-        public event EventHandler<SocketAsyncEventArgs> Completed;
+        public event EventHandler<SocketAsyncEventArgs>? Completed;
 
         protected virtual void OnCompleted(SocketAsyncEventArgs e)
         {
@@ -220,13 +220,13 @@ namespace System.Net.Sockets
             get { return _receiveMessageFromPacketInfo; }
         }
 
-        public EndPoint RemoteEndPoint
+        public EndPoint? RemoteEndPoint
         {
             get { return _remoteEndPoint; }
             set { _remoteEndPoint = value; }
         }
 
-        public SendPacketsElement[] SendPacketsElements
+        public SendPacketsElement[]? SendPacketsElements
         {
             get { return _sendPacketsElements; }
             set
@@ -255,7 +255,7 @@ namespace System.Net.Sockets
             set { _socketError = value; }
         }
 
-        public Exception ConnectByNameError
+        public Exception? ConnectByNameError
         {
             get { return _connectByNameError; }
         }
@@ -266,7 +266,7 @@ namespace System.Net.Sockets
             set { _socketFlags = value; }
         }
 
-        public object UserToken
+        public object? UserToken
         {
             get { return _userToken; }
             set { _userToken = value; }
@@ -318,7 +318,7 @@ namespace System.Net.Sockets
             }
         }
 
-        public void SetBuffer(byte[] buffer, int offset, int count)
+        public void SetBuffer(byte[]? buffer, int offset, int count)
         {
             StartConfiguring();
             try
@@ -405,7 +405,7 @@ namespace System.Net.Sockets
             }
             else
             {
-                SocketException socketException = exception as SocketException;
+                SocketException? socketException = exception as SocketException;
                 if (socketException != null)
                 {
                     _socketError = socketException.SocketErrorCode;
@@ -417,9 +417,9 @@ namespace System.Net.Sockets
             }
         }
 
-        private static void ExecutionCallback(object state)
+        private static void ExecutionCallback(object? state)
         {
-            var thisRef = (SocketAsyncEventArgs)state;
+            var thisRef = (SocketAsyncEventArgs)state!;
             thisRef.OnCompleted(thisRef);
         }
 
@@ -495,7 +495,7 @@ namespace System.Net.Sockets
 
         // Prepares for a native async socket call.
         // This method performs the tasks common to all socket operations.
-        internal void StartOperationCommon(Socket socket, SocketAsyncOperation operation)
+        internal void StartOperationCommon(Socket? socket, SocketAsyncOperation operation)
         {
             // Change status to "in-use".
             int status = Interlocked.CompareExchange(ref _operating, InProgress, Free);
@@ -524,7 +524,7 @@ namespace System.Net.Sockets
             // AcceptEx needs a single buffer that's the size of two native sockaddr buffers with 16
             // extra bytes each. It can also take additional buffer space in front of those special
             // sockaddr structures that can be filled in with initial data coming in on a connection.
-            _acceptAddressBufferCount = 2 * (Socket.GetAddressSize(_currentSocket._rightEndPoint) + 16);
+            _acceptAddressBufferCount = 2 * (Socket.GetAddressSize(_currentSocket!._rightEndPoint!) + 16);
 
             // If our caller specified a buffer (willing to get received data with the Accept) then
             // it needs to be large enough for the two special sockaddr buffers that AcceptEx requires.
@@ -549,7 +549,7 @@ namespace System.Net.Sockets
             }
         }
 
-        internal void StartOperationConnect(MultipleConnectAsync multipleConnect, bool userSocket)
+        internal void StartOperationConnect(MultipleConnectAsync? multipleConnect, bool userSocket)
         {
             _multipleConnect = multipleConnect;
             _connectSocket = null;
@@ -586,7 +586,7 @@ namespace System.Net.Sockets
             // the attempt socket will be closed anyways, so not updating the state is OK.
             // If we're doing a static ConnectAsync to an IPEndPoint, we need to dispose
             // of the socket, as we manufactured it and the caller has no opportunity to do so.
-            Socket currentSocket = _currentSocket;
+            Socket? currentSocket = _currentSocket;
             if (currentSocket != null)
             {
                 currentSocket.UpdateStatusAfterSocketError(socketError);
@@ -619,7 +619,7 @@ namespace System.Net.Sockets
 
         internal void FinishOperationAsyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
         {
-            ExecutionContext context = _context; // store context before it's cleared as part of finishing the operation
+            ExecutionContext? context = _context; // store context before it's cleared as part of finishing the operation
 
             FinishOperationSyncFailure(socketError, bytesTransferred, flags);
 
@@ -635,7 +635,7 @@ namespace System.Net.Sockets
 
         internal void FinishConnectByNameAsyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
         {
-            ExecutionContext context = _context; // store context before it's cleared as part of finishing the operation
+            ExecutionContext? context = _context; // store context before it's cleared as part of finishing the operation
 
             FinishConnectByNameSyncFailure(exception, bytesTransferred, flags);
 
@@ -649,14 +649,14 @@ namespace System.Net.Sockets
             }
         }
 
-        internal void FinishWrapperConnectSuccess(Socket connectSocket, int bytesTransferred, SocketFlags flags)
+        internal void FinishWrapperConnectSuccess(Socket? connectSocket, int bytesTransferred, SocketFlags flags)
         {
             SetResults(SocketError.Success, bytesTransferred, flags);
             _currentSocket = connectSocket;
             _connectSocket = connectSocket;
 
             // Complete the operation and raise the event.
-            ExecutionContext context = _context; // store context before it's cleared as part of completing the operation
+            ExecutionContext? context = _context; // store context before it's cleared as part of completing the operation
             Complete();
             if (context == null)
             {
@@ -682,13 +682,13 @@ namespace System.Net.Sockets
             {
                 case SocketAsyncOperation.Accept:
                     // Get the endpoint.
-                    Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket._rightEndPoint);
+                    Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket!._rightEndPoint!);
 
                     socketError = FinishOperationAccept(remoteSocketAddress);
 
                     if (socketError == SocketError.Success)
                     {
-                        _acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket, _currentSocket._rightEndPoint.Create(remoteSocketAddress));
+                        _acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket!, _currentSocket._rightEndPoint!.Create(remoteSocketAddress));
 
                         if (NetEventSource.IsEnabled) NetEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
                     }
@@ -704,33 +704,33 @@ namespace System.Net.Sockets
                     socketError = FinishOperationConnect();
                     if (socketError == SocketError.Success)
                     {
-                        if (NetEventSource.IsEnabled) NetEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint);
+                        if (NetEventSource.IsEnabled) NetEventSource.Connected(_currentSocket!, _currentSocket!.LocalEndPoint, _currentSocket.RemoteEndPoint);
 
                         // Mark socket connected.
-                        _currentSocket.SetToConnected();
+                        _currentSocket!.SetToConnected();
                         _connectSocket = _currentSocket;
                     }
                     else
                     {
                         SetResults(socketError, bytesTransferred, flags);
-                        _currentSocket.UpdateStatusAfterSocketError(socketError);
+                        _currentSocket!.UpdateStatusAfterSocketError(socketError);
                     }
                     break;
 
                 case SocketAsyncOperation.Disconnect:
-                    _currentSocket.SetToDisconnected();
+                    _currentSocket!.SetToDisconnected();
                     _currentSocket._remoteEndPoint = null;
                     break;
 
                 case SocketAsyncOperation.ReceiveFrom:
                     // Deal with incoming address.
-                    _socketAddress.InternalSize = GetSocketAddressSize();
-                    Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
+                    _socketAddress!.InternalSize = GetSocketAddressSize();
+                    Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint!);
                     if (!socketAddressOriginal.Equals(_socketAddress))
                     {
                         try
                         {
-                            _remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
+                            _remoteEndPoint = _remoteEndPoint!.Create(_socketAddress);
                         }
                         catch
                         {
@@ -740,13 +740,13 @@ namespace System.Net.Sockets
 
                 case SocketAsyncOperation.ReceiveMessageFrom:
                     // Deal with incoming address.
-                    _socketAddress.InternalSize = GetSocketAddressSize();
-                    socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
+                    _socketAddress!.InternalSize = GetSocketAddressSize();
+                    socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint!);
                     if (!socketAddressOriginal.Equals(_socketAddress))
                     {
                         try
                         {
-                            _remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
+                            _remoteEndPoint = _remoteEndPoint!.Create(_socketAddress);
                         }
                         catch
                         {
@@ -766,7 +766,7 @@ namespace System.Net.Sockets
 
         internal void FinishOperationAsyncSuccess(int bytesTransferred, SocketFlags flags)
         {
-            ExecutionContext context = _context; // store context before it's cleared as part of finishing the operation
+            ExecutionContext? context = _context; // store context before it's cleared as part of finishing the operation
 
             FinishOperationSyncSuccess(bytesTransferred, flags);
 
index 0946c9b..59626a5 100644 (file)
@@ -95,7 +95,7 @@ namespace System.Net.Sockets
             return errorCode;
         }
 
-        private static unsafe int Receive(SafeSocketHandle socket, SocketFlags flags, Span<byte> buffer, byte[] socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
+        private static unsafe int Receive(SafeSocketHandle socket, SocketFlags flags, Span<byte> buffer, byte[]? socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
         {
             Debug.Assert(socketAddress != null || socketAddressLen == 0, $"Unexpected values: socketAddress={socketAddress}, socketAddressLen={socketAddressLen}");
 
@@ -136,7 +136,7 @@ namespace System.Net.Sockets
             return checked((int)received);
         }
 
-        private static unsafe int Send(SafeSocketHandle socket, SocketFlags flags, ReadOnlySpan<byte> buffer, ref int offset, ref int count, byte[] socketAddress, int socketAddressLen, out Interop.Error errno)
+        private static unsafe int Send(SafeSocketHandle socket, SocketFlags flags, ReadOnlySpan<byte> buffer, ref int offset, ref int count, byte[]? socketAddress, int socketAddressLen, out Interop.Error errno)
         {
             int sent;
             fixed (byte* sockAddr = socketAddress)
@@ -176,7 +176,7 @@ namespace System.Net.Sockets
             return sent;
         }
 
-        private static unsafe int Send(SafeSocketHandle socket, SocketFlags flags, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, byte[] socketAddress, int socketAddressLen, out Interop.Error errno)
+        private static unsafe int Send(SafeSocketHandle socket, SocketFlags flags, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, byte[]? socketAddress, int socketAddressLen, out Interop.Error errno)
         {
             // Pin buffers and set up iovecs.
             int startIndex = bufferIndex, startOffset = offset;
@@ -273,7 +273,7 @@ namespace System.Net.Sockets
             return bytesSent;
         }
 
-        private static unsafe int Receive(SafeSocketHandle socket, SocketFlags flags, IList<ArraySegment<byte>> buffers, byte[] socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
+        private static unsafe int Receive(SafeSocketHandle socket, SocketFlags flags, IList<ArraySegment<byte>> buffers, byte[]? socketAddress, ref int socketAddressLen, out SocketFlags receivedFlags, out Interop.Error errno)
         {
             int available = 0;
             errno = Interop.Sys.GetBytesAvailable(socket, &available);
@@ -610,13 +610,13 @@ namespace System.Net.Sockets
             return true;
         }
 
-        public static bool TryCompleteReceiveFrom(SafeSocketHandle socket, Span<byte> buffer, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode) =>
+        public static bool TryCompleteReceiveFrom(SafeSocketHandle socket, Span<byte> buffer, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode) =>
             TryCompleteReceiveFrom(socket, buffer, null, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode);
 
-        public static bool TryCompleteReceiveFrom(SafeSocketHandle socket, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode) =>
+        public static bool TryCompleteReceiveFrom(SafeSocketHandle socket, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode) =>
             TryCompleteReceiveFrom(socket, default(Span<byte>), buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode);
 
-        public static unsafe bool TryCompleteReceiveFrom(SafeSocketHandle socket, Span<byte> buffer, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode)
+        public static unsafe bool TryCompleteReceiveFrom(SafeSocketHandle socket, Span<byte> buffer, IList<ArraySegment<byte>>? buffers, SocketFlags flags, byte[]? socketAddress, ref int socketAddressLen, out int bytesReceived, out SocketFlags receivedFlags, out SocketError errorCode)
         {
             try
             {
@@ -676,7 +676,7 @@ namespace System.Net.Sockets
             }
         }
 
-        public static unsafe bool TryCompleteReceiveMessageFrom(SafeSocketHandle socket, Span<byte> buffer, IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out SocketError errorCode)
+        public static unsafe bool TryCompleteReceiveMessageFrom(SafeSocketHandle socket, Span<byte> buffer, IList<ArraySegment<byte>>? buffers, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out SocketError errorCode)
         {
             try
             {
@@ -715,25 +715,25 @@ namespace System.Net.Sockets
             }
         }
 
-        public static bool TryCompleteSendTo(SafeSocketHandle socket, Span<byte> buffer, ref int offset, ref int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
+        public static bool TryCompleteSendTo(SafeSocketHandle socket, Span<byte> buffer, ref int offset, ref int count, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
         {
             int bufferIndex = 0;
             return TryCompleteSendTo(socket, buffer, null, ref bufferIndex, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode);
         }
 
-        public static bool TryCompleteSendTo(SafeSocketHandle socket, ReadOnlySpan<byte> buffer, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
+        public static bool TryCompleteSendTo(SafeSocketHandle socket, ReadOnlySpan<byte> buffer, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
         {
             int bufferIndex = 0, offset = 0, count = buffer.Length;
             return TryCompleteSendTo(socket, buffer, null, ref bufferIndex, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode);
         }
 
-        public static bool TryCompleteSendTo(SafeSocketHandle socket, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
+        public static bool TryCompleteSendTo(SafeSocketHandle socket, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
         {
             int count = 0;
             return TryCompleteSendTo(socket, default(ReadOnlySpan<byte>), buffers, ref bufferIndex, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode);
         }
 
-        public static bool TryCompleteSendTo(SafeSocketHandle socket, ReadOnlySpan<byte> buffer, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, ref int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
+        public static bool TryCompleteSendTo(SafeSocketHandle socket, ReadOnlySpan<byte> buffer, IList<ArraySegment<byte>>? buffers, ref int bufferIndex, ref int offset, ref int count, SocketFlags flags, byte[]? socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
         {
             bool successfulSend = false;
             long start = socket.IsUnderlyingBlocking && socket.SendTimeout > 0 ? Environment.TickCount64 : 0; // Get ticks only if timeout is set and socket is blocking.
@@ -1098,7 +1098,7 @@ namespace System.Net.Sockets
             return completed ? errorCode : SocketError.WouldBlock;
         }
 
-        public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength)
+        public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue, out int optionLength)
         {
             // Three codes are called out in the Winsock IOCTLs documentation as "The following Unix IOCTL codes (commands) are supported." They are
             // also the three codes available for use with ioctlsocket on Windows. Developers should be discouraged from using Socket.IOControl in
@@ -1358,7 +1358,7 @@ namespace System.Net.Sockets
             return GetSocketErrorForErrorCode(err);
         }
 
-        public static unsafe SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption optionValue)
+        public static unsafe SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption? optionValue)
         {
             Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership, $"Unexpected optionName={optionName}");
 
@@ -1383,7 +1383,7 @@ namespace System.Net.Sockets
             return SocketError.Success;
         }
 
-        public static unsafe SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
+        public static unsafe SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption? optionValue)
         {
             Debug.Assert(optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership, $"Unexpected optionName={optionName}");
 
@@ -1403,7 +1403,7 @@ namespace System.Net.Sockets
             return SocketError.Success;
         }
 
-        public static unsafe SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption optionValue)
+        public static unsafe SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption? optionValue)
         {
             Interop.Sys.LingerOption opt = default;
             Interop.Error err = Interop.Sys.GetLingerOption(handle, &opt);
@@ -1447,7 +1447,7 @@ namespace System.Net.Sockets
             return SocketError.Success;
         }
 
-        public static unsafe SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)
+        public static unsafe SocketError Select(IList? checkRead, IList? checkWrite, IList? checkError, int microseconds)
         {
             int checkReadInitialCount = checkRead != null ? checkRead.Count : 0;
             int checkWriteInitialCount = checkWrite != null ? checkWrite.Count : 0;
@@ -1486,9 +1486,9 @@ namespace System.Net.Sockets
         }
 
         private static unsafe SocketError SelectViaPoll(
-            IList checkRead, int checkReadInitialCount,
-            IList checkWrite, int checkWriteInitialCount,
-            IList checkError, int checkErrorInitialCount,
+            IList? checkRead, int checkReadInitialCount,
+            IList? checkWrite, int checkWriteInitialCount,
+            IList? checkError, int checkErrorInitialCount,
             Interop.Sys.PollEvent* events, int eventsLength,
             int microseconds)
         {
@@ -1546,7 +1546,7 @@ namespace System.Net.Sockets
             }
         }
 
-        private static unsafe void AddToPollArray(Interop.Sys.PollEvent* arr, int arrLength, IList socketList, ref int arrOffset, Interop.Sys.PollEvents events, ref int refsAdded)
+        private static unsafe void AddToPollArray(Interop.Sys.PollEvent* arr, int arrLength, IList? socketList, ref int arrOffset, Interop.Sys.PollEvents events, ref int refsAdded)
         {
             if (socketList == null)
                 return;
@@ -1560,7 +1560,7 @@ namespace System.Net.Sockets
                     throw new ArgumentOutOfRangeException(nameof(socketList));
                 }
 
-                Socket socket = socketList[i] as Socket;
+                Socket? socket = socketList[i] as Socket;
                 if (socket == null)
                 {
                     throw new ArgumentException(SR.Format(SR.net_sockets_select, socket?.GetType().FullName ?? "null", typeof(Socket).FullName), nameof(socketList));
@@ -1574,7 +1574,7 @@ namespace System.Net.Sockets
             }
         }
 
-        private static unsafe void FilterPollList(IList socketList, Interop.Sys.PollEvent* arr, int arrEndOffset, Interop.Sys.PollEvents desiredEvents, ref int refsAdded)
+        private static unsafe void FilterPollList(IList? socketList, Interop.Sys.PollEvent* arr, int arrEndOffset, Interop.Sys.PollEvents desiredEvents, ref int refsAdded)
         {
             if (socketList == null)
                 return;
@@ -1600,7 +1600,7 @@ namespace System.Net.Sockets
 
                 if ((arr[arrEndOffset].TriggeredEvents & desiredEvents) == 0)
                 {
-                    Socket socket = (Socket)socketList[i];
+                    Socket socket = (Socket)socketList[i]!;
                     socket.InternalSafeHandle.DangerousRelease();
                     refsAdded--;
                     socketList.RemoveAt(i);
@@ -1694,7 +1694,7 @@ namespace System.Net.Sockets
                         }
                         else
                         {
-                            FileStream fs = files[i] ?? e.FileStream;
+                            FileStream fs = files[i] ?? e.FileStream!;
                             if (e.Count > fs.Length - e.OffsetLong)
                             {
                                 throw new ArgumentOutOfRangeException();
@@ -1723,8 +1723,8 @@ namespace System.Net.Sockets
                 if ((options & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0)
                 {
                     await Task.Factory.FromAsync(
-                        (reuse, c, s) => ((Socket)s).BeginDisconnect(reuse, c, s),
-                        iar => ((Socket)iar.AsyncState).EndDisconnect(iar),
+                        (reuse, c, s) => ((Socket)s!).BeginDisconnect(reuse, c, s),
+                        iar => ((Socket)iar.AsyncState!).EndDisconnect(iar),
                         (options & TransmitFileOptions.ReuseSocket) != 0,
                         socket).ConfigureAwait(false);
                 }
@@ -1820,7 +1820,7 @@ namespace System.Net.Sockets
             return socketError;
         }
 
-        public static SocketError AcceptAsync(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult)
+        public static SocketError AcceptAsync(Socket socket, SafeSocketHandle handle, SafeSocketHandle? acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult)
         {
             Debug.Assert(acceptHandle == null, $"Unexpected acceptHandle: {acceptHandle}");
             Debug.Assert(receiveSize == 0, $"Unexpected receiveSize: {receiveSize}");
index 8118e47..8eab7ef 100644 (file)
@@ -202,8 +202,8 @@ namespace System.Net.Sockets
             int count = buffers.Count;
             bool useStack = count <= StackThreshold;
 
-            WSABuffer[] leasedWSA = null;
-            GCHandle[] leasedGC = null;
+            WSABuffer[]? leasedWSA = null;
+            GCHandle[]? leasedGC = null;
             Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
             Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
             if (useStack)
@@ -227,7 +227,7 @@ namespace System.Net.Sockets
                     RangeValidationHelpers.ValidateSegment(buffer);
                     objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
                     WSABuffers[i].Length = buffer.Count;
-                    WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
+                    WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array!, buffer.Offset);
                 }
 
                 unsafe
@@ -260,8 +260,8 @@ namespace System.Net.Sockets
                 }
                 if (!useStack)
                 {
-                    ArrayPool<WSABuffer>.Shared.Return(leasedWSA);
-                    ArrayPool<GCHandle>.Shared.Return(leasedGC);
+                    ArrayPool<WSABuffer>.Shared.Return(leasedWSA!);
+                    ArrayPool<GCHandle>.Shared.Return(leasedGC!);
                 }
             }
         }
@@ -287,7 +287,7 @@ namespace System.Net.Sockets
             return SocketError.Success;
         }
 
-        public static unsafe SocketError SendFile(SafeSocketHandle handle, SafeFileHandle fileHandle, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
+        public static unsafe SocketError SendFile(SafeSocketHandle handle, SafeFileHandle? fileHandle, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags)
         {
             fixed (byte* prePinnedBuffer = preBuffer)
             fixed (byte* postPinnedBuffer = postBuffer)
@@ -340,8 +340,8 @@ namespace System.Net.Sockets
             int count = buffers.Count;
             bool useStack = count <= StackThreshold;
 
-            WSABuffer[] leasedWSA = null;
-            GCHandle[] leasedGC = null;
+            WSABuffer[]? leasedWSA = null;
+            GCHandle[]? leasedGC = null;
             Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
             Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
             if (useStack)
@@ -365,7 +365,7 @@ namespace System.Net.Sockets
                     RangeValidationHelpers.ValidateSegment(buffer);
                     objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
                     WSABuffers[i].Length = buffer.Count;
-                    WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
+                    WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array!, buffer.Offset);
                 }
 
                 unsafe
@@ -398,8 +398,8 @@ namespace System.Net.Sockets
                 }
                 if (!useStack)
                 {
-                    ArrayPool<WSABuffer>.Shared.Return(leasedWSA);
-                    ArrayPool<GCHandle>.Shared.Return(leasedGC);
+                    ArrayPool<WSABuffer>.Shared.Return(leasedWSA!);
+                    ArrayPool<GCHandle>.Shared.Return(leasedGC!);
                 }
             }
         }
@@ -546,7 +546,7 @@ namespace System.Net.Sockets
             return SocketError.Success;
         }
 
-        public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength)
+        public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue, out int optionLength)
         {
             if (ioControlCode == Interop.Winsock.IoctlSocketConstants.FIONBIO)
             {
@@ -734,7 +734,7 @@ namespace System.Net.Sockets
             return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
         }
 
-        public static SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption optionValue)
+        public static SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption? optionValue)
         {
             Interop.Winsock.IPMulticastRequest ipmr = default;
             int optlen = Interop.Winsock.IPMulticastRequest.Size;
@@ -771,7 +771,7 @@ namespace System.Net.Sockets
             return SocketError.Success;
         }
 
-        public static SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
+        public static SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption? optionValue)
         {
             Interop.Winsock.IPv6MulticastRequest ipmr = default;
 
@@ -795,7 +795,7 @@ namespace System.Net.Sockets
             return SocketError.Success;
         }
 
-        public static SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption optionValue)
+        public static SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption? optionValue)
         {
             Interop.Winsock.Linger lngopt = default;
             int optlen = 4;
@@ -871,10 +871,10 @@ namespace System.Net.Sockets
             }
         }
 
-        public static unsafe SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)
+        public static unsafe SocketError Select(IList? checkRead, IList? checkWrite, IList? checkError, int microseconds)
         {
             const int StackThreshold = 64; // arbitrary limit to avoid too much space on stack
-            bool ShouldStackAlloc(IList list, ref IntPtr[] lease, out Span<IntPtr> span)
+            bool ShouldStackAlloc(IList? list, ref IntPtr[]? lease, out Span<IntPtr> span)
             {
                 int count;
                 if (list == null || (count = list.Count) == 0)
@@ -891,7 +891,7 @@ namespace System.Net.Sockets
                 return true;
             }
 
-            IntPtr[] leaseRead = null, leaseWrite = null, leaseError = null;
+            IntPtr[]? leaseRead = null, leaseWrite = null, leaseError = null;
             int refsAdded = 0;
             try
             {
@@ -1049,7 +1049,7 @@ namespace System.Net.Sockets
                 SocketError errorCode = Interop.Winsock.WSASend(
                     handle,
                     asyncResult._wsaBuffers,
-                    asyncResult._wsaBuffers.Length,
+                    asyncResult._wsaBuffers!.Length,
                     out bytesTransferred,
                     socketFlags,
                     asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
@@ -1068,10 +1068,10 @@ namespace System.Net.Sockets
 
         private static unsafe bool TransmitFileHelper(
             SafeHandle socket,
-            SafeHandle fileHandle,
+            SafeHandle? fileHandle,
             NativeOverlapped* overlapped,
-            byte[] preBuffer,
-            byte[] postBuffer,
+            byte[]? preBuffer,
+            byte[]? postBuffer,
             TransmitFileOptions flags)
         {
             bool needTransmitFileBuffers = false;
@@ -1097,7 +1097,7 @@ namespace System.Net.Sockets
             return success;
         }
 
-        public static unsafe SocketError SendFileAsync(SafeSocketHandle handle, FileStream fileStream, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult)
+        public static unsafe SocketError SendFileAsync(SafeSocketHandle handle, FileStream? fileStream, byte[]? preBuffer, byte[]? postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult)
         {
             asyncResult.SetUnmanagedStructures(fileStream, preBuffer, postBuffer, (flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0);
             try
@@ -1133,7 +1133,7 @@ namespace System.Net.Sockets
                     out bytesTransferred,
                     socketFlags,
                     asyncResult.GetSocketAddressPtr(),
-                    asyncResult.SocketAddress.Size,
+                    asyncResult.SocketAddress!.Size,
                     asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
                     IntPtr.Zero);
 
@@ -1181,7 +1181,7 @@ namespace System.Net.Sockets
                 SocketError errorCode = Interop.Winsock.WSARecv(
                     handle,
                     asyncResult._wsaBuffers,
-                    asyncResult._wsaBuffers.Length,
+                    asyncResult._wsaBuffers!.Length,
                     out bytesTransferred,
                     ref socketFlags,
                     asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
@@ -1231,7 +1231,7 @@ namespace System.Net.Sockets
                 int bytesTransfered;
                 SocketError errorCode = (SocketError)socket.WSARecvMsg(
                     handle,
-                    Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
+                    Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer!, 0),
                     out bytesTransfered,
                     asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
                     IntPtr.Zero);
@@ -1262,7 +1262,7 @@ namespace System.Net.Sockets
                 bool success = socket.AcceptEx(
                     handle,
                     acceptHandle,
-                    Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.Buffer, 0),
+                    Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.Buffer!, 0),
                     receiveSize,
                     addressBufferSize,
                     addressBufferSize,
index 719f7e8..82150ef 100644 (file)
@@ -11,8 +11,8 @@ namespace System.Net.Sockets
     public static class SocketTaskExtensions
     {
         public static Task<Socket> AcceptAsync(this Socket socket) =>
-            socket.AcceptAsync((Socket)null);
-        public static Task<Socket> AcceptAsync(this Socket socket, Socket acceptSocket) =>
+            socket.AcceptAsync((Socket?)null);
+        public static Task<Socket> AcceptAsync(this Socket socket, Socket? acceptSocket) =>
             socket.AcceptAsync(acceptSocket);
 
         public static Task ConnectAsync(this Socket socket, EndPoint remoteEP) =>
index 34d5405..ead0a6e 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Runtime.ExceptionServices;
 using System.Threading;
 using System.Threading.Tasks;
@@ -15,8 +16,8 @@ namespace System.Net.Sockets
     public class TcpClient : IDisposable
     {
         private AddressFamily _family;
-        private Socket _clientSocket;
-        private NetworkStream _dataStream;
+        private Socket _clientSocket = null!; // initialized by helper called from ctor
+        private NetworkStream? _dataStream;
         private volatile int _disposed;
         private bool _active;
 
@@ -114,7 +115,7 @@ namespace System.Net.Sockets
         // Used by the class to provide the underlying network socket.
         public Socket Client
         {
-            get { return Disposed ? null : _clientSocket; }
+            get { return Disposed ? null! : _clientSocket; }
             set
             {
                 _clientSocket = value;
@@ -166,7 +167,7 @@ namespace System.Net.Sockets
             //       DNS when trying to connect. Use of AddressList[0] is
             //       bad form.
             IPAddress[] addresses = Dns.GetHostAddresses(hostname);
-            ExceptionDispatchInfo lastex = null;
+            ExceptionDispatchInfo? lastex = null;
 
             try
             {
@@ -183,7 +184,7 @@ namespace System.Net.Sockets
                             {
                                 var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                                 // Use of Interlocked.Exchanged ensures _clientSocket is written before Disposed is read.
-                                Interlocked.Exchange(ref _clientSocket, socket);
+                                Interlocked.Exchange(ref _clientSocket!, socket);
                                 if (Disposed)
                                 {
                                     // Dispose the socket so it throws ObjectDisposedException when we Connect.
@@ -196,7 +197,7 @@ namespace System.Net.Sockets
                                 }
                                 catch
                                 {
-                                    _clientSocket = null;
+                                    _clientSocket = null!;
                                     throw;
                                 }
                             }
@@ -286,23 +287,23 @@ namespace System.Net.Sockets
 
         public Task ConnectAsync(IPAddress address, int port) =>
             Task.Factory.FromAsync(
-                (targetAddess, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddess, targetPort, callback, state),
-                asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
+                (targetAddess, targetPort, callback, state) => ((TcpClient)state!).BeginConnect(targetAddess, targetPort, callback, state),
+                asyncResult => ((TcpClient)asyncResult.AsyncState!).EndConnect(asyncResult),
                 address, port, state: this);
 
         public Task ConnectAsync(string host, int port) =>
             Task.Factory.FromAsync(
-                (targetHost, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetHost, targetPort, callback, state),
-                asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
+                (targetHost, targetPort, callback, state) => ((TcpClient)state!).BeginConnect(targetHost, targetPort, callback, state),
+                asyncResult => ((TcpClient)asyncResult.AsyncState!).EndConnect(asyncResult),
                 host, port, state: this);
 
         public Task ConnectAsync(IPAddress[] addresses, int port) =>
             Task.Factory.FromAsync(
-                (targetAddresses, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddresses, targetPort, callback, state),
-                asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
+                (targetAddresses, targetPort, callback, state) => ((TcpClient)state!).BeginConnect(targetAddresses, targetPort, callback, state),
+                asyncResult => ((TcpClient)asyncResult.AsyncState!).EndConnect(asyncResult),
                 addresses, port, state: this);
 
-        public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
+        public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback? requestCallback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, address);
 
@@ -312,7 +313,7 @@ namespace System.Net.Sockets
             return result;
         }
 
-        public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
+        public IAsyncResult BeginConnect(string host, int port, AsyncCallback? requestCallback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, (string)host);
 
@@ -322,7 +323,7 @@ namespace System.Net.Sockets
             return result;
         }
 
-        public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
+        public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback? requestCallback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, addresses);
 
@@ -374,7 +375,7 @@ namespace System.Net.Sockets
             {
                 if (disposing)
                 {
-                    IDisposable dataStream = _dataStream;
+                    IDisposable? dataStream = _dataStream;
                     if (dataStream != null)
                     {
                         dataStream.Dispose();
@@ -424,36 +425,37 @@ namespace System.Net.Sockets
         // Gets or sets the size of the receive buffer in bytes.
         public int ReceiveBufferSize
         {
-            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); }
+            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer)!; }
             set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); }
         }
 
         // Gets or sets the size of the send buffer in bytes.
         public int SendBufferSize
         {
-            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer); }
+            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer)!; }
             set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value); }
         }
 
         // Gets or sets the receive time out value of the connection in milliseconds.
         public int ReceiveTimeout
         {
-            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); }
+            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout)!; }
             set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); }
         }
 
         // Gets or sets the send time out value of the connection in milliseconds.
         public int SendTimeout
         {
-            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); }
+            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout)!; }
             set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value); }
         }
 
         // Gets or sets the value of the connection's linger option.
-        public LingerOption LingerState
+        [DisallowNull]
+        public LingerOption? LingerState
         {
             get { return Client.LingerState; }
-            set { Client.LingerState = value; }
+            set { Client.LingerState = value!; }
         }
 
         // Enables or disables delay when send or receive buffers are full.
index 3220214..9dae2af 100644 (file)
@@ -12,7 +12,7 @@ namespace System.Net.Sockets
     public class TcpListener
     {
         private readonly IPEndPoint _serverSocketEP;
-        private Socket _serverSocket;
+        private Socket? _serverSocket;
         private bool _active;
         private bool _exclusiveAddressUse;
         private bool? _allowNatTraversal;
@@ -68,7 +68,7 @@ namespace System.Net.Sockets
             get
             {
                 CreateNewSocketIfNeeded();
-                return _serverSocket;
+                return _serverSocket!;
             }
         }
 
@@ -87,7 +87,7 @@ namespace System.Net.Sockets
         {
             get
             {
-                return _active ? _serverSocket.LocalEndPoint : _serverSocketEP;
+                return _active ? _serverSocket!.LocalEndPoint! : _serverSocketEP;
             }
         }
 
@@ -153,7 +153,7 @@ namespace System.Net.Sockets
 
             CreateNewSocketIfNeeded();
 
-            _serverSocket.Bind(_serverSocketEP);
+            _serverSocket!.Bind(_serverSocketEP);
             try
             {
                 _serverSocket.Listen(backlog);
@@ -189,7 +189,7 @@ namespace System.Net.Sockets
                 throw new InvalidOperationException(SR.net_stopped);
             }
 
-            return _serverSocket.Poll(0, SelectMode.SelectRead);
+            return _serverSocket!.Poll(0, SelectMode.SelectRead);
         }
 
         // Accept the first pending connection
@@ -202,7 +202,7 @@ namespace System.Net.Sockets
                 throw new InvalidOperationException(SR.net_stopped);
             }
 
-            Socket socket = _serverSocket.Accept();
+            Socket socket = _serverSocket!.Accept();
 
             if (NetEventSource.IsEnabled) NetEventSource.Exit(this, socket);
             return socket;
@@ -217,14 +217,14 @@ namespace System.Net.Sockets
                 throw new InvalidOperationException(SR.net_stopped);
             }
 
-            Socket acceptedSocket = _serverSocket.Accept();
+            Socket acceptedSocket = _serverSocket!.Accept();
             TcpClient returnValue = new TcpClient(acceptedSocket);
 
             if (NetEventSource.IsEnabled) NetEventSource.Exit(this, returnValue);
             return returnValue;
         }
 
-        public IAsyncResult BeginAcceptSocket(AsyncCallback callback, object state)
+        public IAsyncResult BeginAcceptSocket(AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
 
@@ -233,7 +233,7 @@ namespace System.Net.Sockets
                 throw new InvalidOperationException(SR.net_stopped);
             }
 
-            IAsyncResult result = _serverSocket.BeginAccept(callback, state);
+            IAsyncResult result = _serverSocket!.BeginAccept(callback, state);
 
             if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
             return result;
@@ -248,8 +248,8 @@ namespace System.Net.Sockets
                 throw new ArgumentNullException(nameof(asyncResult));
             }
 
-            LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
-            Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
+            LazyAsyncResult? lazyResult = asyncResult as LazyAsyncResult;
+            Socket? asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
             if (asyncSocket == null)
             {
                 throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
@@ -262,7 +262,7 @@ namespace System.Net.Sockets
             return socket;
         }
 
-        public IAsyncResult BeginAcceptTcpClient(AsyncCallback callback, object state)
+        public IAsyncResult BeginAcceptTcpClient(AsyncCallback? callback, object? state)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
 
@@ -271,7 +271,7 @@ namespace System.Net.Sockets
                 throw new InvalidOperationException(SR.net_stopped);
             }
 
-            IAsyncResult result = _serverSocket.BeginAccept(callback, state);
+            IAsyncResult result = _serverSocket!.BeginAccept(callback, state);
             if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result);
             return result;
         }
@@ -285,8 +285,8 @@ namespace System.Net.Sockets
                 throw new ArgumentNullException(nameof(asyncResult));
             }
 
-            LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
-            Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
+            LazyAsyncResult? lazyResult = asyncResult as LazyAsyncResult;
+            Socket? asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
             if (asyncSocket == null)
             {
                 throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
@@ -301,16 +301,16 @@ namespace System.Net.Sockets
         public Task<Socket> AcceptSocketAsync()
         {
             return Task<Socket>.Factory.FromAsync(
-                (callback, state) => ((TcpListener)state).BeginAcceptSocket(callback, state),
-                asyncResult => ((TcpListener)asyncResult.AsyncState).EndAcceptSocket(asyncResult),
+                (callback, state) => ((TcpListener)state!).BeginAcceptSocket(callback, state),
+                asyncResult => ((TcpListener)asyncResult.AsyncState!).EndAcceptSocket(asyncResult),
                 state: this);
         }
 
         public Task<TcpClient> AcceptTcpClientAsync()
         {
             return Task<TcpClient>.Factory.FromAsync(
-                (callback, state) => ((TcpListener)state).BeginAcceptTcpClient(callback, state),
-                asyncResult => ((TcpListener)asyncResult.AsyncState).EndAcceptTcpClient(asyncResult),
+                (callback, state) => ((TcpListener)state!).BeginAcceptTcpClient(callback, state),
+                asyncResult => ((TcpListener)asyncResult.AsyncState!).EndAcceptTcpClient(asyncResult),
                 state: this);
         }
 
@@ -344,7 +344,7 @@ namespace System.Net.Sockets
         }
 
         private void SetIPProtectionLevel(bool allowed)
-            => _serverSocket.SetIPProtectionLevel(allowed ? IPProtectionLevel.Unrestricted : IPProtectionLevel.EdgeRestricted);
+            => _serverSocket!.SetIPProtectionLevel(allowed ? IPProtectionLevel.Unrestricted : IPProtectionLevel.EdgeRestricted);
 
         private void CreateNewSocketIfNeeded()
         {
index f5c9c2d..3d2c35a 100644 (file)
@@ -8,15 +8,15 @@ namespace System.Net.Sockets
 {
     internal sealed class TransmitFileAsyncResult : BaseOverlappedAsyncResult
     {
-        private FileStream _fileStream;
+        private FileStream? _fileStream;
         private bool _doDisconnect;
 
-        internal TransmitFileAsyncResult(Socket socket, object asyncState, AsyncCallback asyncCallback) :
+        internal TransmitFileAsyncResult(Socket socket, object? asyncState, AsyncCallback? asyncCallback) :
             base(socket, asyncState, asyncCallback)
         {
         }
 
-        internal void SetUnmanagedStructures(FileStream fileStream, byte[] preBuffer, byte[] postBuffer, bool doDisconnect)
+        internal void SetUnmanagedStructures(FileStream? fileStream, byte[]? preBuffer, byte[]? postBuffer, bool doDisconnect)
         {
             _fileStream = fileStream;
             _doDisconnect = doDisconnect;
@@ -29,7 +29,7 @@ namespace System.Net.Sockets
             if (postBuffer != null && postBuffer.Length > 0)
                 ++buffsNumber;
 
-            object[] objectsToPin = null;
+            object[]? objectsToPin = null;
             if (buffsNumber != 0)
             {
                 objectsToPin = new object[buffsNumber];
index c3e6a09..c7d280f 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.Threading.Tasks;
 
 namespace System.Net.Sockets
@@ -13,7 +14,7 @@ namespace System.Net.Sockets
     {
         private const int MaxUDPSize = 0x10000;
 
-        private Socket _clientSocket;
+        private Socket _clientSocket = null!; // initialized by helper called from ctor
         private bool _active;
         private readonly byte[] _buffer = new byte[MaxUDPSize];
         private AddressFamily _family = AddressFamily.InterNetwork;
@@ -243,7 +244,7 @@ namespace System.Net.Sockets
                     // of the Bind() call and free the bound IPEndPoint.
                     chkClientSocket.InternalShutdown(SocketShutdown.Both);
                     chkClientSocket.Dispose();
-                    _clientSocket = null;
+                    _clientSocket = null!;
                 }
 
                 _disposed = true;
@@ -281,7 +282,7 @@ namespace System.Net.Sockets
             }
         }
 
-        public IAsyncResult BeginSend(byte[] datagram, int bytes, IPEndPoint endPoint, AsyncCallback requestCallback, object state)
+        public IAsyncResult BeginSend(byte[] datagram, int bytes, IPEndPoint? endPoint, AsyncCallback? requestCallback, object? state)
         {
             ThrowIfDisposed();
 
@@ -312,7 +313,7 @@ namespace System.Net.Sockets
             return _clientSocket.BeginSendTo(datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state);
         }
 
-        public IAsyncResult BeginSend(byte[] datagram, int bytes, string hostname, int port, AsyncCallback requestCallback, object state)
+        public IAsyncResult BeginSend(byte[] datagram, int bytes, string? hostname, int port, AsyncCallback? requestCallback, object? state)
         {
             if (_active && ((hostname != null) || (port != 0)))
             {
@@ -320,7 +321,7 @@ namespace System.Net.Sockets
                 throw new InvalidOperationException(SR.net_udpconnected);
             }
 
-            IPEndPoint ipEndPoint = null;
+            IPEndPoint? ipEndPoint = null;
             if (hostname != null && port != 0)
             {
                 IPAddress[] addresses = Dns.GetHostAddresses(hostname);
@@ -342,7 +343,7 @@ namespace System.Net.Sockets
             return BeginSend(datagram, bytes, ipEndPoint, requestCallback, state);
         }
 
-        public IAsyncResult BeginSend(byte[] datagram, int bytes, AsyncCallback requestCallback, object state)
+        public IAsyncResult BeginSend(byte[] datagram, int bytes, AsyncCallback? requestCallback, object? state)
         {
             return BeginSend(datagram, bytes, null, requestCallback, state);
         }
@@ -361,7 +362,7 @@ namespace System.Net.Sockets
             }
         }
 
-        public IAsyncResult BeginReceive(AsyncCallback requestCallback, object state)
+        public IAsyncResult BeginReceive(AsyncCallback? requestCallback, object? state)
         {
             // Validate input parameters.
             ThrowIfDisposed();
@@ -382,7 +383,7 @@ namespace System.Net.Sockets
             return _clientSocket.BeginReceiveFrom(_buffer, 0, MaxUDPSize, SocketFlags.None, ref tempRemoteEP, requestCallback, state);
         }
 
-        public byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint remoteEP)
+        public byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint? remoteEP)
         {
             ThrowIfDisposed();
 
@@ -597,38 +598,38 @@ namespace System.Net.Sockets
         public Task<int> SendAsync(byte[] datagram, int bytes)
         {
             return Task<int>.Factory.FromAsync(
-                (targetDatagram, targetBytes, callback, state) => ((UdpClient)state).BeginSend(targetDatagram, targetBytes, callback, state),
-                asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult),
+                (targetDatagram, targetBytes, callback, state) => ((UdpClient)state!).BeginSend(targetDatagram, targetBytes, callback, state),
+                asyncResult => ((UdpClient)asyncResult.AsyncState!).EndSend(asyncResult),
                 datagram,
                 bytes,
                 state: this);
         }
 
-        public Task<int> SendAsync(byte[] datagram, int bytes, IPEndPoint endPoint)
+        public Task<int> SendAsync(byte[] datagram, int bytes, IPEndPoint? endPoint)
         {
             return Task<int>.Factory.FromAsync(
-                (targetDatagram, targetBytes, targetEndpoint, callback, state) => ((UdpClient)state).BeginSend(targetDatagram, targetBytes, targetEndpoint, callback, state),
-                asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult),
+                (targetDatagram, targetBytes, targetEndpoint, callback, state) => ((UdpClient)state!).BeginSend(targetDatagram, targetBytes, targetEndpoint, callback, state),
+                asyncResult => ((UdpClient)asyncResult.AsyncState!).EndSend(asyncResult),
                 datagram,
                 bytes,
                 endPoint,
                 state: this);
         }
 
-        public Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port)
+        public Task<int> SendAsync(byte[] datagram, int bytes, string? hostname, int port)
         {
-            Tuple<byte[], string> packedArguments = Tuple.Create(datagram, hostname);
+            Tuple<byte[], string?> packedArguments = Tuple.Create(datagram, hostname);
 
             return Task<int>.Factory.FromAsync(
                 (targetPackedArguments, targetBytes, targetPort, callback, state) =>
                 {
                     byte[] targetDatagram = targetPackedArguments.Item1;
-                    string targetHostname = targetPackedArguments.Item2;
-                    var client = (UdpClient)state;
+                    string? targetHostname = targetPackedArguments.Item2;
+                    var client = (UdpClient)state!;
 
                     return client.BeginSend(targetDatagram, targetBytes, targetHostname, targetPort, callback, state);
                 },
-                asyncResult => ((UdpClient)asyncResult.AsyncState).EndSend(asyncResult),
+                asyncResult => ((UdpClient)asyncResult.AsyncState!).EndSend(asyncResult),
                 packedArguments,
                 bytes,
                 port,
@@ -638,13 +639,13 @@ namespace System.Net.Sockets
         public Task<UdpReceiveResult> ReceiveAsync()
         {
             return Task<UdpReceiveResult>.Factory.FromAsync(
-                (callback, state) => ((UdpClient)state).BeginReceive(callback, state),
+                (callback, state) => ((UdpClient)state!).BeginReceive(callback, state),
                 asyncResult =>
                 {
-                    var client = (UdpClient)asyncResult.AsyncState;
-                    IPEndPoint remoteEP = null;
+                    var client = (UdpClient)asyncResult.AsyncState!;
+                    IPEndPoint? remoteEP = null;
                     byte[] buffer = client.EndReceive(asyncResult, ref remoteEP);
-                    return new UdpReceiveResult(buffer, remoteEP);
+                    return new UdpReceiveResult(buffer, remoteEP!);
                 },
                 state: this);
         }
@@ -699,9 +700,9 @@ namespace System.Net.Sockets
 
             IPAddress[] addresses = Dns.GetHostAddresses(hostname);
 
-            Exception lastex = null;
-            Socket ipv6Socket = null;
-            Socket ipv4Socket = null;
+            Exception? lastex = null;
+            Socket? ipv6Socket = null;
+            Socket? ipv4Socket = null;
 
             try
             {
@@ -841,7 +842,7 @@ namespace System.Net.Sockets
             _active = true;
         }
 
-        public byte[] Receive(ref IPEndPoint remoteEP)
+        public byte[] Receive([NotNull] ref IPEndPoint? remoteEP)
         {
             ThrowIfDisposed();
 
@@ -878,7 +879,7 @@ namespace System.Net.Sockets
 
 
         // Sends a UDP datagram to the host at the remote end point.
-        public int Send(byte[] dgram, int bytes, IPEndPoint endPoint)
+        public int Send(byte[] dgram, int bytes, IPEndPoint? endPoint)
         {
             ThrowIfDisposed();
 
@@ -904,7 +905,7 @@ namespace System.Net.Sockets
 
 
         // Sends a UDP datagram to the specified port on the specified remote host.
-        public int Send(byte[] dgram, int bytes, string hostname, int port)
+        public int Send(byte[] dgram, int bytes, string? hostname, int port)
         {
             ThrowIfDisposed();
 
index 02da108..9c0ef7b 100644 (file)
@@ -69,7 +69,7 @@ namespace System.Net.Sockets
         /// </summary>
         /// <param name="obj">The object to compare with this instance</param>
         /// <returns>true if obj is an instance of <see cref="UdpReceiveResult"/> and equals the value of the instance; otherwise, false</returns>
-        public override bool Equals(object obj) =>
+        public override bool Equals(object? obj) =>
             obj is UdpReceiveResult other && Equals(other);
 
         /// <summary>
index 09a88f2..607a347 100644 (file)
@@ -32,6 +32,7 @@ namespace System.Net.Sockets.Tests
             using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
             {
                 AssertExtensions.Throws<ArgumentNullException>("asyncResult", () => s.EndDisconnect(null));
+                AssertExtensions.Throws<ArgumentNullException>("e", () => s.DisconnectAsync(null));
                 AssertExtensions.Throws<ArgumentException>("asyncResult", () => s.EndDisconnect(Task.CompletedTask));
                 s.Dispose();
                 Assert.Throws<ObjectDisposedException>(() => s.Disconnect(true));