Annotate System.Runtime.WindowsRuntime for nullable reference types (#33692)
authorStephen Toub <stoub@microsoft.com>
Fri, 20 Mar 2020 13:58:40 +0000 (09:58 -0400)
committerGitHub <noreply@github.com>
Fri, 20 Mar 2020 13:58:40 +0000 (09:58 -0400)
31 files changed:
src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ExceptionSupport.cs
src/libraries/System.Private.CoreLib/src/Internal/Resources/WindowsRuntimeResourceManagerBase.cs
src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.Manual.cs
src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.cs
src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.csproj
src/libraries/System.Runtime.WindowsRuntime/src/System.Runtime.WindowsRuntime.csproj
src/libraries/System.Runtime.WindowsRuntime/src/System/IO/NetFxToWinRtStreamAdapter.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/IO/StreamOperationAsyncResult.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/IO/StreamOperationsImplementation.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WinRtToNetFxStreamAdapter.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WindowsRuntimeStorageExtensions.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WindowsRuntimeStreamExtensions.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/MarshalingHelpers.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBuffer.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferExtensions.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/AsyncInfoToTaskBridge.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/ExceptionDispatchHelper.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncActionAdapter.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncInfoAdapter.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncOperationAdapter.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncOperationWithProgressAdapter.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/WindowsRuntimeSynchronizationContext.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Point.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Rect.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Size.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/TokenizerHelper.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/UI/Color.cs
src/libraries/System.Runtime.WindowsRuntime/src/System/WindowsRuntimeSystemExtensions.cs
src/mono/netcore/System.Private.CoreLib/src/Internal/Resources/WindowsRuntimeResourceManagerBase.cs
src/mono/netcore/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ExceptionSupport.cs

index 504f428..c7feb47 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System;
+using System.Diagnostics.CodeAnalysis;
 using System.Runtime.InteropServices.WindowsRuntime;
 
 namespace Internal.Runtime.InteropServices.WindowsRuntime
@@ -13,6 +14,7 @@ namespace Internal.Runtime.InteropServices.WindowsRuntime
         /// Attach restricted error information to the exception if it may apply to that exception, returning
         /// back the input value
         /// </summary>
+        [return: NotNullIfNotNull("e")]
         public static Exception? AttachRestrictedErrorInfo(Exception? e)
         {
             // If there is no exception, then the restricted error info doesn't apply to it
index 173b237..20b73ed 100644 (file)
@@ -12,7 +12,7 @@ namespace Internal.Resources
     {
         public abstract bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo? exceptionInfo);
 
-        public abstract string GetString(string stringName, string? startingCulture, string? neutralResourcesCulture);
+        public abstract string? GetString(string stringName, string? startingCulture, string? neutralResourcesCulture);
 
         public abstract CultureInfo? GlobalResourceContextBestFitCultureInfo
         {
index f0152a3..f7ef82e 100644 (file)
@@ -18,17 +18,17 @@ namespace Windows.Foundation
 {
     public partial struct Point : IFormattable
     {
-        string IFormattable.ToString(string format, IFormatProvider provider) { throw null; }
+        string IFormattable.ToString(string? format, IFormatProvider? provider) { throw null; }
     }
     public partial struct Rect : IFormattable
     {
-        string IFormattable.ToString(string format, IFormatProvider provider) { throw null; }
+        string IFormattable.ToString(string? format, IFormatProvider? provider) { throw null; }
     }
 }
 namespace Windows.UI
 {
     public partial struct Color : IFormattable
     {
-        string IFormattable.ToString(string format, IFormatProvider provider) { throw null; }
+        string IFormattable.ToString(string? format, IFormatProvider? provider) { throw null; }
     }
 }
index 1210eb6..c3e6e2f 100644 (file)
@@ -15,15 +15,15 @@ namespace System
         public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source) { throw null; }
         public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source, System.Threading.CancellationToken cancellationToken) { throw null; }
         public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source) { throw null; }
-        public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, System.IProgress<TProgress> progress) { throw null; }
+        public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, System.IProgress<TProgress>? progress) { throw null; }
         public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, System.Threading.CancellationToken cancellationToken) { throw null; }
-        public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, System.Threading.CancellationToken cancellationToken, System.IProgress<TProgress> progress) { throw null; }
+        public static System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, System.Threading.CancellationToken cancellationToken, System.IProgress<TProgress>? progress) { throw null; }
         public static System.Threading.Tasks.Task<TResult> AsTask<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source) { throw null; }
         public static System.Threading.Tasks.Task<TResult> AsTask<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source, System.Threading.CancellationToken cancellationToken) { throw null; }
         public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source) { throw null; }
-        public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, System.IProgress<TProgress> progress) { throw null; }
+        public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, System.IProgress<TProgress>? progress) { throw null; }
         public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, System.Threading.CancellationToken cancellationToken) { throw null; }
-        public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, System.Threading.CancellationToken cancellationToken, System.IProgress<TProgress> progress) { throw null; }
+        public static System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, System.Threading.CancellationToken cancellationToken, System.IProgress<TProgress>? progress) { throw null; }
         [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
         public static System.Runtime.CompilerServices.TaskAwaiter GetAwaiter(this global::Windows.Foundation.IAsyncAction source) { throw null; }
         [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
@@ -122,7 +122,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         [System.CLSCompliantAttribute(false)]
         public static global::Windows.Storage.Streams.IBuffer GetWindowsRuntimeBuffer(this System.IO.MemoryStream underlyingStream, int positionInStream, int length) { throw null; }
         [System.CLSCompliantAttribute(false)]
-        public static bool IsSameData(this global::Windows.Storage.Streams.IBuffer buffer, global::Windows.Storage.Streams.IBuffer otherBuffer) { throw null; }
+        public static bool IsSameData(this global::Windows.Storage.Streams.IBuffer buffer, global::Windows.Storage.Streams.IBuffer? otherBuffer) { throw null; }
         [System.CLSCompliantAttribute(false)]
         public static byte[] ToArray(this global::Windows.Storage.Streams.IBuffer source) { throw null; }
         [System.CLSCompliantAttribute(false)]
@@ -137,13 +137,13 @@ namespace Windows.Foundation
         public Point(double x, double y) { throw null; }
         public double X { get { throw null; } set { } }
         public double Y { get { throw null; } set { } }
-        public override bool Equals(object o) { throw null; }
+        public override bool Equals(object? o) { throw null; }
         public bool Equals(global::Windows.Foundation.Point value) { throw null; }
         public override int GetHashCode() { throw null; }
         public static bool operator ==(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw null; }
         public static bool operator !=(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw null; }
         public override string ToString() { throw null; }
-        public string ToString(global::System.IFormatProvider provider) { throw null; }
+        public string ToString(global::System.IFormatProvider? provider) { throw null; }
     }
     public partial struct Rect : global::System.IFormattable
     {
@@ -162,14 +162,14 @@ namespace Windows.Foundation
         public double X { get { throw null; } set { } }
         public double Y { get { throw null; } set { } }
         public bool Contains(global::Windows.Foundation.Point point) { throw null; }
-        public override bool Equals(object o) { throw null; }
+        public override bool Equals(object? o) { throw null; }
         public bool Equals(global::Windows.Foundation.Rect value) { throw null; }
         public override int GetHashCode() { throw null; }
         public void Intersect(global::Windows.Foundation.Rect rect) { }
         public static bool operator ==(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { throw null; }
         public static bool operator !=(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { throw null; }
         public override string ToString() { throw null; }
-        public string ToString(global::System.IFormatProvider provider) { throw null; }
+        public string ToString(global::System.IFormatProvider? provider) { throw null; }
         public void Union(global::Windows.Foundation.Point point) { }
         public void Union(global::Windows.Foundation.Rect rect) { }
     }
@@ -181,7 +181,7 @@ namespace Windows.Foundation
         public double Height { get { throw null; } set { } }
         public bool IsEmpty { get { throw null; } }
         public double Width { get { throw null; } set { } }
-        public override bool Equals(object o) { throw null; }
+        public override bool Equals(object? o) { throw null; }
         public bool Equals(global::Windows.Foundation.Size value) { throw null; }
         public override int GetHashCode() { throw null; }
         public static bool operator ==(global::Windows.Foundation.Size size1, global::Windows.Foundation.Size size2) { throw null; }
@@ -198,13 +198,13 @@ namespace Windows.UI
         public byte B { get { throw null; } set { } }
         public byte G { get { throw null; } set { } }
         public byte R { get { throw null; } set { } }
-        public override bool Equals(object o) { throw null; }
+        public override bool Equals(object? o) { throw null; }
         public bool Equals(global::Windows.UI.Color color) { throw null; }
         public static global::Windows.UI.Color FromArgb(byte a, byte r, byte g, byte b) { throw null; }
         public override int GetHashCode() { throw null; }
         public static bool operator ==(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { throw null; }
         public static bool operator !=(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { throw null; }
         public override string ToString() { throw null; }
-        public string ToString(global::System.IFormatProvider provider) { throw null; }
+        public string ToString(global::System.IFormatProvider? provider) { throw null; }
     }
 }
index 08655bb..3885371 100644 (file)
@@ -12,6 +12,7 @@
     <NoWarn>$(NoWarn);1698</NoWarn>
     <TargetFrameworks>$(NetCoreAppCurrent);netstandard2.0</TargetFrameworks>
     <ExcludeCurrentNetCoreAppFromPackage>true</ExcludeCurrentNetCoreAppFromPackage>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="System.Runtime.WindowsRuntime.cs" />
index 60f7f32..b8714d9 100644 (file)
@@ -10,6 +10,7 @@
     <DefineConstants Condition="'$(TargetsNetCoreApp)' == 'true'">$(DefineConstants);FEATURE_APPX</DefineConstants>
     <TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;netstandard1.0;netstandard1.2;netstandard2.0</TargetFrameworks>
     <ExcludeCurrentNetCoreAppFromPackage>true</ExcludeCurrentNetCoreAppFromPackage>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <PropertyGroup Condition="'$(TargetsNetStandard)' == 'true'">
     <GeneratePlatformNotSupportedAssemblyMessage>SR.PlatformNotSupported_WindowsRuntime</GeneratePlatformNotSupportedAssemblyMessage>
index 2b1a2e8..b9402ac 100644 (file)
@@ -10,6 +10,7 @@ using System.Threading.Tasks;
 using System.Threading;
 using Windows.Foundation;
 using Windows.Storage.Streams;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.IO
 {
@@ -128,7 +129,7 @@ namespace System.IO
 
         private static bool CanApplyReadMemoryStreamOptimization(Stream stream)
         {
-            MemoryStream memStream = stream as MemoryStream;
+            MemoryStream? memStream = stream as MemoryStream;
             if (memStream == null)
                 return false;
 
@@ -154,7 +155,7 @@ namespace System.IO
 
         #region Instance variables
 
-        private Stream _managedStream = null;
+        private Stream? _managedStream = null;
         private bool _leaveUnderlyingStreamOpen = true;
         private readonly StreamReadOperationOptimization _readOptimization;
 
@@ -176,7 +177,7 @@ namespace System.IO
         }
 
 
-        public Stream GetManagedStream()
+        public Stream? GetManagedStream()
         {
             return _managedStream;
         }
@@ -184,7 +185,7 @@ namespace System.IO
 
         private Stream EnsureNotDisposed()
         {
-            Stream str = _managedStream;
+            Stream? str = _managedStream;
 
             if (str == null)
             {
@@ -204,7 +205,7 @@ namespace System.IO
         /// <summary>Implements IDisposable.Dispose (IClosable.Close in WinRT)</summary>
         void IDisposable.Dispose()
         {
-            Stream str = _managedStream;
+            Stream? str = _managedStream;
             if (str == null)
                 return;
 
@@ -412,7 +413,7 @@ namespace System.IO
         // for IRandonAccessStream.
         // Cloning can be added in future, however, it would be quite complex
         // to support it correctly for generic streams.
-
+        [DoesNotReturn]
         private static void ThrowCloningNotSupported(string methodName)
         {
             NotSupportedException nse = new NotSupportedException(SR.Format(SR.NotSupported_CloningNotSupported, methodName));
index 8a58356..c94c172 100644 (file)
@@ -11,6 +11,7 @@ using System.Threading.Tasks;
 using System.Threading;
 using Windows.Foundation;
 using Windows.Storage.Streams;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.IO
 {
@@ -18,25 +19,25 @@ namespace System.IO
 
     internal abstract partial class StreamOperationAsyncResult : IAsyncResult
     {
-        private readonly AsyncCallback _userCompletionCallback = null;
-        private readonly object _userAsyncStateInfo = null;
+        private readonly AsyncCallback? _userCompletionCallback = null;
+        private readonly object? _userAsyncStateInfo = null;
 
-        private IAsyncInfo _asyncStreamOperation = null;
+        private IAsyncInfo? _asyncStreamOperation = null;
 
         private volatile bool _completed = false;
         private volatile bool _callbackInvoked = false;
-        private volatile ManualResetEvent _waitHandle = null;
+        private volatile ManualResetEvent? _waitHandle = null;
 
         private long _bytesCompleted = 0;
 
-        private ExceptionDispatchInfo _errorInfo = null;
+        private ExceptionDispatchInfo? _errorInfo = null;
 
         private readonly bool _processCompletedOperationInCallback;
-        private IAsyncInfo _completedOperation = null;
+        private IAsyncInfo? _completedOperation = null;
 
 
         protected internal StreamOperationAsyncResult(IAsyncInfo asyncStreamOperation,
-                                                      AsyncCallback userCompletionCallback, object userAsyncStateInfo,
+                                                      AsyncCallback? userCompletionCallback, object? userAsyncStateInfo,
                                                       bool processCompletedOperationInCallback)
         {
             if (asyncStreamOperation == null)
@@ -58,7 +59,7 @@ namespace System.IO
         }
 
 
-        public object AsyncState
+        public object? AsyncState
         {
             get { return _userAsyncStateInfo; }
         }
@@ -74,7 +75,7 @@ namespace System.IO
         {
             get
             {
-                ManualResetEvent wh = _waitHandle;
+                ManualResetEvent? wh = _waitHandle;
                 if (wh != null)
                     return wh;
 
@@ -82,7 +83,7 @@ namespace System.IO
                 // > Use 'completed' in the ctor - this way the handle wait will return as appropriate.
                 wh = new ManualResetEvent(_completed);
 
-                ManualResetEvent otherHandle = Interlocked.CompareExchange(ref _waitHandle, wh, null);
+                ManualResetEvent? otherHandle = Interlocked.CompareExchange(ref _waitHandle, wh, null);
 
                 // We lost the race. Dispose OUR handle and return OTHER handle:
                 if (otherHandle != null)
@@ -177,10 +178,10 @@ namespace System.IO
 
         internal abstract void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted);
 
-
-        private static void ProcessCompletedOperation_InvalidOperationThrowHelper(ExceptionDispatchInfo errInfo, string errMsg)
+        [DoesNotReturn]
+        private static void ProcessCompletedOperation_InvalidOperationThrowHelper(ExceptionDispatchInfo? errInfo, string errMsg)
         {
-            Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
+            Exception? errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
 
             if (errInfoSrc == null)
                 throw new InvalidOperationException(errMsg);
@@ -209,14 +210,14 @@ namespace System.IO
 
             if (_completedOperation == null)
             {
-                ExceptionDispatchInfo errInfo = _errorInfo;
-                Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
+                ExceptionDispatchInfo? errInfo = _errorInfo;
+                Exception? errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
 
                 // See if errorInfo is set because we observed completedOperation == null previously (being slow is Ok on error path):
                 if (errInfoSrc != null && errInfoSrc is NullReferenceException
                         && SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo.Equals(errInfoSrc.Message))
                 {
-                    errInfo.Throw();
+                    errInfo!.Throw();
                 }
                 else
                 {
@@ -224,7 +225,7 @@ namespace System.IO
                 }
             }
 
-            if (_completedOperation.Id != _asyncStreamOperation.Id)
+            if (_completedOperation.Id != _asyncStreamOperation!.Id)
                 ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_UnexpectedAsyncOperationID);
 
             if (_completedOperation.Status == AsyncStatus.Error)
@@ -285,7 +286,7 @@ namespace System.IO
 
         private void ThrowWithIOExceptionDispatchInfo(Exception e)
         {
-            WinRtIOHelper.NativeExceptionToIOExceptionInfo(ExceptionSupport.AttachRestrictedErrorInfo(_completedOperation.ErrorCode)).Throw();
+            WinRtIOHelper.NativeExceptionToIOExceptionInfo(ExceptionSupport.AttachRestrictedErrorInfo(_completedOperation!.ErrorCode)!).Throw();
         }
     }  // class StreamOperationAsyncResult
 
@@ -296,10 +297,10 @@ namespace System.IO
 
     internal class StreamReadAsyncResult : StreamOperationAsyncResult
     {
-        private readonly IBuffer _userBuffer = null;
+        private readonly IBuffer _userBuffer;
 
         internal StreamReadAsyncResult(IAsyncOperationWithProgress<IBuffer, uint> asyncStreamReadOperation, IBuffer buffer,
-                                       AsyncCallback userCompletionCallback, object userAsyncStateInfo,
+                                       AsyncCallback? userCompletionCallback, object? userAsyncStateInfo,
                                        bool processCompletedOperationInCallback)
 
             : base(asyncStreamReadOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
@@ -323,8 +324,8 @@ namespace System.IO
             IBuffer resultBuffer = completedOperation.GetResults();
             Debug.Assert(resultBuffer != null);
 
-            WinRtIOHelper.EnsureResultsInUserBuffer(_userBuffer, resultBuffer);
-            bytesCompleted = _userBuffer.Length;
+            WinRtIOHelper.EnsureResultsInUserBuffer(_userBuffer!, resultBuffer);
+            bytesCompleted = _userBuffer!.Length;
         }
     }  // class StreamReadAsyncResult
 
@@ -336,7 +337,7 @@ namespace System.IO
     internal class StreamWriteAsyncResult : StreamOperationAsyncResult
     {
         internal StreamWriteAsyncResult(IAsyncOperationWithProgress<uint, uint> asyncStreamWriteOperation,
-                                        AsyncCallback userCompletionCallback, object userAsyncStateInfo,
+                                        AsyncCallback? userCompletionCallback, object? userAsyncStateInfo,
                                         bool processCompletedOperationInCallback)
 
             : base(asyncStreamWriteOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
index 252eb69..9414d9f 100644 (file)
@@ -41,7 +41,7 @@ namespace System.IO
             // The user specified buffer will not have any data put into it:
             buffer.Length = 0;
 
-            MemoryStream memStream = stream as MemoryStream;
+            MemoryStream? memStream = stream as MemoryStream;
             Debug.Assert(memStream != null);
 
             try
@@ -82,7 +82,7 @@ namespace System.IO
             //         Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we would need to create
             //         an array to read into either way.
 
-            IBuffer dataBuffer = buffer as WindowsRuntimeBuffer;
+            IBuffer? dataBuffer = buffer as WindowsRuntimeBuffer;
 
             if (dataBuffer == null)
                 dataBuffer = WindowsRuntimeBuffer.Create((int)Math.Min((uint)int.MaxValue, buffer.Capacity));
@@ -94,7 +94,7 @@ namespace System.IO
                 dataBuffer.Length = 0;
 
                 // Get the buffer backing array:
-                byte[] data;
+                byte[]? data;
                 int offset;
                 bool managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset);
                 Debug.Assert(managedBufferAssert);
@@ -111,7 +111,7 @@ namespace System.IO
                     try
                     {
                         // Read asynchronously:
-                        bytesRead = await stream.ReadAsync(data, offset + bytesCompleted, bytesRequested - bytesCompleted, cancelToken)
+                        bytesRead = await stream.ReadAsync(data!, offset + bytesCompleted, bytesRequested - bytesCompleted, cancelToken)
                                                 .ConfigureAwait(continueOnCapturedContext: false);
 
                         // We will continue here on a different thread when read async completed:
@@ -166,7 +166,7 @@ namespace System.IO
 
             // Choose the optimal writing strategy for the kind of buffer supplied:
             Func<CancellationToken, IProgress<uint>, Task<uint>> writeOperation;
-            byte[] data;
+            byte[]? data;
             int offset;
 
             // If buffer is backed by a managed array:
index d7d5fe8..5da6d2b 100644 (file)
@@ -10,6 +10,7 @@ using System.Threading.Tasks;
 using System.Threading;
 using Windows.Foundation;
 using Windows.Storage.Streams;
+using System.Diagnostics.CodeAnalysis;
 
 namespace System.IO
 {
@@ -93,10 +94,10 @@ namespace System.IO
 
         #region Instance variables
 
-        private byte[] _oneByteBuffer = null;
+        private byte[]? _oneByteBuffer = null;
         private bool _leaveUnderlyingStreamOpen = true;
 
-        private object _winRtStream;
+        private object? _winRtStream;
         private readonly bool _canRead;
         private readonly bool _canWrite;
         private readonly bool _canSeek;
@@ -119,9 +120,9 @@ namespace System.IO
         }
 
 
-        public TWinRtStream GetWindowsRuntimeStream<TWinRtStream>() where TWinRtStream : class
+        public TWinRtStream? GetWindowsRuntimeStream<TWinRtStream>() where TWinRtStream : class
         {
-            object wrtStr = _winRtStream;
+            object? wrtStr = _winRtStream;
 
             if (wrtStr == null)
                 return null;
@@ -138,26 +139,16 @@ namespace System.IO
         {
             get
             {
-                byte[] obb = _oneByteBuffer;
+                byte[]? obb = _oneByteBuffer;
                 if (obb == null)  // benign race for multiple init
                     _oneByteBuffer = obb = new byte[1];
                 return obb;
             }
         }
 
-
-#if DEBUG
-        private static void AssertValidStream(object winRtStream)
-        {
-            Debug.Assert(winRtStream != null,
-                            "This to-NetFx Stream adapter must not be disposed and the underlying WinRT stream must be of compatible type for this operation");
-        }
-#endif  // DEBUG
-
-
-        private TWinRtStream EnsureNotDisposed<TWinRtStream>() where TWinRtStream : class
+        private TWinRtStream? EnsureNotDisposed<TWinRtStream>() where TWinRtStream : class
         {
-            object wrtStr = _winRtStream;
+            object? wrtStr = _winRtStream;
 
             if (wrtStr == null)
                 throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation);
@@ -196,7 +187,7 @@ namespace System.IO
             // WinRT streams should implement IDisposable (IClosable in WinRT), but let's be defensive:
             if (disposing && _winRtStream != null && !_leaveUnderlyingStreamOpen)
             {
-                IDisposable disposableWinRtStream = _winRtStream as IDisposable;  // benign race on winRtStream
+                IDisposable? disposableWinRtStream = _winRtStream as IDisposable;  // benign race on winRtStream
                 if (disposableWinRtStream != null)
                     disposableWinRtStream.Dispose();
             }
@@ -238,14 +229,12 @@ namespace System.IO
         {
             get
             {
-                IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
+                IRandomAccessStream? wrtStr = EnsureNotDisposed<IRandomAccessStream>();
 
                 if (!_canSeek)
                     throw new NotSupportedException(SR.NotSupported_CannotUseLength_StreamNotSeekable);
 
-#if DEBUG
-                AssertValidStream(wrtStr);
-#endif  // DEBUG
+                Debug.Assert(wrtStr != null);
 
                 ulong size = wrtStr.Size;
 
@@ -262,14 +251,12 @@ namespace System.IO
         {
             get
             {
-                IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
+                IRandomAccessStream? wrtStr = EnsureNotDisposed<IRandomAccessStream>();
 
                 if (!_canSeek)
                     throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable);
 
-#if DEBUG
-                AssertValidStream(wrtStr);
-#endif  // DEBUG
+                Debug.Assert(wrtStr != null);
 
                 ulong pos = wrtStr.Position;
 
@@ -285,14 +272,12 @@ namespace System.IO
                 if (value < 0)
                     throw new ArgumentOutOfRangeException(nameof(Position), SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition);
 
-                IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
+                IRandomAccessStream? wrtStr = EnsureNotDisposed<IRandomAccessStream>();
 
                 if (!_canSeek)
                     throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable);
 
-#if DEBUG
-                AssertValidStream(wrtStr);
-#endif  // DEBUG
+                Debug.Assert(wrtStr != null);
 
                 wrtStr.Seek(unchecked((ulong)value));
             }
@@ -301,14 +286,12 @@ namespace System.IO
 
         public override long Seek(long offset, SeekOrigin origin)
         {
-            IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
+            IRandomAccessStream? wrtStr = EnsureNotDisposed<IRandomAccessStream>();
 
             if (!_canSeek)
                 throw new NotSupportedException(SR.NotSupported_CannotSeekInStream);
 
-#if DEBUG
-            AssertValidStream(wrtStr);
-#endif  // DEBUG
+            Debug.Assert(wrtStr != null);
 
             switch (origin)
             {
@@ -387,16 +370,14 @@ namespace System.IO
             if (value < 0)
                 throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_CannotResizeStreamToNegative);
 
-            IRandomAccessStream wrtStr = EnsureNotDisposed<IRandomAccessStream>();
+            IRandomAccessStream? wrtStr = EnsureNotDisposed<IRandomAccessStream>();
 
             if (!_canSeek)
                 throw new NotSupportedException(SR.NotSupported_CannotSeekInStream);
 
             EnsureCanWrite();
 
-#if DEBUG
-            AssertValidStream(wrtStr);
-#endif  // DEBUG
+            Debug.Assert(wrtStr != null);
 
             wrtStr.Size = unchecked((ulong)value);
 
@@ -411,7 +392,7 @@ namespace System.IO
 
         #region Reading
 
-        private IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool usedByBlockingWrapper)
+        private IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state, bool usedByBlockingWrapper)
         {
             // This method is somewhat tricky: We could consider just calling ReadAsync (recall that Task implements IAsyncResult).
             // It would be OK for cases where BeginRead is invoked directly by the public user.
@@ -448,12 +429,10 @@ namespace System.IO
             if (buffer.Length - offset < count)
                 throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
 
-            IInputStream wrtStr = EnsureNotDisposed<IInputStream>();
+            IInputStream? wrtStr = EnsureNotDisposed<IInputStream>();
             EnsureCanRead();
 
-#if DEBUG
-            AssertValidStream(wrtStr);
-#endif  // DEBUG
+            Debug.Assert(wrtStr != null);
 
             IBuffer userBuffer = buffer.AsBuffer(offset, count);
             IAsyncOperationWithProgress<IBuffer, uint> asyncReadOperation = wrtStr.ReadAsync(userBuffer,
@@ -480,7 +459,7 @@ namespace System.IO
             EnsureNotDisposed();
             EnsureCanRead();
 
-            StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult;
+            StreamOperationAsyncResult? streamAsyncResult = asyncResult as StreamOperationAsyncResult;
             if (streamAsyncResult == null)
                 throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult));
 
@@ -570,12 +549,12 @@ namespace System.IO
         #region Writing
 
 
-        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
         {
             return BeginWrite(buffer, offset, count, callback, state, usedByBlockingWrapper: false);
         }
 
-        private IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool usedByBlockingWrapper)
+        private IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state, bool usedByBlockingWrapper)
         {
             // See the large comment in BeginRead about why we are not using this.WriteAsync,
             // and instead using a custom implementation of IAsyncResult.
@@ -592,12 +571,10 @@ namespace System.IO
             if (buffer.Length - offset < count)
                 throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
 
-            IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
+            IOutputStream? wrtStr = EnsureNotDisposed<IOutputStream>();
             EnsureCanWrite();
 
-#if DEBUG
-            AssertValidStream(wrtStr);
-#endif  // DEBUG
+            Debug.Assert(wrtStr != null);
 
             IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count);
 
@@ -623,7 +600,7 @@ namespace System.IO
             EnsureNotDisposed();
             EnsureCanWrite();
 
-            StreamOperationAsyncResult streamAsyncResult = asyncResult as StreamOperationAsyncResult;
+            StreamOperationAsyncResult? streamAsyncResult = asyncResult as StreamOperationAsyncResult;
             if (streamAsyncResult == null)
                 throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult));
 
@@ -666,12 +643,10 @@ namespace System.IO
             if (buffer.Length - offset < count)
                 throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
 
-            IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
+            IOutputStream? wrtStr = EnsureNotDisposed<IOutputStream>();
             EnsureCanWrite();
 
-#if DEBUG
-            AssertValidStream(wrtStr);
-#endif  // DEBUG
+            Debug.Assert(wrtStr != null);
 
             // If already cancelled, bail early:
             cancellationToken.ThrowIfCancellationRequested();
@@ -717,15 +692,13 @@ namespace System.IO
             // See the large comment in BeginRead about why we are not using this.FlushAsync,
             // and instead using a custom implementation of IAsyncResult.
 
-            IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
+            IOutputStream? wrtStr = EnsureNotDisposed<IOutputStream>();
 
             // Calling Flush in a non-writable stream is a no-op, not an error:
             if (!_canWrite)
                 return;
 
-#if DEBUG
-            AssertValidStream(wrtStr);
-#endif  // DEBUG
+            Debug.Assert(wrtStr != null);
 
             IAsyncOperation<bool> asyncFlushOperation = wrtStr.FlushAsync();
             StreamFlushAsyncResult asyncResult = new StreamFlushAsyncResult(asyncFlushOperation, processCompletedOperationInCallback: false);
@@ -755,15 +728,13 @@ namespace System.IO
 
         public override Task FlushAsync(CancellationToken cancellationToken)
         {
-            IOutputStream wrtStr = EnsureNotDisposed<IOutputStream>();
+            IOutputStream? wrtStr = EnsureNotDisposed<IOutputStream>();
 
             // Calling Flush in a non-writable stream is a no-op, not an error:
             if (!_canWrite)
                 return Task.CompletedTask;
 
-#if DEBUG
-            AssertValidStream(wrtStr);
-#endif  // DEBUG
+            Debug.Assert(wrtStr != null);
 
             cancellationToken.ThrowIfCancellationRequested();
 
@@ -787,11 +758,9 @@ namespace System.IO
             Debug.Assert(buffer.Length - offset >= count);
             Debug.Assert(_canRead);
 
-            IInputStream wrtStr = EnsureNotDisposed<IInputStream>();
+            IInputStream? wrtStr = EnsureNotDisposed<IInputStream>();
 
-#if DEBUG
-            AssertValidStream(wrtStr);
-#endif  // DEBUG
+            Debug.Assert(wrtStr != null);
 
             try
             {
index dad2ca5..09f870b 100644 (file)
@@ -176,7 +176,7 @@ namespace System.IO
         }
 
         [CLSCompliant(false)]
-        public static SafeFileHandle CreateSafeFileHandle(
+        public static SafeFileHandle? CreateSafeFileHandle(
             this IStorageFile windowsRuntimeFile,
             FileAccess access = FileAccess.ReadWrite,
             FileShare share = FileShare.Read,
@@ -189,7 +189,7 @@ namespace System.IO
             HANDLE_SHARING_OPTIONS sharingOptions = FileShareToHandleSharingOptions(share);
             HANDLE_OPTIONS handleOptions = FileOptionsToHandleOptions(options);
 
-            IStorageItemHandleAccess handleAccess = ((object)windowsRuntimeFile) as IStorageItemHandleAccess;
+            IStorageItemHandleAccess? handleAccess = ((object)windowsRuntimeFile) as IStorageItemHandleAccess;
 
             if (handleAccess == null)
                 return null;
@@ -210,7 +210,7 @@ namespace System.IO
         }
 
         [CLSCompliant(false)]
-        public static SafeFileHandle CreateSafeFileHandle(
+        public static SafeFileHandle? CreateSafeFileHandle(
             this IStorageFolder rootDirectory,
             string relativePath,
             FileMode mode)
@@ -219,7 +219,7 @@ namespace System.IO
         }
 
         [CLSCompliant(false)]
-        public static SafeFileHandle CreateSafeFileHandle(
+        public static SafeFileHandle? CreateSafeFileHandle(
             this IStorageFolder rootDirectory,
             string relativePath,
             FileMode mode,
@@ -237,7 +237,7 @@ namespace System.IO
             HANDLE_SHARING_OPTIONS sharingOptions = FileShareToHandleSharingOptions(share);
             HANDLE_OPTIONS handleOptions = FileOptionsToHandleOptions(options);
 
-            IStorageFolderHandleAccess handleAccess = ((object)rootDirectory) as IStorageFolderHandleAccess;
+            IStorageFolderHandleAccess? handleAccess = ((object)rootDirectory) as IStorageFolderHandleAccess;
 
             if (handleAccess == null)
                 return null;
index d96db30..e84c3a8 100644 (file)
@@ -40,7 +40,7 @@ namespace System.IO
                                                                                                 where TKey : class
                                                                                                 where TValue : class
         {
-            TValue valueInMap;
+            TValue? valueInMap;
 
             Debug.Assert(key != null);
 
@@ -50,7 +50,7 @@ namespace System.IO
 
             if (valueMayBeWrappedInBufferedStream)
             {
-                BufferedStream bufferedValueInMap = valueInMap as BufferedStream;
+                BufferedStream? bufferedValueInMap = valueInMap as BufferedStream;
                 Debug.Assert(object.ReferenceEquals(value, valueInMap)
                                 || (bufferedValueInMap != null && object.ReferenceEquals(value, bufferedValueInMap.UnderlyingStream)));
             }
@@ -67,7 +67,7 @@ namespace System.IO
             Debug.Assert(!string.IsNullOrWhiteSpace(methodName));
 
             int currentBufferSize = 0;
-            BufferedStream bufferedAdapter = adapter as BufferedStream;
+            BufferedStream? bufferedAdapter = adapter as BufferedStream;
             if (bufferedAdapter != null)
                 currentBufferSize = bufferedAdapter.BufferSize;
 
@@ -142,10 +142,10 @@ namespace System.IO
 
             // We currently do capability-based adapter selection for WinRt->NetFx, but not vice versa (time constraints).
             // Once we added the reverse direction, we will be able replce this entire section with just a few lines.
-            NetFxToWinRtStreamAdapter sAdptr = windowsRuntimeStream as NetFxToWinRtStreamAdapter;
+            NetFxToWinRtStreamAdapter? sAdptr = windowsRuntimeStream as NetFxToWinRtStreamAdapter;
             if (sAdptr != null)
             {
-                Stream wrappedNetFxStream = sAdptr.GetManagedStream();
+                Stream? wrappedNetFxStream = sAdptr.GetManagedStream();
                 if (wrappedNetFxStream == null)
                     throw new ObjectDisposedException(nameof(windowsRuntimeStream), SR.ObjectDisposed_CannotPerformOperation);
 
@@ -159,7 +159,7 @@ namespace System.IO
 
             // We have a real WinRT stream.
 
-            Stream adapter;
+            Stream? adapter;
             bool adapterExists = s_winRtToNetFxAdapterMap.TryGetValue(windowsRuntimeStream, out adapter);
 
             // There is already an adapter:
@@ -215,11 +215,11 @@ namespace System.IO
             if (forceBufferSize)
                 EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName);
 
-            WinRtToNetFxStreamAdapter actualAdapter = adapter as WinRtToNetFxStreamAdapter;
+            WinRtToNetFxStreamAdapter? actualAdapter = adapter as WinRtToNetFxStreamAdapter;
             if (actualAdapter == null)
                 actualAdapter = ((BufferedStream)adapter).UnderlyingStream as WinRtToNetFxStreamAdapter;
 
-            actualAdapter.SetWonInitializationRace();
+            actualAdapter!.SetWonInitializationRace();
 
             return adapter;
         }
@@ -240,7 +240,7 @@ namespace System.IO
 
             object adapter = AsWindowsRuntimeStreamInternal(stream);
 
-            IInputStream winRtStream = adapter as IInputStream;
+            IInputStream? winRtStream = adapter as IInputStream;
             Debug.Assert(winRtStream != null);
 
             return winRtStream;
@@ -258,7 +258,7 @@ namespace System.IO
 
             object adapter = AsWindowsRuntimeStreamInternal(stream);
 
-            IOutputStream winRtStream = adapter as IOutputStream;
+            IOutputStream? winRtStream = adapter as IOutputStream;
             Debug.Assert(winRtStream != null);
 
             return winRtStream;
@@ -276,7 +276,7 @@ namespace System.IO
 
             object adapter = AsWindowsRuntimeStreamInternal(stream);
 
-            IRandomAccessStream winRtStream = adapter as IRandomAccessStream;
+            IRandomAccessStream? winRtStream = adapter as IRandomAccessStream;
             Debug.Assert(winRtStream != null);
 
             return winRtStream;
@@ -287,10 +287,10 @@ namespace System.IO
         {
             // Check to see if the managed stream is actually a wrapper of a WinRT stream:
             // (This can be either an adapter directly, or an adapter wrapped in a BufferedStream.)
-            WinRtToNetFxStreamAdapter sAdptr = stream as WinRtToNetFxStreamAdapter;
+            WinRtToNetFxStreamAdapter? sAdptr = stream as WinRtToNetFxStreamAdapter;
             if (sAdptr == null)
             {
-                BufferedStream buffAdptr = stream as BufferedStream;
+                BufferedStream? buffAdptr = stream as BufferedStream;
                 if (buffAdptr != null)
                     sAdptr = buffAdptr.UnderlyingStream as WinRtToNetFxStreamAdapter;
             }
@@ -299,7 +299,7 @@ namespace System.IO
             // In that case we do not need to put the wrapper into the map.
             if (sAdptr != null)
             {
-                object wrappedWinRtStream = sAdptr.GetWindowsRuntimeStream<object>();
+                object? wrappedWinRtStream = sAdptr.GetWindowsRuntimeStream<object>();
                 if (wrappedWinRtStream == null)
                     throw new ObjectDisposedException(nameof(stream), SR.ObjectDisposed_CannotPerformOperation);
 
@@ -312,12 +312,12 @@ namespace System.IO
             // We have a real managed Stream.
 
             // See if the managed stream already has an adapter:
-            NetFxToWinRtStreamAdapter adapter;
+            NetFxToWinRtStreamAdapter? adapter;
             bool adapterExists = s_netFxToWinRtAdapterMap.TryGetValue(stream, out adapter);
 
             // There is already an adapter:
             if (adapterExists)
-                return adapter;
+                return adapter!;
 
             // We do not have an adapter for this managed stream yet and we need to create one.
             // Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating
index 3cf8427..3e9de88 100644 (file)
@@ -29,34 +29,34 @@ namespace System.Resources
         // invariant name is an empty string. We will use the private invariant culture name x-VL instead.
         private const string c_InvariantCulturePrivateName = "x-VL";
 
-        private ResourceMap _resourceMap;
-        private ResourceContext _clonedResourceContext;
-        private string _clonedResourceContextFallBackList;
+        private ResourceMap? _resourceMap;
+        private ResourceContext? _clonedResourceContext;
+        private string? _clonedResourceContextFallBackList;
 
-        private static char[] s_charCultureSeparator;
+        private static char[]? s_charCultureSeparator;
 
         private struct PackageInfo
         {
-            public string Path;
-            public string Name;
-            public string FullName;
+            public string? Path;
+            public string? Name;
+            public string? FullName;
         }
 
         private static PackageInfo s_currentPackageInfo;
 
-        private static List<PackageInfo> s_dependentPackageInfoList;
+        private static List<PackageInfo>? s_dependentPackageInfoList;
 
-        private static ResourceContext s_globalResourceContext; // Read from it but do not modify it or call Reset() on it as that would affect the app-wide state
+        private static ResourceContext? s_globalResourceContext; // Read from it but do not modify it or call Reset() on it as that would affect the app-wide state
 
-        private static volatile string s_globalResourceContextFallBackList;
-        private static volatile CultureInfo s_globalResourceContextBestFitCultureInfo;
-        private static volatile global::Windows.ApplicationModel.Resources.Core.ResourceManager s_globalResourceManager;
+        private static volatile string? s_globalResourceContextFallBackList;
+        private static volatile CultureInfo? s_globalResourceContextBestFitCultureInfo;
+        private static volatile global::Windows.ApplicationModel.Resources.Core.ResourceManager? s_globalResourceManager;
 
         private static readonly object s_objectForLock = new object(); // Used by InitializeStatics
 
         private static bool InitializeStatics()
         {
-            global::Windows.ApplicationModel.Resources.Core.ResourceManager globalResourceManager = null;
+            global::Windows.ApplicationModel.Resources.Core.ResourceManager? globalResourceManager = null;
 
             if (s_globalResourceManager == null)
             {
@@ -104,7 +104,7 @@ namespace System.Resources
             return s_globalResourceManager != null;
         }
 
-        private static void InitializeStaticGlobalResourceContext(global::Windows.ApplicationModel.Resources.Core.ResourceManager resourceManager)
+        private static void InitializeStaticGlobalResourceContext(global::Windows.ApplicationModel.Resources.Core.ResourceManager? resourceManager)
         {
             if (s_globalResourceContext == null)
             {
@@ -137,7 +137,7 @@ namespace System.Resources
 
         // Returns the CultureInfo representing the first language in the list that we can construct a CultureInfo for or null if
         // no such culture exists.
-        private static unsafe CultureInfo GetBestFitCultureFromLanguageList(List<string> languages)
+        private static unsafe CultureInfo? GetBestFitCultureFromLanguageList(List<string> languages)
         {
             char* localeNameBuffer = stackalloc char[Interop.Kernel32.LOCALE_NAME_MAX_LENGTH]; // LOCALE_NAME_MAX_LENGTH includes null terminator
 
@@ -285,7 +285,7 @@ namespace System.Resources
         }
 #endif
 
-        private static string FindPackageSimpleNameForFilename(string libpath)
+        private static string? FindPackageSimpleNameForFilename(string libpath)
         {
             Debug.Assert(libpath != null);
             Debug.Assert(s_currentPackageInfo.Path != null); // Set in InitializeStatics()
@@ -298,9 +298,9 @@ namespace System.Resources
                 InitializeStaticsForDependentPackages();
 
                 // s_dependentPackageInfoList is empty (but non-null) if there are no dependent packages.
-                foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList)
+                foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList!)
                 {
-                    if (LibpathMatchesPackagepath(libpath, dependentPackageInfo.Path))
+                    if (LibpathMatchesPackagepath(libpath, dependentPackageInfo.Path!))
                         return dependentPackageInfo.Name; // This may be null, in which case we failed to get the name (in InitializeStaticsForDependentPackages), but matched the path, so stop looking.
                 }
             }
@@ -312,14 +312,14 @@ namespace System.Resources
                package name as subfolder in its path. Based on this assumption we can find the package
                to which an NI belongs. Below code does that.
               */
-            if (LibpathContainsPackagename(libpath, s_currentPackageInfo.FullName))
+            if (LibpathContainsPackagename(libpath, s_currentPackageInfo.FullName!))
                 return s_currentPackageInfo.Name;
             else // Look at dependent packages
             {
                 // s_dependentPackageInfoList is empty (but non-null) if there are no dependent packages.
                 foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList)
                 {
-                    if (LibpathContainsPackagename(libpath, dependentPackageInfo.FullName))
+                    if (LibpathContainsPackagename(libpath, dependentPackageInfo.FullName!))
                         return dependentPackageInfo.Name;
                 }
             }
@@ -339,7 +339,7 @@ namespace System.Resources
         // Only returns true if the function succeeded completely.
         // Outputs exceptionInfo since it may be needed for debugging purposes
         // if an exception is thrown by one of Initialize's callees.
-        public override bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo exceptionInfo)
+        public override bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo? exceptionInfo)
         {
             Debug.Assert(libpath != null);
             Debug.Assert(reswFilename != null);
@@ -357,11 +357,11 @@ namespace System.Resources
                 // reliable information to include in it.
 
                 IReadOnlyDictionary<string, ResourceMap>
-                    resourceMapDictionary = s_globalResourceManager.AllResourceMaps;
+                    resourceMapDictionary = s_globalResourceManager!.AllResourceMaps;
 
                 if (resourceMapDictionary != null)
                 {
-                    string packageSimpleName = FindPackageSimpleNameForFilename(libpath);
+                    string? packageSimpleName = FindPackageSimpleNameForFilename(libpath);
 
 #if NETSTANDARD2_0 || NETCOREAPP
                     // If we have found a simple package name for the assembly, lets make sure it is not *.resource.dll that
@@ -379,7 +379,7 @@ namespace System.Resources
 #endif
                     if (packageSimpleName != null)
                     {
-                        ResourceMap packageResourceMap = null;
+                        ResourceMap? packageResourceMap = null;
 
                         // Win8 enforces that package simple names are unique (for example, the App Store will not
                         // allow two apps with the same package simple name). That is why the Modern Resource Manager
@@ -391,7 +391,7 @@ namespace System.Resources
                                 // GetSubtree returns null when it cannot find resource strings
                                 // named "reswFilename/*" for the package we are looking up.
 
-                                reswFilename = UriUtility.UriEncode(reswFilename);
+                                reswFilename = UriUtility.UriEncode(reswFilename)!;
                                 _resourceMap = packageResourceMap.GetSubtree(reswFilename);
 
                                 if (_resourceMap == null)
@@ -402,7 +402,7 @@ namespace System.Resources
                                 }
                                 else
                                 {
-                                    _clonedResourceContext = s_globalResourceContext.Clone();
+                                    _clonedResourceContext = s_globalResourceContext!.Clone();
 
                                     if (_clonedResourceContext != null)
                                     {
@@ -443,7 +443,7 @@ namespace System.Resources
             get
             {
                 InitializeStaticGlobalResourceContext(null);
-                return s_globalResourceContextBestFitCultureInfo;
+                return s_globalResourceContextBestFitCultureInfo!;
             }
         }
 
@@ -501,15 +501,14 @@ namespace System.Resources
         // continue to be thread-safe.
 
         // Throws exceptions
-        public override string GetString(string stringName,
-                 string startingCulture, string neutralResourcesCulture)
+        public override string? GetString(string stringName, string? startingCulture, string? neutralResourcesCulture)
         {
             Debug.Assert(stringName != null);
             Debug.Assert(_resourceMap != null); // Should have been initialized by now
 
-            ResourceCandidate resourceCandidate = null;
+            ResourceCandidate? resourceCandidate = null;
 
-            stringName = UriUtility.UriEncode(stringName);
+            stringName = UriUtility.UriEncode(stringName)!;
 
             if (startingCulture == null && neutralResourcesCulture == null)
             {
@@ -528,7 +527,7 @@ namespace System.Resources
                 // The starting culture has to be looked up first, and neutral resources culture has
                 // to be looked up last.
 
-                string newResourceFallBackList = null;
+                string? newResourceFallBackList = null;
 
                 newResourceFallBackList =
                     (startingCulture == null ? "" : startingCulture + ";") +
@@ -577,7 +576,7 @@ namespace System.Resources
         // Adapted from the UrlEncode methods originally
         // in file:ndp\fx\src\xsp\system\web\httpserverutility.cs
         // and file:ndp\fx\src\xsp\system\web\util\httpencoder.cs
-        public static string UriEncode(string str)
+        public static string? UriEncode(string str)
         {
             if (str == null)
                 return null;
@@ -598,7 +597,7 @@ namespace System.Resources
                     cBytesToEncode++;
             }
 
-            byte[] expandedBytes = null;
+            byte[]? expandedBytes = null;
 
             // nothing to expand?
             if (cBytesToEncode == 0)
index 484bd84..9daa7cf 100644 (file)
@@ -88,7 +88,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         // The return type for this function is actually an INotifyCollectionChangedEventArgs*
         // but we need to make sure we don't accidentally project our native object back to managed
         // when marshalling it to native (which happens when correctly typing the return type as an INotifyCollectionChangedEventArgs).
-        IntPtr CreateInstanceWithAllParameters(int action, IList newItems, IList oldItems, int newIndex, int oldIndex, object outer, ref object inner);
+        IntPtr CreateInstanceWithAllParameters(int action, IList? newItems, IList? oldItems, int newIndex, int oldIndex, object? outer, ref object? inner);
     }
 
     // Local definition of Windows.UI.Xaml.Data.INotifyCollectionChangedEventArgsFactory
@@ -100,14 +100,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         // The return type for this function is actually an IPropertyChangedEventArgs*
         // but we need to make sure we don't accidentally project our native object back to managed
         // when marshalling it to native (which happens when correctly typing the return type as an IPropertyChangedEventArgs).
-        IntPtr CreateInstance(string name, object outer, ref object inner);
+        IntPtr CreateInstance(string? name, object? outer, ref object? inner);
     }
 
     internal static class NotifyCollectionChangedEventArgsMarshaler
     {
         private const string WinRTNotifyCollectionChangedEventArgsName = "Windows.UI.Xaml.Interop.NotifyCollectionChangedEventArgs";
 
-        private static INotifyCollectionChangedEventArgsFactory s_EventArgsFactory;
+        private static INotifyCollectionChangedEventArgsFactory? s_EventArgsFactory;
 
         // Extracts properties from a managed NotifyCollectionChangedEventArgs and passes them to
         // a VM-implemented helper that creates a WinRT NotifyCollectionChangedEventArgs instance.
@@ -119,7 +119,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
             if (s_EventArgsFactory == null)
             {
-                object factory = null;
+                object? factory = null;
                 Guid guid = typeof(INotifyCollectionChangedEventArgsFactory).GUID;
                 int hr = Interop.mincore.RoGetActivationFactory(WinRTNotifyCollectionChangedEventArgsName, ref guid, out factory);
                 if (hr < 0)
@@ -128,14 +128,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 s_EventArgsFactory = (INotifyCollectionChangedEventArgsFactory)factory;
             }
 
-            object inner = null;
+            object? inner = null;
             return s_EventArgsFactory.CreateInstanceWithAllParameters((int)managedArgs.Action, managedArgs.NewItems, managedArgs.OldItems, managedArgs.NewStartingIndex, managedArgs.OldStartingIndex, null, ref inner);
         }
 
         // Extracts properties from a WinRT NotifyCollectionChangedEventArgs and creates a new
         // managed NotifyCollectionChangedEventArgs instance.
         // This method is called from IL stubs and needs to have its token stabilized.
-        internal static NotifyCollectionChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP)
+        internal static NotifyCollectionChangedEventArgs? ConvertToManaged(IntPtr nativeArgsIP)
         {
             if (nativeArgsIP == IntPtr.Zero)
                 return null;
@@ -168,7 +168,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
     {
         private const string WinRTPropertyChangedEventArgsName = "Windows.UI.Xaml.Data.PropertyChangedEventArgs";
 
-        private static IPropertyChangedEventArgsFactory s_pPCEventArgsFactory;
+        private static IPropertyChangedEventArgsFactory? s_pPCEventArgsFactory;
 
         // Extracts PropertyName from a managed PropertyChangedEventArgs and passes them to
         // a VM-implemented helper that creates a WinRT PropertyChangedEventArgs instance.
@@ -180,7 +180,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
             if (s_pPCEventArgsFactory == null)
             {
-                object factory = null;
+                object? factory = null;
                 Guid guid = typeof(IPropertyChangedEventArgsFactory).GUID;
                 int hr = Interop.mincore.RoGetActivationFactory(WinRTPropertyChangedEventArgsName, ref guid, out factory);
                 if (hr < 0)
@@ -189,14 +189,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 s_pPCEventArgsFactory = (IPropertyChangedEventArgsFactory)factory;
             }
 
-            object inner = null;
+            object? inner = null;
             return s_pPCEventArgsFactory.CreateInstance(managedArgs.PropertyName, null, ref inner);
         }
 
         // Extracts properties from a WinRT PropertyChangedEventArgs and creates a new
         // managed PropertyChangedEventArgs instance.
         // This method is called from IL stubs and needs to have its token stabilized.
-        internal static PropertyChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP)
+        internal static PropertyChangedEventArgs? ConvertToManaged(IntPtr nativeArgsIP)
         {
             if (nativeArgsIP == IntPtr.Zero)
                 return null;
@@ -282,7 +282,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             INotifyCollectionChanged _this = Unsafe.As<INotifyCollectionChanged>(this);
             EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
 
-            if (table.RemoveEventHandler(token, out NotifyCollectionChangedEventHandler handler))
+            if (table.RemoveEventHandler(token, out NotifyCollectionChangedEventHandler? handler))
             {
                 _this.CollectionChanged -= handler;
             }
@@ -363,7 +363,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             INotifyPropertyChanged _this = Unsafe.As<INotifyPropertyChanged>(this);
             EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
 
-            if (table.RemoveEventHandler(token, out PropertyChangedEventHandler handler))
+            if (table.RemoveEventHandler(token, out PropertyChangedEventHandler? handler))
             {
                 _this.PropertyChanged -= handler;
             }
@@ -470,7 +470,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             ICommand _this = Unsafe.As<ICommand>(this);
             EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this);
 
-            if (table.RemoveEventHandler(token, out EventHandler handler))
+            if (table.RemoveEventHandler(token, out EventHandler? handler))
             {
                 _this.CanExecuteChanged -= handler;
             }
@@ -496,16 +496,16 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         {
             // Check whether it is a round-tripping case i.e. the sender is of the type eventArgs,
             // If so we use it else we pass EventArgs.Empty
-            return (object sender, object e) =>
+            return (object? sender, object e) =>
                 {
-                    EventArgs eventArgs = e as EventArgs;
+                    EventArgs? eventArgs = e as EventArgs;
                     handler(sender, (eventArgs == null ? System.EventArgs.Empty : eventArgs));
                 };
         }
 
         internal static EventHandler CreateWrapperHandler(EventHandler<object> handler)
         {
-            return (object sender, EventArgs e) => handler(sender, e);
+            return (object? sender, EventArgs e) => handler(sender, e);
         }
 
         internal static EventHandler<object> GetValueFromEquivalentKey(
index 93507d8..04847a7 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.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Security;
@@ -63,7 +64,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         // This object handles IMarshal calls for us:
         [ThreadStatic]
-        private static IMarshal t_winRtMarshalProxy = null;
+        private static IMarshal? t_winRtMarshalProxy = null;
 
         private static void EnsureHasMarshalProxy()
         {
@@ -99,7 +100,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         #region Fields
 
-        private readonly byte[] _data = null;
+        private readonly byte[] _data;
         private readonly int _dataStartOffs = 0;
         private int _usefulDataLength = 0;
         private readonly int _maxDataCapacity = 0;
@@ -148,9 +149,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
 
         #region Helpers
 
-        internal void GetUnderlyingData(out byte[] underlyingDataArray, out int underlyingDataArrayStartOffset)
+        internal void GetUnderlyingData([NotNull] out byte[]? underlyingDataArray, out int underlyingDataArrayStartOffset)
         {
-            underlyingDataArray = _data;
+            underlyingDataArray = _data!;
             underlyingDataArrayStartOffset = _dataStartOffs;
         }
 
@@ -262,42 +263,42 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         void IMarshal.DisconnectObject(uint dwReserved)
         {
             EnsureHasMarshalProxy();
-            t_winRtMarshalProxy.DisconnectObject(dwReserved);
+            t_winRtMarshalProxy!.DisconnectObject(dwReserved);
         }
 
 
         void IMarshal.GetMarshalSizeMax(ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlflags, out uint pSize)
         {
             EnsureHasMarshalProxy();
-            t_winRtMarshalProxy.GetMarshalSizeMax(ref riid, pv, dwDestContext, pvDestContext, mshlflags, out pSize);
+            t_winRtMarshalProxy!.GetMarshalSizeMax(ref riid, pv, dwDestContext, pvDestContext, mshlflags, out pSize);
         }
 
 
         void IMarshal.GetUnmarshalClass(ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlFlags, out Guid pCid)
         {
             EnsureHasMarshalProxy();
-            t_winRtMarshalProxy.GetUnmarshalClass(ref riid, pv, dwDestContext, pvDestContext, mshlFlags, out pCid);
+            t_winRtMarshalProxy!.GetUnmarshalClass(ref riid, pv, dwDestContext, pvDestContext, mshlFlags, out pCid);
         }
 
 
         void IMarshal.MarshalInterface(IntPtr pStm, ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlflags)
         {
             EnsureHasMarshalProxy();
-            t_winRtMarshalProxy.MarshalInterface(pStm, ref riid, pv, dwDestContext, pvDestContext, mshlflags);
+            t_winRtMarshalProxy!.MarshalInterface(pStm, ref riid, pv, dwDestContext, pvDestContext, mshlflags);
         }
 
 
         void IMarshal.ReleaseMarshalData(IntPtr pStm)
         {
             EnsureHasMarshalProxy();
-            t_winRtMarshalProxy.ReleaseMarshalData(pStm);
+            t_winRtMarshalProxy!.ReleaseMarshalData(pStm);
         }
 
 
         void IMarshal.UnmarshalInterface(IntPtr pStm, ref Guid riid, out IntPtr ppv)
         {
             EnsureHasMarshalProxy();
-            t_winRtMarshalProxy.UnmarshalInterface(pStm, ref riid, out ppv);
+            t_winRtMarshalProxy!.UnmarshalInterface(pStm, ref riid, out ppv);
         }
         #endregion Implementation of IMarshal
 
index 9e757f5..35a4bae 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.IO;
 using Windows.Foundation;
 using Windows.Storage.Streams;
@@ -94,7 +95,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
 
             // If destination is backed by a managed array, use the array instead of the pointer as it does not require pinning:
-            byte[] destDataArr;
+            byte[]? destDataArr;
             int destDataOffs;
             if (destination.TryGetUnderlyingData(out destDataArr, out destDataOffs))
             {
@@ -164,7 +165,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             if (destination.Length - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset);
 
             // If source is backed by a managed array, use the array instead of the pointer as it does not require pinning:
-            byte[] srcDataArr;
+            byte[]? srcDataArr;
             int srcDataOffs;
             if (source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs))
             {
@@ -202,7 +203,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer);
 
             // If source are destination are backed by managed arrays, use the arrays instead of the pointers as it does not require pinning:
-            byte[] srcDataArr, destDataArr;
+            byte[]? srcDataArr, destDataArr;
             int srcDataOffs, destDataOffs;
 
             bool srcIsManaged = source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs);
@@ -214,7 +215,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 Debug.Assert(sourceIndex <= int.MaxValue);
                 Debug.Assert(destinationIndex <= int.MaxValue);
 
-                Buffer.BlockCopy(srcDataArr, srcDataOffs + (int)sourceIndex, destDataArr, destDataOffs + (int)destinationIndex, (int)count);
+                Buffer.BlockCopy(srcDataArr!, srcDataOffs + (int)sourceIndex, destDataArr!, destDataOffs + (int)destinationIndex, (int)count);
                 return;
             }
 
@@ -226,7 +227,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 Debug.Assert(sourceIndex <= int.MaxValue);
 
                 destPtr = destination.GetPointerAtOffset(destinationIndex);
-                Marshal.Copy(srcDataArr, srcDataOffs + (int)sourceIndex, destPtr, (int)count);
+                Marshal.Copy(srcDataArr!, srcDataOffs + (int)sourceIndex, destPtr, (int)count);
                 return;
             }
 
@@ -236,7 +237,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
                 Debug.Assert(destinationIndex <= int.MaxValue);
 
                 srcPtr = source.GetPointerAtOffset(sourceIndex);
-                Marshal.Copy(srcPtr, destDataArr, destDataOffs + (int)destinationIndex, (int)count);
+                Marshal.Copy(srcPtr, destDataArr!, destDataOffs + (int)destinationIndex, (int)count);
                 return;
             }
 
@@ -263,12 +264,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         /// <param name="underlyingDataArrayStartOffset">Will be set to the start offset of the buffer data in the backing array
         /// or to <code>-1</code>.</param>
         /// <returns>Whether the <code>IBuffer</code> is backed by a managed byte array.</returns>
-        internal static bool TryGetUnderlyingData(this IBuffer buffer, out byte[] underlyingDataArray, out int underlyingDataArrayStartOffset)
+        internal static bool TryGetUnderlyingData(this IBuffer buffer, [NotNullWhen(true)] out byte[]? underlyingDataArray, out int underlyingDataArrayStartOffset)
         {
             if (buffer == null)
                 throw new ArgumentNullException(nameof(buffer));
 
-            WindowsRuntimeBuffer winRtBuffer = buffer as WindowsRuntimeBuffer;
+            WindowsRuntimeBuffer? winRtBuffer = buffer as WindowsRuntimeBuffer;
             if (winRtBuffer == null)
             {
                 underlyingDataArray = null;
@@ -292,7 +293,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
         /// <returns><code>true</code> if the underlying <code>Buffer</code> memory pointer is the same for both specified
         /// <code>IBuffer</code> instances (i.e. if they are backed by the same memory); <code>false</code> otherwise.</returns>
         [CLSCompliant(false)]
-        public static bool IsSameData(this IBuffer buffer, IBuffer otherBuffer)
+        public static bool IsSameData(this IBuffer buffer, IBuffer? otherBuffer)
         {
             if (buffer == null)
                 throw new ArgumentNullException(nameof(buffer));
@@ -303,7 +304,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             if (buffer == otherBuffer)
                 return true;
 
-            byte[] thisDataArr, otherDataArr;
+            byte[]? thisDataArr, otherDataArr;
             int thisDataOffs, otherDataOffs;
 
             bool thisIsManaged = buffer.TryGetUnderlyingData(out thisDataArr, out thisDataOffs);
@@ -351,7 +352,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             {
                 throw new UnauthorizedAccessException(SR.UnauthorizedAccess_InternalBuffer);
             }
-            return new WindowsRuntimeBuffer(streamData.Array, (int)streamData.Offset, (int)underlyingStream.Length, underlyingStream.Capacity);
+            return new WindowsRuntimeBuffer(streamData.Array!, (int)streamData.Offset, (int)underlyingStream.Length, underlyingStream.Capacity);
         }
 
 
@@ -401,7 +402,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             int originInStream = streamData.Offset;
             int buffCapacity = Math.Min(length, underlyingStream.Capacity - positionInStream);
             int buffLength = Math.Max(0, Math.Min(length, ((int)underlyingStream.Length) - positionInStream));
-            return new WindowsRuntimeBuffer(streamData.Array, originInStream + positionInStream, buffLength, buffCapacity);
+            return new WindowsRuntimeBuffer(streamData.Array!, originInStream + positionInStream, buffLength, buffCapacity);
         }
 
 
@@ -411,7 +412,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             if (source == null)
                 throw new ArgumentNullException(nameof(source));
 
-            byte[] dataArr;
+            byte[]? dataArr;
             int dataOffs;
             if (source.TryGetUnderlyingData(out dataArr, out dataOffs))
             {
@@ -437,7 +438,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
             if (source == null) throw new ArgumentNullException(nameof(source));
             if (source.Capacity <= byteOffset) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity, nameof(byteOffset));
 
-            byte[] srcDataArr;
+            byte[]? srcDataArr;
             int srcDataOffs;
             if (source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs))
             {
index a2d1038..ff8f1f0 100644 (file)
@@ -53,7 +53,7 @@ namespace System.Threading.Tasks
             {
                 if (_ct.CanBeCanceled && !_completing)
                 { // benign race on m_completing... it's ok if it's not up-to-date.
-                    var ctr = _ct.Register(ai => ((IAsyncInfo)ai).Cancel(), asyncInfo); // delegate cached by compiler
+                    var ctr = _ct.Register(ai => ((IAsyncInfo)ai!).Cancel(), asyncInfo); // delegate cached by compiler
 
                     // The operation may already be completing by this time, in which case
                     // we might need to dispose of our new cancellation registration here.
@@ -114,7 +114,7 @@ namespace System.Threading.Tasks
         /// <param name="asyncInfo">The asynchronous operation.</param>
         /// <param name="getResultsFunction">A function used to retrieve the TResult from the async operation; may be null.</param>
         /// <param name="asyncStatus">The status of the asynchronous operation.</param>
-        private void Complete(IAsyncInfo asyncInfo, Func<IAsyncInfo, TResult> getResultsFunction, AsyncStatus asyncStatus)
+        private void Complete(IAsyncInfo asyncInfo, Func<IAsyncInfo, TResult>? getResultsFunction, AsyncStatus asyncStatus)
         {
             if (asyncInfo == null)
                 throw new ArgumentNullException(nameof(asyncInfo));
@@ -160,7 +160,7 @@ namespace System.Threading.Tasks
 
                     // Retrieve the completion data from the IAsyncInfo.
                     TResult result = default(TResult);
-                    Exception error = null;
+                    Exception? error = null;
                     if (asyncStatus == AsyncStatus.Error)
                     {
                         error = asyncInfo.ErrorCode;
@@ -199,7 +199,7 @@ namespace System.Threading.Tasks
                         case AsyncStatus.Completed:
                             if (AsyncCausalitySupport.LoggingOn)
                                 AsyncCausalitySupport.TraceOperationCompletedSuccess(this.Task);
-                            success = base.TrySetResult(result);
+                            success = base.TrySetResult(result!);
                             break;
 
                         case AsyncStatus.Error:
index ff4afa7..6d1f215 100644 (file)
@@ -10,7 +10,7 @@ namespace System.Threading.Tasks
 {
     internal static class ExceptionDispatchHelper
     {
-        internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
+        internal static void ThrowAsync(Exception? exception, SynchronizationContext? targetContext)
         {
             if (exception == null)
                 return;
@@ -26,7 +26,7 @@ namespace System.Threading.Tasks
             {
                 try
                 {
-                    targetContext.Post((edi) => ((ExceptionDispatchInfo)edi).Throw(), exceptionDispatchInfo);
+                    targetContext.Post((edi) => ((ExceptionDispatchInfo)edi!).Throw(), exceptionDispatchInfo);
                 }
                 catch
                 {
@@ -39,7 +39,7 @@ namespace System.Threading.Tasks
             bool scheduled = true;
             try
             {
-                new SynchronizationContext().Post((edi) => ((ExceptionDispatchInfo)edi).Throw(), exceptionDispatchInfo);
+                new SynchronizationContext().Post((edi) => ((ExceptionDispatchInfo)edi!).Throw(), exceptionDispatchInfo);
             }
             catch
             {
index 6400a8a..2869fd6 100644 (file)
@@ -21,7 +21,7 @@ namespace System.Threading.Tasks
         }
 
 
-        internal TaskToAsyncActionAdapter(Task underlyingTask, CancellationTokenSource underlyingCancelTokenSource)
+        internal TaskToAsyncActionAdapter(Task underlyingTask, CancellationTokenSource? underlyingCancelTokenSource)
 
             : base(underlyingTask, underlyingCancelTokenSource, underlyingProgressDispatcher: null)
         {
index f6b13ea..6b3b8bd 100644 (file)
@@ -4,6 +4,7 @@
 
 using System;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Diagnostics.Contracts;
 using System.Runtime.ExceptionServices;
 using System.Runtime.InteropServices;
@@ -66,8 +67,7 @@ namespace System.Threading.Tasks
         // These two masks are used to clear all STATE_XXXX bits and leave any STATEFLAG_XXXX bits.
         private const int STATEMASK_CLEAR_ALL_ASYNC_STATES = ~STATEMASK_SELECT_ANY_ASYNC_STATE;
 
-
-        private static InvalidOperationException CreateCannotGetResultsFromIncompleteOperationException(Exception cause)
+        private static InvalidOperationException CreateCannotGetResultsFromIncompleteOperationException(Exception? cause)
         {
             InvalidOperationException ex = (cause == null)
                             ? new InvalidOperationException(SR.InvalidOperation_CannotGetResultsFromIncompleteOperation)
@@ -82,7 +82,7 @@ namespace System.Threading.Tasks
         #region Instance variables
 
         /// <summary>The token source used to cancel running operations.</summary>
-        private CancellationTokenSource _cancelTokenSource = null;
+        private CancellationTokenSource? _cancelTokenSource = null;
 
         /// <summary>The async info's ID. InvalidAsyncId stands for not yet been initialised.</summary>
         private uint _id = AsyncInfoIdGenerator.InvalidId;
@@ -90,7 +90,7 @@ namespace System.Threading.Tasks
         /// <summary>The cached error code used to avoid creating several exception objects if the <code>ErrorCode</code>
         /// property is accessed several times. <code>null</code> indicates either no error or that <code>ErrorCode</code>
         /// has not yet been called.</summary>
-        private Exception _error = null;
+        private Exception? _error = null;
 
         /// <summary>The state of the async info. Interlocked operations are used to manipulate this field.</summary>
         private volatile int _state = STATE_NOT_INITIALIZED;
@@ -101,16 +101,16 @@ namespace System.Threading.Tasks
         /// or to one of Task or Task{TResult} in the latter case. This approach allows us to save a field on all IAsyncInfos.
         /// Notably, this makes us pay the added cost of boxing for synchronously completing IAsyncInfos where TResult is a
         /// value type, however, this is expected to occur rather rare compared to non-synchronously completed user-IAsyncInfos.</summary>
-        private object _dataContainer;
+        private object? _dataContainer;
 
         /// <summary>Registered completed handler.</summary>
-        private TCompletedHandler _completedHandler;
+        private TCompletedHandler? _completedHandler;
 
         /// <summary>Registered progress handler.</summary>
-        private TProgressHandler _progressHandler;
+        private TProgressHandler? _progressHandler;
 
         /// <summary>The synchronization context on which this instance was created/started. Used to callback invocations.</summary>
-        private SynchronizationContext _startingContext;
+        private SynchronizationContext? _startingContext;
 
         #endregion Instance variables
 
@@ -146,7 +146,7 @@ namespace System.Threading.Tasks
 
             // Set the completion routine and let the task running:
             task.ContinueWith(
-                (_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_).TaskCompleted(),
+                (_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_!).TaskCompleted(),
                 this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
         }
 
@@ -162,7 +162,7 @@ namespace System.Threading.Tasks
         /// <param name="underlyingProgressDispatcher">A progress listener/pugblisher that receives progress notifications
         /// form <code>underlyingTask</code>.</param>
         internal TaskToAsyncInfoAdapter(Task underlyingTask,
-                                        CancellationTokenSource underlyingCancelTokenSource, Progress<TProgressInfo> underlyingProgressDispatcher)
+                                        CancellationTokenSource? underlyingCancelTokenSource, Progress<TProgressInfo>? underlyingProgressDispatcher)
         {
             if (underlyingTask == null)
                 throw new ArgumentNullException(nameof(underlyingTask));
@@ -189,7 +189,7 @@ namespace System.Threading.Tasks
             _state = (STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_STARTED);
 
             underlyingTask.ContinueWith(
-                (_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_).TaskCompleted(),
+                (_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_!).TaskCompleted(),
                 this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
         }
 
@@ -199,7 +199,7 @@ namespace System.Threading.Tasks
         /// specified <code>synchronousResult</code> is used as the result value.
         /// </summary>
         /// <param name="synchronousResult">The result of this synchronously completed IAsyncInfo.</param>
-        internal TaskToAsyncInfoAdapter(TResult synchronousResult)
+        internal TaskToAsyncInfoAdapter([AllowNull] TResult synchronousResult)
         {
             // We already completed. There will be no progress callback invokations and a potential completed handler invokation will be synchronous.
             // We do not need the starting SynchronizationContext:
@@ -342,7 +342,7 @@ namespace System.Threading.Tasks
 
         #region Infrastructure methods
 
-        private SynchronizationContext GetStartingContext()
+        private SynchronizationContext? GetStartingContext()
         {
 #if DESKTOP // as a reminder that on most platforms we want a different behavior
             return SynchronizationContext.CurrentNoFlow;
@@ -352,7 +352,7 @@ namespace System.Threading.Tasks
         }
 
 
-        internal Task Task
+        internal Task? Task
         {
             get
             {
@@ -361,12 +361,12 @@ namespace System.Threading.Tasks
                 if (CompletedSynchronously)
                     return null;
 
-                return (Task)_dataContainer;
+                return (Task?)_dataContainer;
             }
         }
 
 
-        internal CancellationTokenSource CancelTokenSource
+        internal CancellationTokenSource? CancelTokenSource
         {
             get { return _cancelTokenSource; }
         }
@@ -403,7 +403,7 @@ namespace System.Threading.Tasks
             bool conditionFailed;
 
             // Get the handler:
-            TCompletedHandler handler = Volatile.Read(ref _completedHandler);
+            TCompletedHandler? handler = Volatile.Read(ref _completedHandler);
 
             // If we might not run the handler now, we need to remember that if it is set later, it will need to be run then:
             if (handler == null)
@@ -444,7 +444,7 @@ namespace System.Threading.Tasks
             {
                 var tuple = (Tuple<TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>,
                                    TProgressHandler,
-                                   TProgressInfo>)tupleObject;
+                                   TProgressInfo>)tupleObject!;
 
                 tuple.Item1.OnProgress(tuple.Item2, tuple.Item3);
             }, Tuple.Create(this, handler, progressInfo));
@@ -456,7 +456,7 @@ namespace System.Threading.Tasks
         void IProgress<TProgressInfo>.Report(TProgressInfo value)
         {
             // If no progress handler is set, there is nothing to do:
-            TProgressHandler handler = Volatile.Read(ref _progressHandler);
+            TProgressHandler? handler = Volatile.Read(ref _progressHandler);
             if (handler == null)
                 return;
 
@@ -479,7 +479,7 @@ namespace System.Threading.Tasks
         }
 
 
-        private void OnReportChainedProgress(object sender, TProgressInfo progressInfo)
+        private void OnReportChainedProgress(object? sender, TProgressInfo progressInfo)
         {
             ((IProgress<TProgressInfo>)this).Report(progressInfo);
         }
@@ -577,7 +577,7 @@ namespace System.Threading.Tasks
             Debug.Assert(IsInRunningState);
             Debug.Assert(!CompletedSynchronously);
 
-            Task task = _dataContainer as Task;
+            Task? task = _dataContainer as Task;
             Debug.Assert(task != null);
             Debug.Assert(task.IsCompleted);
 
@@ -652,7 +652,7 @@ namespace System.Threading.Tasks
                     // Invoke callback in the right context (delegate cached by compiler):
                     _startingContext.Post((tupleObject) =>
                     {
-                        var tuple = (Tuple<TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>, AsyncStatus>)tupleObject;
+                        var tuple = (Tuple<TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>, AsyncStatus>)tupleObject!;
                         tuple.Item1.OnCompletedInvoker(tuple.Item2);
                     }, Tuple.Create(this, terminationStatus));
                 }
@@ -698,7 +698,6 @@ namespace System.Threading.Tasks
             return AsyncStatus.Error;
         }
 
-
         internal TResult GetResultsInternal()
         {
             EnsureNotClosed();
@@ -706,7 +705,7 @@ namespace System.Threading.Tasks
             // If this IAsyncInfo has actually faulted, GetResults will throw the same error as returned by ErrorCode:
             if (IsInErrorState)
             {
-                Exception error = ErrorCode;
+                Exception? error = ErrorCode;
                 Debug.Assert(error != null);
                 ExceptionDispatchInfo.Capture(error).Throw();
             }
@@ -718,16 +717,16 @@ namespace System.Threading.Tasks
 
             // If this is a synchronous operation, use the cached result:
             if (CompletedSynchronously)
-                return (TResult)_dataContainer;
+                return (TResult)_dataContainer!;
 
             // The operation is asynchronous:
-            Task<TResult> task = _dataContainer as Task<TResult>;
+            Task<TResult>? task = _dataContainer as Task<TResult>;
 
             // Since CompletedSynchronously is false and EnsureNotClosed() did not throw, task can only be null if:
             //  - this IAsyncInfo has completed synchronously, however we checked for this above;
             //  - it was not converted to Task<TResult>, which means it is a non-generic Task. In that case we cannot get a result from Task.
             if (task == null)
-                return default(TResult);
+                return default(TResult)!;
 
             Debug.Assert(IsInRunToCompletionState);
 
@@ -815,11 +814,11 @@ namespace System.Threading.Tasks
         /// If we the completion handler is set AFTER this IAsyncInfo already completed, then this setter will invoke the handler synchronously
         /// on the current context.
         /// </summary>
-        public virtual TCompletedHandler Completed
+        public virtual TCompletedHandler? Completed
         {
             get
             {
-                TCompletedHandler handler = Volatile.Read(ref _completedHandler);
+                TCompletedHandler? handler = Volatile.Read(ref _completedHandler);
                 EnsureNotClosed();
                 return handler;
             }
@@ -833,7 +832,7 @@ namespace System.Threading.Tasks
                 //  Some other WinRT projection languages do not allow setting the Completed handler more than once, even if it is set to null.
                 //  We could do the same by introducing a new STATEFLAG_COMPLETION_HNDL_SET bit-flag constant and saving a this state into
                 //  the m_state field to indicate that the completion handler has been set previously, but we choose not to do this.)
-                TCompletedHandler handlerBefore = Interlocked.CompareExchange(ref _completedHandler, value, null);
+                TCompletedHandler? handlerBefore = Interlocked.CompareExchange(ref _completedHandler, value, null);
                 if (handlerBefore != null)
                 {
                     InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_CannotSetCompletionHanlderMoreThanOnce);
@@ -864,11 +863,11 @@ namespace System.Threading.Tasks
 
 
         /// <summary>Gets or sets the progress handler.</summary>
-        public virtual TProgressHandler Progress
+        public virtual TProgressHandler? Progress
         {
             get
             {
-                TProgressHandler handler = Volatile.Read(ref _progressHandler);
+                TProgressHandler? handler = Volatile.Read(ref _progressHandler);
                 EnsureNotClosed();
 
                 return handler;
@@ -930,7 +929,7 @@ namespace System.Threading.Tasks
 
 
         /// <summary>Gets the error code for the async info.</summary>
-        public virtual Exception ErrorCode
+        public virtual Exception? ErrorCode
         {
             get
             {
@@ -942,17 +941,17 @@ namespace System.Threading.Tasks
                 if (!IsInErrorState)
                     return null;
 
-                Exception error = Volatile.Read(ref _error);
+                Exception? error = Volatile.Read(ref _error);
 
                 // ERROR is a terminal state. SO if we have an error, just return it.
                 // If we completed synchronously, we return the current error iven if it is null since we do not expect this to change:
                 if (error != null || CompletedSynchronously)
                     return error;
 
-                Task task = _dataContainer as Task;
+                Task? task = _dataContainer as Task;
                 Debug.Assert(task != null);
 
-                AggregateException aggregateException = task.Exception;
+                AggregateException? aggregateException = task.Exception;
 
                 // By spec, if task.IsFaulted is true, then task.Exception must not be null and its InnerException must
                 // also not be null. However, in case something is unexpected on the Task side of the road, let?s be defensive
@@ -965,7 +964,7 @@ namespace System.Threading.Tasks
                 }
                 else
                 {
-                    Exception innerException = aggregateException.InnerException;
+                    Exception? innerException = aggregateException.InnerException;
 
                     error = (innerException == null)
                                 ? aggregateException
@@ -974,7 +973,7 @@ namespace System.Threading.Tasks
 
                 // If m_error was set concurrently, setError will be non-null. Then we use that - as it is the first m_error
                 // that was set. If setError we know that we won any races and we can return error:
-                Exception setError = Interlocked.CompareExchange(ref _error, error, null);
+                Exception? setError = Interlocked.CompareExchange(ref _error, error, null);
                 return setError ?? error;
             }
         }
index 6292a78..63744b6 100644 (file)
@@ -4,6 +4,7 @@
 
 using System;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Threading;
 using System.Threading.Tasks;
 using Windows.Foundation;
@@ -21,20 +22,19 @@ namespace System.Threading.Tasks
         }
 
 
-        internal TaskToAsyncOperationAdapter(Task underlyingTask, CancellationTokenSource underlyingCancelTokenSource)
+        internal TaskToAsyncOperationAdapter(Task underlyingTask, CancellationTokenSource? underlyingCancelTokenSource)
 
             : base(underlyingTask, underlyingCancelTokenSource, underlyingProgressDispatcher: null)
         {
         }
 
 
-        internal TaskToAsyncOperationAdapter(TResult synchronousResult)
+        internal TaskToAsyncOperationAdapter([AllowNull] TResult synchronousResult)
 
             : base(synchronousResult)
         {
         }
 
-
         public virtual TResult GetResults()
         {
             return GetResultsInternal();
index da729f1..7a1ce71 100644 (file)
@@ -4,6 +4,7 @@
 
 using System;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Threading;
 using System.Threading.Tasks;
 using Windows.Foundation;
@@ -33,13 +34,12 @@ namespace System.Threading.Tasks
         //}
 
 
-        internal TaskToAsyncOperationWithProgressAdapter(TResult synchronousResult)
+        internal TaskToAsyncOperationWithProgressAdapter([AllowNull] TResult synchronousResult)
 
             : base(synchronousResult)
         {
         }
 
-
         public virtual TResult GetResults()
         {
             return GetResultsInternal();
index 229f6d8..da60f6a 100644 (file)
@@ -113,7 +113,7 @@ namespace System.Threading
             _dispatcher = dispatcher;
         }
 
-        public override void Post(SendOrPostCallback d, object state)
+        public override void Post(SendOrPostCallback d, object? state)
         {
             if (d == null)
                 throw new ArgumentNullException(nameof(d));
@@ -135,7 +135,7 @@ namespace System.Threading
             _dispatcherQueue = dispatcherQueue;
         }
 
-        public override void Post(SendOrPostCallback d, object state)
+        public override void Post(SendOrPostCallback d, object? state)
         {
             if (d == null)
                 throw new ArgumentNullException(nameof(d));
@@ -158,13 +158,13 @@ namespace System.Threading
 
         protected class Invoker
         {
-            private readonly ExecutionContext _executionContext;
+            private readonly ExecutionContext? _executionContext;
             private readonly SendOrPostCallback _callback;
-            private readonly object _state;
+            private readonly object? _state;
 
             private static readonly ContextCallback s_contextCallback = new ContextCallback(InvokeInContext);
 
-            public Invoker(SendOrPostCallback callback, object state)
+            public Invoker(SendOrPostCallback callback, object? state)
             {
                 _executionContext = ExecutionContext.Capture();
                 _callback = callback;
@@ -179,9 +179,9 @@ namespace System.Threading
                     ExecutionContext.Run(_executionContext, s_contextCallback, this);
             }
 
-            private static void InvokeInContext(object thisObj)
+            private static void InvokeInContext(object? thisObj)
             {
-                ((Invoker)thisObj).InvokeCore();
+                ((Invoker)thisObj!).InvokeCore();
             }
 
             private void InvokeCore()
@@ -203,7 +203,7 @@ namespace System.Threading
                         if (!ExceptionSupport.ReportUnhandledError(ex))
                         {
                             var edi = ExceptionDispatchInfo.Capture(ex);
-                            ThreadPool.QueueUserWorkItem(o => ((ExceptionDispatchInfo)o).Throw(), edi);
+                            ThreadPool.QueueUserWorkItem(o => ((ExceptionDispatchInfo)o!).Throw(), edi);
                         }
                     }
                 }
@@ -212,7 +212,7 @@ namespace System.Threading
 
         #endregion class WinRTSynchronizationContext.Invoker
 
-        public override void Send(SendOrPostCallback d, object state)
+        public override void Send(SendOrPostCallback d, object? state)
         {
             throw new NotSupportedException(SR.InvalidOperation_SendNotSupportedOnWindowsRTSynchronizationContext);
         }
index 25b3461..505b40d 100644 (file)
@@ -60,19 +60,19 @@ namespace Windows.Foundation
             return ConvertToString(null /* format string */, null /* format provider */);
         }
 
-        public string ToString(IFormatProvider provider)
+        public string ToString(IFormatProvider? provider)
         {
             // Delegate to the internal method which implements all ToString calls.
             return ConvertToString(null /* format string */, provider);
         }
 
-        string IFormattable.ToString(string format, IFormatProvider provider)
+        string IFormattable.ToString(string? format, IFormatProvider? provider)
         {
             // Delegate to the internal method which implements all ToString calls.
             return ConvertToString(format, provider);
         }
 
-        private string ConvertToString(string format, IFormatProvider provider)
+        private string ConvertToString(string? format, IFormatProvider? provider)
         {
             // Helper to get the numeric list separator for a given culture.
             char separator = TokenizerHelper.GetNumericListSeparator(provider);
@@ -94,7 +94,7 @@ namespace Windows.Foundation
             return !(point1 == point2);
         }
 
-        public override bool Equals(object o)
+        public override bool Equals(object? o)
         {
             return o is Point && this == (Point)o;
         }
index e4d6dbe..4ea7cb8 100644 (file)
@@ -281,19 +281,19 @@ namespace Windows.Foundation
             return ConvertToString(null /* format string */, null /* format provider */);
         }
 
-        public string ToString(IFormatProvider provider)
+        public string ToString(IFormatProvider? provider)
         {
             // Delegate to the internal method which implements all ToString calls.
             return ConvertToString(null /* format string */, provider);
         }
 
-        string IFormattable.ToString(string format, IFormatProvider provider)
+        string IFormattable.ToString(string? format, IFormatProvider? provider)
         {
             // Delegate to the internal method which implements all ToString calls.
             return ConvertToString(format, provider);
         }
 
-        internal string ConvertToString(string format, IFormatProvider provider)
+        internal string ConvertToString(string? format, IFormatProvider? provider)
         {
             if (IsEmpty)
             {
@@ -329,7 +329,7 @@ namespace Windows.Foundation
             return !(rect1 == rect2);
         }
 
-        public override bool Equals(object o)
+        public override bool Equals(object? o)
         {
             return o is Rect && this == (Rect)o;
         }
index b0c6cde..39e73f9 100644 (file)
@@ -103,7 +103,7 @@ namespace Windows.Foundation
             return !(size1 == size2);
         }
 
-        public override bool Equals(object o)
+        public override bool Equals(object? o)
         {
             return o is Size && Size.Equals(this, (Size)o);
         }
index 2481429..c93ce56 100644 (file)
@@ -29,7 +29,7 @@ namespace Windows.Foundation
 
     internal static class TokenizerHelper
     {
-        internal static char GetNumericListSeparator(IFormatProvider provider)
+        internal static char GetNumericListSeparator(IFormatProvider? provider)
         {
             char numericSeparator = ',';
 
index 9866532..72574c4 100644 (file)
@@ -81,19 +81,19 @@ namespace Windows.UI
             return ConvertToString(null, null);
         }
 
-        public string ToString(IFormatProvider provider)
+        public string ToString(IFormatProvider? provider)
         {
             // Delegate to the internal method which implements all ToString calls.
             return ConvertToString(null, provider);
         }
 
-        string IFormattable.ToString(string format, IFormatProvider provider)
+        string IFormattable.ToString(string? format, IFormatProvider? provider)
         {
             // Delegate to the internal method which implements all ToString calls.
             return ConvertToString(format, provider);
         }
 
-        internal string ConvertToString(string format, IFormatProvider provider)
+        internal string ConvertToString(string? format, IFormatProvider? provider)
         {
             StringBuilder sb = new StringBuilder();
 
@@ -122,7 +122,7 @@ namespace Windows.UI
             return _A.GetHashCode() ^ _R.GetHashCode() ^ _G.GetHashCode() ^ _B.GetHashCode();
         }
 
-        public override bool Equals(object o)
+        public override bool Equals(object? o)
         {
             return o is Color && this == (Color)o;
         }
index 4dadcfa..6a0f150 100644 (file)
@@ -32,10 +32,10 @@ namespace System
         {
             Debug.Assert(sink != null);
 
-            CancellationTokenRegistration ctReg = source.Register((state) => { ((CancellationTokenSource)state).Cancel(); },
+            CancellationTokenRegistration ctReg = source.Register((state) => { ((CancellationTokenSource)state!).Cancel(); },
                                                                   sink);
 
-            concatenationLifetime.ContinueWith((_, state) => { ((CancellationTokenRegistration)state).Dispose(); },
+            concatenationLifetime.ContinueWith((_, state) => { ((CancellationTokenRegistration)state!).Dispose(); },
                                                ctReg, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
         }
 
@@ -90,7 +90,7 @@ namespace System
             var wrapper = source as TaskToAsyncActionAdapter;
             if (wrapper != null && !wrapper.CompletedSynchronously)
             {
-                Task innerTask = wrapper.Task;
+                Task? innerTask = wrapper.Task;
                 Debug.Assert(innerTask != null);
                 Debug.Assert(innerTask.Status != TaskStatus.Created);
 
@@ -164,7 +164,7 @@ namespace System
             var wrapper = source as TaskToAsyncOperationAdapter<TResult>;
             if (wrapper != null && !wrapper.CompletedSynchronously)
             {
-                Task<TResult> innerTask = wrapper.Task as Task<TResult>;
+                Task<TResult>? innerTask = wrapper.Task as Task<TResult>;
                 Debug.Assert(innerTask != null);
                 Debug.Assert(innerTask.Status != TaskStatus.Created);  // Is WaitingForActivation a legal state at this moment?
 
@@ -240,7 +240,7 @@ namespace System
         /// <param name="source">The asynchronous operation.</param>
         /// <param name="progress">The progress object used to receive progress updates.</param>
         /// <returns>The Task representing the asynchronous operation.</returns>
-        public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> progress)
+        public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, IProgress<TProgress>? progress)
         {
             return AsTask(source, CancellationToken.None, progress);
         }
@@ -252,7 +252,7 @@ namespace System
         /// <param name="progress">The progress object used to receive progress updates.</param>
         /// <returns>The Task representing the asynchronous operation.</returns>
         public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source,
-                                             CancellationToken cancellationToken, IProgress<TProgress> progress)
+                                             CancellationToken cancellationToken, IProgress<TProgress>? progress)
         {
             if (source == null)
                 throw new ArgumentNullException(nameof(source));
@@ -261,7 +261,7 @@ namespace System
             var wrapper = source as TaskToAsyncActionWithProgressAdapter<TProgress>;
             if (wrapper != null && !wrapper.CompletedSynchronously)
             {
-                Task innerTask = wrapper.Task;
+                Task? innerTask = wrapper.Task;
                 Debug.Assert(innerTask != null);
                 Debug.Assert(innerTask.Status != TaskStatus.Created);  // Is WaitingForActivation a legal state at this moment?
 
@@ -347,7 +347,7 @@ namespace System
         /// <param name="progress">The progress object used to receive progress updates.</param>
         /// <returns>The Task representing the asynchronous operation.</returns>
         public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
-                                                               IProgress<TProgress> progress)
+                                                               IProgress<TProgress>? progress)
         {
             return AsTask(source, CancellationToken.None, progress);
         }
@@ -359,7 +359,7 @@ namespace System
         /// <param name="progress">The progress object used to receive progress updates.</param>
         /// <returns>The Task representing the asynchronous operation.</returns>
         public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
-                                                               CancellationToken cancellationToken, IProgress<TProgress> progress)
+                                                               CancellationToken cancellationToken, IProgress<TProgress>? progress)
         {
             if (source == null)
                 throw new ArgumentNullException(nameof(source));
@@ -368,7 +368,7 @@ namespace System
             var wrapper = source as TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>;
             if (wrapper != null && !wrapper.CompletedSynchronously)
             {
-                Task<TResult> innerTask = wrapper.Task as Task<TResult>;
+                Task<TResult>? innerTask = wrapper.Task as Task<TResult>;
                 Debug.Assert(innerTask != null);
                 Debug.Assert(innerTask.Status != TaskStatus.Created);  // Is WaitingForActivation a legal state at this moment?
 
@@ -446,14 +446,14 @@ namespace System
         {
             // This method is an aid for NGen to save common generic
             // instantiations into the ngen image.
-            ((IAsyncOperation<bool>)null).AsTask();
-            ((IAsyncOperation<string>)null).AsTask();
-            ((IAsyncOperation<object>)null).AsTask();
-            ((IAsyncOperation<uint>)null).AsTask();
-
-            ((IAsyncOperationWithProgress<uint, uint>)null).AsTask();
-            ((IAsyncOperationWithProgress<ulong, ulong>)null).AsTask();
-            ((IAsyncOperationWithProgress<string, ulong>)null).AsTask();
+            ((IAsyncOperation<bool>)null!).AsTask();
+            ((IAsyncOperation<string>)null!).AsTask();
+            ((IAsyncOperation<object>)null!).AsTask();
+            ((IAsyncOperation<uint>)null!).AsTask();
+
+            ((IAsyncOperationWithProgress<uint, uint>)null!).AsTask();
+            ((IAsyncOperationWithProgress<ulong, ulong>)null!).AsTask();
+            ((IAsyncOperationWithProgress<string, ulong>)null!).AsTask();
         }
     }  // class WindowsRuntimeSystemExtensions
 }  // namespace
index cad3f23..09da728 100644 (file)
@@ -11,7 +11,7 @@ namespace Internal.Resources
     {
         public abstract bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo? exceptionInfo);
 
-        public abstract string GetString(string stringName, string? startingCulture, string? neutralResourcesCulture);
+        public abstract string? GetString(string stringName, string? startingCulture, string? neutralResourcesCulture);
 
         public abstract CultureInfo? GlobalResourceContextBestFitCultureInfo
         {
index 34812bb..dcc2dc8 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System;
+using System.Diagnostics.CodeAnalysis;
 
 namespace Internal.Runtime.InteropServices.WindowsRuntime
 {
@@ -12,6 +13,7 @@ namespace Internal.Runtime.InteropServices.WindowsRuntime
         /// Attach restricted error information to the exception if it may apply to that exception, returning
         /// back the input value
         /// </summary>
+        [return: NotNullIfNotNull("e")]
         public static Exception? AttachRestrictedErrorInfo(Exception? e) => throw new PlatformNotSupportedException();
 
         /// <summary>